1 /*
2  * Copyright (c) 2021 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "time_helper.h"
17 
18 #include "db_errno.h"
19 #include "log_print.h"
20 #include "platform_specific.h"
21 
22 namespace DistributedDB {
23 std::mutex TimeHelper::systemTimeLock_;
24 Timestamp TimeHelper::lastSystemTimeUs_ = 0;
25 Timestamp TimeHelper::currentIncCount_ = 0;
26 std::atomic<Timestamp> TimeHelper::lastMonotonicTime_ = 0;
27 
GetSysCurrentTime()28 Timestamp TimeHelper::GetSysCurrentTime()
29 {
30     uint64_t curTime = 0;
31     std::lock_guard<std::mutex> lock(systemTimeLock_);
32     int errCode = OS::GetCurrentSysTimeInMicrosecond(curTime);
33     if (errCode != E_OK) {
34         return INVALID_TIMESTAMP;
35     }
36 
37     // If GetSysCurrentTime in 1us, we need increase the currentIncCount_
38     if (curTime == lastSystemTimeUs_) {
39         // if the currentIncCount_ has been increased MAX_INC_COUNT, keep the currentIncCount_
40         if (currentIncCount_ < MAX_INC_COUNT) {
41             currentIncCount_++;
42         }
43     } else {
44         lastSystemTimeUs_ = curTime;
45         currentIncCount_ = 0;
46     }
47     return (curTime * TO_100_NS) + currentIncCount_; // Currently Timestamp is uint64_t
48 }
49 
GetSysCurrentRawTime(uint64_t & curTime)50 int TimeHelper::GetSysCurrentRawTime(uint64_t &curTime)
51 {
52     int errCode = OS::GetCurrentSysTimeInMicrosecond(curTime);
53     if (errCode != 0) {
54         return errCode;
55     }
56     if (curTime > (UINT64_MAX / TO_100_NS)) {
57         LOGD("curTime is too large %" PRIu64, curTime);
58         return -E_OUT_OF_DATE;
59     }
60     curTime *= TO_100_NS;
61     return E_OK;
62 }
63 
TimeHelper()64 TimeHelper::TimeHelper()
65     : storage_(nullptr),
66       metadata_(nullptr)
67 {
68 }
69 
~TimeHelper()70 TimeHelper::~TimeHelper()
71 {
72     metadata_ = nullptr;
73     storage_ = nullptr;
74 }
75 
Initialize(const ISyncInterface * inStorage,const std::shared_ptr<Metadata> & inMetadata)76 int TimeHelper::Initialize(const ISyncInterface *inStorage, const std::shared_ptr<Metadata> &inMetadata)
77 {
78     if ((inStorage == nullptr) || (inMetadata == nullptr)) {
79         return -E_INVALID_ARGS;
80     }
81     metadata_ = inMetadata;
82     storage_ = inStorage;
83     Timestamp currentSysTime = GetSysCurrentTime();
84     TimeOffset localTimeOffset = GetLocalTimeOffset();
85     Timestamp maxItemTime = GetMaxDataItemTime();
86     if (currentSysTime > MAX_VALID_TIME || maxItemTime > MAX_VALID_TIME) {
87         return -E_INVALID_TIME;
88     }
89     Timestamp virtualSysTime = static_cast<Timestamp>(currentSysTime + localTimeOffset);
90     if (virtualSysTime <= maxItemTime || virtualSysTime > BUFFER_VALID_TIME) {
91         localTimeOffset = static_cast<TimeOffset>(maxItemTime - currentSysTime + MS_TO_100_NS); // 1ms
92         int errCode = SaveLocalTimeOffset(localTimeOffset);
93         if (errCode != E_OK) {
94             LOGE("[TimeHelper] save local time offset failed,err=%d", errCode);
95             return errCode;
96         }
97     }
98     lastMonotonicTime_ = GetMonotonicTime();
99     metadata_->SetLastLocalTime(currentSysTime + static_cast<Timestamp>(localTimeOffset));
100     return E_OK;
101 }
102 
GetTime()103 Timestamp TimeHelper::GetTime()
104 {
105     Timestamp currentSysTime = GetSysCurrentTime();
106     TimeOffset localTimeOffset = GetLocalTimeOffset();
107     Timestamp currentLocalTime = currentSysTime + static_cast<Timestamp>(localTimeOffset);
108     Timestamp lastLocalTime = metadata_->GetLastLocalTime();
109     Timestamp currentMonotonicTime = GetMonotonicTime();
110     Timestamp deltaTime = 1UL;
111     if (currentMonotonicTime != INVALID_TIMESTAMP && lastMonotonicTime_ != INVALID_TIMESTAMP) {
112         deltaTime = currentMonotonicTime - lastMonotonicTime_;
113     }
114     lastMonotonicTime_ = currentMonotonicTime;
115     if (currentLocalTime <= lastLocalTime || currentLocalTime > BUFFER_VALID_TIME) {
116         lastLocalTime += deltaTime;
117         currentLocalTime = lastLocalTime;
118         metadata_->SetLastLocalTime(lastLocalTime);
119     } else {
120         metadata_->SetLastLocalTime(currentLocalTime);
121     }
122     return currentLocalTime;
123 }
124 
GetMaxDataItemTime()125 Timestamp TimeHelper::GetMaxDataItemTime()
126 {
127     Timestamp timestamp = 0;
128     storage_->GetMaxTimestamp(timestamp);
129     return timestamp;
130 }
131 
GetLocalTimeOffset() const132 TimeOffset TimeHelper::GetLocalTimeOffset() const
133 {
134     return metadata_->GetLocalTimeOffset();
135 }
136 
SaveLocalTimeOffset(TimeOffset offset)137 int TimeHelper::SaveLocalTimeOffset(TimeOffset offset)
138 {
139     return metadata_->SaveLocalTimeOffset(offset);
140 }
141 
SetSendConfig(const std::string & dstTarget,bool nonBlock,uint32_t timeout,SendConfig & sendConf)142 void TimeHelper::SetSendConfig(const std::string &dstTarget, bool nonBlock, uint32_t timeout, SendConfig &sendConf)
143 {
144     SetSendConfigParam(storage_->GetDbProperties(), dstTarget, false, SEND_TIME_OUT, sendConf);
145 }
146 
GetMonotonicTime()147 Timestamp TimeHelper::GetMonotonicTime()
148 {
149     Timestamp time = INVALID_TIMESTAMP;
150     int errCode = OS::GetMonotonicRelativeTimeInMicrosecond(time);
151     if (errCode != E_OK) {
152         LOGE("GetMonotonicTime ERR! errCode = %d", errCode);
153     }
154     return time;
155 }
156 } // namespace DistributedDB
157