1 /* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
3 #include "icinga/timeperiod.hpp"
4 #include "icinga/timeperiod-ti.cpp"
5 #include "icinga/legacytimeperiod.hpp"
6 #include "base/configtype.hpp"
7 #include "base/objectlock.hpp"
8 #include "base/exception.hpp"
9 #include "base/logger.hpp"
10 #include "base/timer.hpp"
11 #include "base/utility.hpp"
12 #include <boost/thread/once.hpp>
14 using namespace icinga;
16 REGISTER_TYPE(TimePeriod);
18 static Timer::Ptr l_UpdateTimer;
20 void TimePeriod::Start(bool runtimeCreated)
22 ObjectImpl<TimePeriod>::Start(runtimeCreated);
24 static boost::once_flag once = BOOST_ONCE_INIT;
26 boost::call_once(once, [this]() {
27 l_UpdateTimer = new Timer();
28 l_UpdateTimer->SetInterval(300);
29 l_UpdateTimer->OnTimerExpired.connect(std::bind(&TimePeriod::UpdateTimerHandler));
30 l_UpdateTimer->Start();
33 /* Pre-fill the time period for the next 24 hours. */
34 double now = Utility::GetTime();
35 UpdateRegion(now, now + 24 * 3600, true);
41 void TimePeriod::AddSegment(double begin, double end)
45 Log(LogDebug, "TimePeriod")
46 << "Adding segment '" << Utility::FormatDateTime("%c", begin) << "' <-> '"
47 << Utility::FormatDateTime("%c", end) << "' to TimePeriod '" << GetName() << "'";
49 if (GetValidBegin().IsEmpty() || begin < GetValidBegin())
52 if (GetValidEnd().IsEmpty() || end > GetValidEnd())
55 Array::Ptr segments = GetSegments();
58 /* Try to merge the new segment into an existing segment. */
59 ObjectLock dlock(segments);
60 for (const Dictionary::Ptr& segment : segments) {
61 if (segment->Get("begin") <= begin && segment->Get("end") >= end)
62 return; /* New segment is fully contained in this segment. */
64 if (segment->Get("begin") >= begin && segment->Get("end") <= end) {
65 segment->Set("begin", begin);
66 segment->Set("end", end); /* Extend an existing segment to both sides */
70 if (segment->Get("end") >= begin && segment->Get("end") <= end) {
71 segment->Set("end", end); /* Extend an existing segment to right. */
75 if (segment->Get("begin") >= begin && segment->Get("begin") <= end) {
76 segment->Set("begin", begin); /* Extend an existing segment to left. */
83 /* Create new segment if we weren't able to merge this into an existing segment. */
84 Dictionary::Ptr segment = new Dictionary({
90 segments = new Array();
91 SetSegments(segments);
94 segments->Add(segment);
97 void TimePeriod::AddSegment(const Dictionary::Ptr& segment)
99 AddSegment(segment->Get("begin"), segment->Get("end"));
102 void TimePeriod::RemoveSegment(double begin, double end)
106 Log(LogDebug, "TimePeriod")
107 << "Removing segment '" << Utility::FormatDateTime("%c", begin) << "' <-> '"
108 << Utility::FormatDateTime("%c", end) << "' from TimePeriod '" << GetName() << "'";
110 if (GetValidBegin().IsEmpty() || begin < GetValidBegin())
111 SetValidBegin(begin);
113 if (GetValidEnd().IsEmpty() || end > GetValidEnd())
116 Array::Ptr segments = GetSegments();
121 Array::Ptr newSegments = new Array();
123 /* Try to split or adjust an existing segment. */
124 ObjectLock dlock(segments);
125 for (const Dictionary::Ptr& segment : segments) {
126 /* Fully contained in the specified range? */
127 if (segment->Get("begin") >= begin && segment->Get("end") <= end)
128 // Don't add the old segment, because the segment is fully contained into our range
131 /* Not overlapping at all? */
132 if (segment->Get("end") < begin || segment->Get("begin") > end) {
133 newSegments->Add(segment);
138 if (segment->Get("begin") < begin && segment->Get("end") > end) {
139 newSegments->Add(new Dictionary({
140 { "begin", segment->Get("begin") },
144 newSegments->Add(new Dictionary({
146 { "end", segment->Get("end") }
148 // Don't add the old segment, because we have now two new segments and a gap between
152 /* Adjust the begin/end timestamps so as to not overlap with the specified range. */
153 if (segment->Get("begin") > begin && segment->Get("begin") < end)
154 segment->Set("begin", end);
156 if (segment->Get("end") > begin && segment->Get("end") < end)
157 segment->Set("end", begin);
159 newSegments->Add(segment);
162 SetSegments(newSegments);
169 void TimePeriod::RemoveSegment(const Dictionary::Ptr& segment)
171 RemoveSegment(segment->Get("begin"), segment->Get("end"));
174 void TimePeriod::PurgeSegments(double end)
178 Log(LogDebug, "TimePeriod")
179 << "Purging segments older than '" << Utility::FormatDateTime("%c", end)
180 << "' from TimePeriod '" << GetName() << "'";
182 if (GetValidBegin().IsEmpty() || end < GetValidBegin())
187 Array::Ptr segments = GetSegments();
192 Array::Ptr newSegments = new Array();
194 /* Remove old segments. */
195 ObjectLock dlock(segments);
196 for (const Dictionary::Ptr& segment : segments) {
197 if (segment->Get("end") >= end)
198 newSegments->Add(segment);
201 SetSegments(newSegments);
204 void TimePeriod::Merge(const TimePeriod::Ptr& timeperiod, bool include)
206 Log(LogDebug, "TimePeriod")
207 << "Merge TimePeriod '" << GetName() << "' with '" << timeperiod->GetName() << "' "
208 << "Method: " << (include ? "include" : "exclude");
210 Array::Ptr segments = timeperiod->GetSegments();
213 ObjectLock dlock(segments);
214 ObjectLock ilock(this);
215 for (const Dictionary::Ptr& segment : segments) {
216 include ? AddSegment(segment) : RemoveSegment(segment);
221 void TimePeriod::UpdateRegion(double begin, double end, bool clearExisting)
224 SetSegments(new Array());
226 if (begin < GetValidEnd())
227 begin = GetValidEnd();
229 if (end < GetValidEnd())
233 Array::Ptr segments = GetUpdate()->Invoke({ this, begin, end });
236 ObjectLock olock(this);
237 RemoveSegment(begin, end);
240 ObjectLock dlock(segments);
241 for (const Dictionary::Ptr& segment : segments) {
247 bool preferInclude = GetPreferIncludes();
249 /* First handle the non preferred timeranges */
250 Array::Ptr timeranges = preferInclude ? GetExcludes() : GetIncludes();
253 ObjectLock olock(timeranges);
254 for (const String& name : timeranges) {
255 const TimePeriod::Ptr timeperiod = TimePeriod::GetByName(name);
258 Merge(timeperiod, !preferInclude);
262 /* Preferred timeranges must be handled at the end */
263 timeranges = preferInclude ? GetIncludes() : GetExcludes();
266 ObjectLock olock(timeranges);
267 for (const String& name : timeranges) {
268 const TimePeriod::Ptr timeperiod = TimePeriod::GetByName(name);
271 Merge(timeperiod, preferInclude);
276 bool TimePeriod::GetIsInside() const
278 return IsInside(Utility::GetTime());
281 bool TimePeriod::IsInside(double ts) const
283 ObjectLock olock(this);
285 if (GetValidBegin().IsEmpty() || ts < GetValidBegin() || GetValidEnd().IsEmpty() || ts > GetValidEnd())
286 return true; /* Assume that all invalid regions are "inside". */
288 Array::Ptr segments = GetSegments();
291 ObjectLock dlock(segments);
292 for (const Dictionary::Ptr& segment : segments) {
293 if (ts > segment->Get("begin") && ts < segment->Get("end"))
301 double TimePeriod::FindNextTransition(double begin)
303 ObjectLock olock(this);
305 Array::Ptr segments = GetSegments();
307 double closestTransition = -1;
310 ObjectLock dlock(segments);
311 for (const Dictionary::Ptr& segment : segments) {
312 if (segment->Get("begin") > begin && (segment->Get("begin") < closestTransition || closestTransition == -1))
313 closestTransition = segment->Get("begin");
315 if (segment->Get("end") > begin && (segment->Get("end") < closestTransition || closestTransition == -1))
316 closestTransition = segment->Get("end");
320 return closestTransition;
323 void TimePeriod::UpdateTimerHandler()
325 double now = Utility::GetTime();
327 for (const TimePeriod::Ptr& tp : ConfigType::GetObjectsByType<TimePeriod>()) {
334 ObjectLock olock(tp);
335 tp->PurgeSegments(now - 3600);
337 valid_end = tp->GetValidEnd();
340 tp->UpdateRegion(valid_end, now + 24 * 3600, false);
347 void TimePeriod::Dump()
349 Array::Ptr segments = GetSegments();
351 Log(LogDebug, "TimePeriod")
352 << "Dumping TimePeriod '" << GetName() << "'";
354 Log(LogDebug, "TimePeriod")
355 << "Valid from '" << Utility::FormatDateTime("%c", GetValidBegin())
356 << "' until '" << Utility::FormatDateTime("%c", GetValidEnd());
359 ObjectLock dlock(segments);
360 for (const Dictionary::Ptr& segment : segments) {
361 Log(LogDebug, "TimePeriod")
362 << "Segment: " << Utility::FormatDateTime("%c", segment->Get("begin")) << " <-> "
363 << Utility::FormatDateTime("%c", segment->Get("end"));
367 Log(LogDebug, "TimePeriod", "---");
370 void TimePeriod::ValidateRanges(const Lazy<Dictionary::Ptr>& lvalue, const ValidationUtils& utils)
375 /* create a fake time environment to validate the definitions */
376 time_t refts = Utility::GetTime();
377 tm reference = Utility::LocalTime(refts);
378 Array::Ptr segments = new Array();
380 ObjectLock olock(lvalue());
381 for (const Dictionary::Pair& kv : lvalue()) {
385 LegacyTimePeriod::ParseTimeRange(kv.first, &begin_tm, &end_tm, &stride, &reference);
386 } catch (const std::exception& ex) {
387 BOOST_THROW_EXCEPTION(ValidationError(this, { "ranges" }, "Invalid time specification '" + kv.first + "': " + ex.what()));
391 LegacyTimePeriod::ProcessTimeRanges(kv.second, &reference, segments);
392 } catch (const std::exception& ex) {
393 BOOST_THROW_EXCEPTION(ValidationError(this, { "ranges" }, "Invalid time range definition '" + kv.second + "': " + ex.what()));