-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsystimemgr.cpp
More file actions
937 lines (856 loc) · 32.2 KB
/
systimemgr.cpp
File metadata and controls
937 lines (856 loc) · 32.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
/*
* Copyright 2023 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "systimemgr.h"
#include <stdlib.h>
#include <vector>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include "timerfactory.h"
#include <memory>
#include <sys/inotify.h>
#include <limits.h>
#include "irdklog.h"
#include "itimermsg.h"
#include <chrono>
#include "secure_wrapper.h"
#if !defined(MILESTONE_SUPPORT_DISABLED)
#include "rdk_logger_milestone.h"
#endif
#if defined(GTEST_ENABLE) || defined(__LOCAL_TEST_)
#include "systimerfactory/unittest/mocks/libchronyctl.h"
#else
#include "libchronyctl.h"
#endif
#include "systimerfactory/networkstatussrc.h"
#include <sys/timex.h>
#include <fcntl.h>
#ifdef T2_EVENT_ENABLED
#include <telemetry_busmessage_sender.h>
#endif
using namespace std::chrono;
SysTimeMgr* SysTimeMgr::pInstance = NULL;
recursive_mutex SysTimeMgr::g_state_mutex;
mutex SysTimeMgr::g_instance_mutex;
SysTimeMgr* SysTimeMgr::get_instance()
{
if(!pInstance)
{
std::lock_guard<std::mutex> guard(g_instance_mutex);
if(!pInstance)
{
pInstance = new SysTimeMgr;
RDK_LOG(RDK_LOG_DEBUG,LOG_SYSTIME,"[%s:%d]:Created New Instance \n",__FUNCTION__,__LINE__);
}
}
return pInstance;
}
SysTimeMgr::SysTimeMgr (string cfgfile):m_state(eSYSMGR_STATE_INIT),
m_event(eSYSMGR_EVENT_UNKNOWN),
m_timerInterval(600000),
m_timequality(eTIMEQUALILTY_UNKNOWN),
m_publish(NULL),
m_subscriber(NULL),
m_tmrsubscriber(NULL),
m_timersrc("Last Known"),
m_cfgfile(std::move(cfgfile)),
m_chronyRfcEnabled(access("/opt/secure/RFC/chrony/chronyd_enabled", F_OK) == 0)
{
}
SysTimeMgr::~SysTimeMgr()
{
if (m_chronyRfcEnabled) {
chronyctl_cleanup();
}
}
void SysTimeMgr::initialize()
{
std::lock_guard<std::recursive_mutex> guard(g_state_mutex);
#ifdef T2_EVENT_ENABLED
t2_init((char *) "sysTimeMgr");
#endif
//Create Timer Src and Syncs.
ifstream cfgFile(m_cfgfile.c_str());
if (cfgFile.is_open())
{
string category,type,objargs;
while(cfgFile>>category>>type>>objargs)
{
RDK_LOG(RDK_LOG_INFO,LOG_SYSTIME,"[%s:%d]:Initializing Src and Syncs. Category = %s, Type = %s, Args = %s.\n",__FUNCTION__,__LINE__,category.c_str(),type.c_str(),objargs.c_str());
if (category == "timesrc")
{
m_timerSrc.push_back(createTimeSrc(type,m_directory + objargs));
}
else if (category == "timesync")
{
m_timerSync.push_back(createTimeSync(type,m_directory + objargs));
}
}
cfgFile.close();
}
else
{
RDK_LOG(RDK_LOG_ERROR,LOG_SYSTIME,"[%s:%d]:Failed to open Config file: %s , will run in degraded mode.\n",__FUNCTION__,__LINE__,m_cfgfile.c_str());
}
if(m_chronyRfcEnabled) {
RDK_LOG(RDK_LOG_INFO,LOG_SYSTIME,"[%s:%d]:[ChronyCTL] Initialize ChronyCTL library\n",__FUNCTION__,__LINE__);
int chronyctl_ret = chronyctl_init();
if (chronyctl_ret != CHRONYCTL_SUCCESS) {
RDK_LOG(RDK_LOG_ERROR, LOG_SYSTIME, "[ChronyCTL] Initialization failed: rc=%d, error=%s\n",
chronyctl_ret, chronyctl_strerror(chronyctl_ret));
}
}
//m_timerSrc.push_back(createTimeSrc("regular","/tmp/clock.txt"));
//m_timerSync.push_back(createTimeSync("test","/tmp/clock1.txt"));
#if !defined(IARM_SUPPORT_DISABLED)
m_publish = createPublish("iarm",IARM_BUS_SYSTIME_MGR_NAME);
RDK_LOG(RDK_LOG_INFO,LOG_SYSTIME,"[%s:%d]:createSubscriber IARM_BUS_SYSTIME_MGR_NAME TIMER_STATUS_MSG Invoke\n",__FUNCTION__,__LINE__);
m_tmrsubscriber = createSubscriber("iarm",IARM_BUS_SYSTIME_MGR_NAME,TIMER_STATUS_MSG);
RDK_LOG(RDK_LOG_INFO,LOG_SYSTIME,"[%s:%d]:createSubscriber IARM_BUS_SYSTIME_MGR_NAME POWER_CHANGE_MSG Invoke\n",__FUNCTION__,__LINE__);
m_subscriber = createSubscriber("iarm",IARM_BUS_SYSTIME_MGR_NAME,POWER_CHANGE_MSG);
RDK_LOG(RDK_LOG_INFO,LOG_SYSTIME,"[%s:%d]:IarmTimerStatusSubscriber Invoke \n",__FUNCTION__,__LINE__);
m_tmrsubscriber->subscribe(TIMER_STATUS_MSG,SysTimeMgr::getTimeStatus);
RDK_LOG(RDK_LOG_INFO,LOG_SYSTIME,"[%s:%d]:IpowerControllerSubscriber or IarmPowerSubscriber Invoke \n",__FUNCTION__,__LINE__);
m_subscriber->subscribe(POWER_CHANGE_MSG,SysTimeMgr::powerhandler);
#else
m_publish = createPublish("test",IARM_BUS_SYSTIME_MGR_NAME);
RDK_LOG(RDK_LOG_INFO,LOG_SYSTIME,"[%s:%d]:createSubscriber IARM_BUS_SYSTIME_MGR_NAME TIMER_STATUS_MSG Invoke\n",__FUNCTION__,__LINE__);
m_tmrsubscriber = createSubscriber("test",IARM_BUS_SYSTIME_MGR_NAME,TIMER_STATUS_MSG);
RDK_LOG(RDK_LOG_INFO,LOG_SYSTIME,"[%s:%d]:createSubscriber IARM_BUS_SYSTIME_MGR_NAME POWER_CHANGE_MSG Invoke\n",__FUNCTION__,__LINE__);
m_subscriber = createSubscriber("test",IARM_BUS_SYSTIME_MGR_NAME,POWER_CHANGE_MSG);
RDK_LOG(RDK_LOG_INFO,LOG_SYSTIME,"[%s:%d]:IarmTimerStatusSubscriber Invoke \n",__FUNCTION__,__LINE__);
m_tmrsubscriber->subscribe(TIMER_STATUS_MSG,SysTimeMgr::getTimeStatus);
RDK_LOG(RDK_LOG_INFO,LOG_SYSTIME,"[%s:%d]:IpowerControllerSubscriber or IarmPowerSubscriber Invoke \n",__FUNCTION__,__LINE__);
m_subscriber->subscribe(POWER_CHANGE_MSG,SysTimeMgr::powerhandler);
#endif
//Initialize Path Event Map
m_pathEventMap.insert(pair<string,sysTimeMgrEvent>("ntp",eSYSMGR_EVENT_NTP_AVAILABLE));
//Keeping the NTP available event for stt as well. Source is different but no need to have separate event.
m_pathEventMap.insert(pair<string,sysTimeMgrEvent>("stt",eSYSMGR_EVENT_NTP_AVAILABLE));
m_pathEventMap.insert(pair<string,sysTimeMgrEvent>("drm",eSYSMGR_EVENT_SECURE_TIME_AVAILABLE));
m_pathEventMap.insert(pair<string,sysTimeMgrEvent>("dtt",eSYSMGR_EVENT_DTT_TIME_AVAILABLE));
//Initialize time from the sync.
setInitialTime();
//Initialize state machine.
stateMachine[eSYSMGR_STATE_RUNNING][eSYSMGR_EVENT_TIMER_EXPIRY] = &SysTimeMgr::timerExpiry;
stateMachine[eSYSMGR_STATE_NTP_WAIT][eSYSMGR_EVENT_TIMER_EXPIRY] = &SysTimeMgr::ntpFailed;
stateMachine[eSYSMGR_STATE_NTP_WAIT][eSYSMGR_EVENT_NTP_AVAILABLE] = &SysTimeMgr::ntpAquired;
stateMachine[eSYSMGR_STATE_NTP_WAIT][eSYSMGR_EVENT_SECURE_TIME_AVAILABLE] = &SysTimeMgr::secureTimeAcquired;
stateMachine[eSYSMGR_STATE_NTP_ACQUIRED][eSYSMGR_EVENT_SECURE_TIME_AVAILABLE] = &SysTimeMgr::updateSecureTime;
stateMachine[eSYSMGR_STATE_NTP_ACQUIRED][eSYSMGR_EVENT_TIMER_EXPIRY] = &SysTimeMgr::updateTime;
stateMachine[eSYSMGR_STATE_NTP_FAIL][eSYSMGR_EVENT_DTT_TIME_AVAILABLE] = &SysTimeMgr::dttAquired;
stateMachine[eSYSMGR_STATE_NTP_FAIL][eSYSMGR_EVENT_TIMER_EXPIRY] = &SysTimeMgr::updateTime;
stateMachine[eSYSMGR_STATE_NTP_FAIL][eSYSMGR_EVENT_NTP_AVAILABLE] = &SysTimeMgr::ntpAquired;
stateMachine[eSYSMGR_STATE_NTP_FAIL][eSYSMGR_EVENT_SECURE_TIME_AVAILABLE] = &SysTimeMgr::secureTimeAcquired;
stateMachine[eSYSMGR_STATE_DTT_ACQUIRED][eSYSMGR_EVENT_TIMER_EXPIRY] = &SysTimeMgr::updateClockRealTime;
stateMachine[eSYSMGR_STATE_DTT_ACQUIRED][eSYSMGR_EVENT_SECURE_TIME_AVAILABLE] = &SysTimeMgr::secureTimeAcquired;
stateMachine[eSYSMGR_STATE_DTT_ACQUIRED][eSYSMGR_EVENT_NTP_AVAILABLE] = &SysTimeMgr::ntpAquired;
stateMachine[eSYSMGR_STATE_SECURE_TIME_ACQUIRED][eSYSMGR_EVENT_NTP_AVAILABLE] = &SysTimeMgr::updateSecureTime;
stateMachine[eSYSMGR_STATE_SECURE_TIME_ACQUIRED][eSYSMGR_EVENT_TIMER_EXPIRY] = &SysTimeMgr::updateTime;
m_state = eSYSMGR_STATE_NTP_WAIT;
}
void SysTimeMgr::runStateMachine(sysTimeMgrEvent event,void* args)
{
RDK_LOG(RDK_LOG_DEBUG,LOG_SYSTIME,"[%s:%d]:Entered State Machine: Event = %d \n",__FUNCTION__,__LINE__,event);
std::lock_guard<std::recursive_mutex> guard(g_state_mutex);
map<sysTimeMgrState,map<sysTimeMgrEvent,memfunc> >::const_iterator iter = stateMachine.find(m_state);
if ((iter != stateMachine.end()) && (iter->second.find(event) != iter->second.end()))
{
m_event = event;
(this->*stateMachine[m_state][event])(args);
}
else
{
RDK_LOG(RDK_LOG_INFO,LOG_SYSTIME,"[%s:%d]:There is no Event Processing available in this state. State = %d, Event = %d \n",__FUNCTION__,__LINE__,m_state,event);
}
}
void SysTimeMgr::run(bool forever)
{
//1. create thread
//2. if selected to run forever wait till thread dies.
std::thread processThrd(SysTimeMgr::processThr,this);
std::thread timerThrd(SysTimeMgr::timerThr,this);
std::thread pathMonitorThrd(SysTimeMgr::pathThr,this);
RDK_LOG(RDK_LOG_INFO,LOG_SYSTIME,"[%s:%d]:RFC chronyd_enabled file %s\n",
__FUNCTION__,__LINE__,
m_chronyRfcEnabled ? "found, starting network event threads"
: "not found, skipping network event threads");
std::thread nwEventProcessThrd;
std::thread nwEventSubscribeThrd;
std::thread ntpSyncMonitorThrd;
if (m_chronyRfcEnabled) {
/* nwEventProcessThrd must start before nwEventSubscribeThrd so the
* processing thread is ready before any event can arrive. */
nwEventProcessThrd = std::thread(SysTimeMgr::nwEventProcessThr, this);
nwEventSubscribeThrd = std::thread(SysTimeMgr::nwEventSubscribeThr, this);
ntpSyncMonitorThrd = std::thread(SysTimeMgr::ntpSyncMonitorThr,this);
}
if (forever)
{
ofstream pidfile("/run/systimemgr.pid",ios::out);
if (pidfile.is_open())
{
pidfile<<getpid()<<"\n";
pidfile.close();
}
processThrd.join();
timerThrd.join();
pathMonitorThrd.join();
if (nwEventProcessThrd.joinable()) {
nwEventProcessThrd.join();
}
if (nwEventSubscribeThrd.joinable()) {
nwEventSubscribeThrd.join();
}
if (ntpSyncMonitorThrd.joinable()) {
ntpSyncMonitorThrd.join();
}
}
else
{
processThrd.detach();
timerThrd.detach();
pathMonitorThrd.detach();
if (nwEventProcessThrd.joinable()) {
nwEventProcessThrd.detach();
}
if (nwEventSubscribeThrd.joinable()) {
nwEventSubscribeThrd.detach();
}
if (ntpSyncMonitorThrd.joinable()) {
ntpSyncMonitorThrd.detach();
}
}
}
void SysTimeMgr::processThr(SysTimeMgr* instance)
{
if (instance)
{
instance->processMsg();
}
}
void SysTimeMgr::timerThr(SysTimeMgr* instance)
{
if (instance)
{
instance->runTimer();
}
}
void SysTimeMgr::pathThr(SysTimeMgr* instance)
{
if (instance)
{
instance->runPathMonitor();
}
}
/* nwEventSubscribeThr: subscribes to NetworkManager events (retries until success). */
void SysTimeMgr::nwEventSubscribeThr(SysTimeMgr* instance)
{
if (instance)
instance->runNetworkStatusMonitor();
}
/* nwEventProcessThr: waits for internet-up signals and runs chrony sync commands. */
void SysTimeMgr::nwEventProcessThr(SysTimeMgr* instance)
{
if (instance)
instance->runNWEventProcessing();
}
void SysTimeMgr::ntpSyncMonitorThr(SysTimeMgr* instance)
{
if (instance)
instance->runNTPSyncMonitor();
}
/*
* runNTPSyncMonitor: polls adjtimex() once per second until the kernel clock is
* synchronised with NTP (STA_UNSYNC flag cleared). On success it logs the
* event, creates /tmp/clock-event and /tmp/systimemgr/ntp, then returns.
* The primary purpose is to capture the NTP convergence time.
*/
void SysTimeMgr::runNTPSyncMonitor()
{
RDK_LOG(RDK_LOG_INFO, LOG_SYSTIME,
"[%s:%d]: CHRONY: NTP sync monitor thread started\n", __FUNCTION__, __LINE__);
while (1)
{
struct timex tx;
memset(&tx, 0, sizeof(tx));
/* Capture adjtimex() return value: TIME_ERROR means the kernel clock
* is not disciplined, which is treated the same as STA_UNSYNC. */
int adjtimex_state = adjtimex(&tx);
if (adjtimex_state < 0)
{
RDK_LOG(RDK_LOG_ERROR, LOG_SYSTIME,
"[%s:%d]: CHRONY: adjtimex() failed, retrying\n", __FUNCTION__, __LINE__);
std::this_thread::sleep_for(std::chrono::seconds(1));
continue;
}
if (adjtimex_state == TIME_ERROR || (tx.status & STA_UNSYNC))
{
/* Clock not yet synchronised — keep polling. */
std::this_thread::sleep_for(std::chrono::seconds(1));
continue;
}
/* NTP synchronisation achieved. */
RDK_LOG(RDK_LOG_INFO, LOG_SYSTIME,
"[%s:%d]: CHRONY: NTP synchronised\n", __FUNCTION__, __LINE__);
/* Create /tmp/systimemgr/ntp and update its timestamps via futimens()
* so that the inotify IN_ATTRIB event fires and the path monitor thread
* reliably dispatches eSYSMGR_EVENT_NTP_AVAILABLE into the state machine.
* O_NOFOLLOW|O_CLOEXEC guard against symlink attacks. */
{
int fd = open((m_directory + "/ntp").c_str(),
O_CREAT | O_WRONLY | O_NOFOLLOW | O_CLOEXEC | O_NOCTTY, 0644);
if (fd >= 0)
{
struct timespec ts[2];
timespec_get(&ts[0], TIME_UTC);
ts[1] = ts[0];
if (futimens(fd, ts) != 0)
RDK_LOG(RDK_LOG_ERROR, LOG_SYSTIME,
"[%s:%d]: futimens() failed for %s/ntp\n",
__FUNCTION__, __LINE__, m_directory.c_str());
close(fd);
}
else
RDK_LOG(RDK_LOG_ERROR, LOG_SYSTIME,
"[%s:%d]: Failed to create %s/ntp\n",
__FUNCTION__, __LINE__, m_directory.c_str());
}
/* Create /tmp/clock-event — O_NOFOLLOW|O_CLOEXEC guard against
* symlink/hardlink attacks when running with elevated privileges. */
{
int fd = open("/tmp/clock-event",
O_CREAT | O_WRONLY | O_NOFOLLOW | O_CLOEXEC, 0644);
if (fd >= 0)
close(fd);
else
RDK_LOG(RDK_LOG_ERROR, LOG_SYSTIME,
"[%s:%d]: Failed to create /tmp/clock-event\n",
__FUNCTION__, __LINE__);
}
/* Write NTP sync status to /tmp/ntp_status — O_NOFOLLOW|O_CLOEXEC
* guards against symlink attacks; write() return value is checked. */
{
int fd = open("/tmp/ntp_status",
O_CREAT | O_WRONLY | O_TRUNC | O_NOFOLLOW | O_CLOEXEC, 0644);
if (fd >= 0)
{
const char* status = "Synchronized\n";
ssize_t written = write(fd, status, strlen(status));
if (written < 0)
RDK_LOG(RDK_LOG_ERROR, LOG_SYSTIME,
"[%s:%d]: Failed to write to /tmp/ntp_status\n",
__FUNCTION__, __LINE__);
close(fd);
}
else
{
RDK_LOG(RDK_LOG_ERROR, LOG_SYSTIME,
"[%s:%d]: Failed to create /tmp/ntp_status\n",
__FUNCTION__, __LINE__);
}
}
double offset = 0.0;
int ret = chronyctl_get_offset(&offset);
if (ret == CHRONYCTL_SUCCESS) {
char offset_str[16];
RDK_LOG(RDK_LOG_INFO, LOG_SYSTIME, "[ChronyCTL] Offset: %f seconds\n", offset);
snprintf(offset_str, sizeof(offset_str), "%.3f", offset);
#ifdef T2_EVENT_ENABLED
t2ValNotify((char *) "SYST_INFO_NTP_DELTA_split",offset_str);
#endif
} else {
RDK_LOG(RDK_LOG_ERROR, LOG_SYSTIME, "[ChronyCTL] Error fetching offset: %s\n", chronyctl_strerror(ret));
}
/* Synchronisation captured — stop polling. */
break;
}
RDK_LOG(RDK_LOG_INFO, LOG_SYSTIME,
"[%s:%d]: CHRONY: NTP sync monitor thread exiting\n", __FUNCTION__, __LINE__);
}
void SysTimeMgr::processMsg()
{
while (1)
{
unique_lock<std::mutex> lk(m_queue_mutex);
while (m_queue.empty())
{
m_cond_var.wait(lk); // release lock and go join the waiting thread queue
}
//sysTimeMsg* val = m_queue.front();
unique_ptr<sysTimeMsg> val = move(m_queue.front());
m_queue.pop();
runStateMachine(val->m_event,val->m_args);
//delete val;
}
}
void SysTimeMgr::runTimer()
{
while (1)
{
std::this_thread::sleep_for(std::chrono::milliseconds(m_timerInterval));
if (m_chronyRfcEnabled)
{
double offset = 0.0;
int ret = chronyctl_get_offset(&offset);
if (ret == CHRONYCTL_SUCCESS) {
char offset_str[16];
RDK_LOG(RDK_LOG_INFO, LOG_SYSTIME, "[ChronyCTL] Offset: %f seconds\n", offset);
snprintf(offset_str, sizeof(offset_str), "%.3f", offset);
#ifdef T2_EVENT_ENABLED
t2ValNotify((char *) "SYST_INFO_NTP_DELTA_split",offset_str);
#endif
} else {
RDK_LOG(RDK_LOG_ERROR, LOG_SYSTIME, "[ChronyCTL] Error fetching offset: %s\n", chronyctl_strerror(ret));
}
}
sendMessage(eSYSMGR_EVENT_TIMER_EXPIRY,NULL);
}
}
void SysTimeMgr::runPathMonitor()
{
//Send out events oif the file already exists.
//This will take care of cases where the program has to restart.
for (auto iter = m_pathEventMap.begin();iter != m_pathEventMap.end();++iter)
{
string fname = m_directory + "/" + iter->first;
ifstream f(fname.c_str());
if (f.good())
{
sendMessage(iter->second,NULL);
}
f.close();
}
int inotifyFd, wd;
inotifyFd = inotify_init();
if (inotifyFd == -1)
{
RDK_LOG(RDK_LOG_ERROR,LOG_SYSTIME,"[%s:%d]: Unable to create inotifyfd. Exiting thread \n",__FUNCTION__,__LINE__);
return;
}
wd = inotify_add_watch(inotifyFd, m_directory.c_str(), IN_DELETE|IN_MODIFY|IN_ATTRIB);
if (wd == -1)
{
RDK_LOG(RDK_LOG_ERROR,LOG_SYSTIME,"[%s:%d]:Unable to create Watchi descriptor. Exiting thread \n",__FUNCTION__,__LINE__);
return;
}
char buffer[sizeof(struct inotify_event) + NAME_MAX + 1];
while (1)
{
ssize_t count = read(inotifyFd, buffer, sizeof(buffer));
if (count < 0)
{
RDK_LOG(RDK_LOG_ERROR,LOG_SYSTIME,"[%s:%d]:Failed to read. Exiting \n",__FUNCTION__,__LINE__);
return;
}
buffer[sizeof(buffer)- 1] = '\0';
struct inotify_event * pevent = reinterpret_cast<struct inotify_event *>(buffer);
if (pevent->mask & IN_ATTRIB)
{
//This is file changed or created.
RDK_LOG(RDK_LOG_INFO,LOG_SYSTIME,"[%s:%d]:File created/modified = %s \n",__FUNCTION__,__LINE__,pevent->name);
string fName(pevent->name);
auto iter = m_pathEventMap.find(fName);
if (iter != m_pathEventMap.end())
{
RDK_LOG(RDK_LOG_DEBUG,LOG_SYSTIME,"[%s:%d]:FOUND EVENT = %d \n",__FUNCTION__,__LINE__,iter->second);
sendMessage(iter->second,NULL);
}
}
}
}
static NetworkStatusSrc networkStatusMonitor;
void SysTimeMgr::runNetworkStatusMonitor()
{
RDK_LOG(RDK_LOG_INFO,LOG_SYSTIME,"[%s:%d]:CHRONY: Starting network status subscription thread\n",__FUNCTION__,__LINE__);
networkStatusMonitor.subscribeInternetStatusEvent();
}
void SysTimeMgr::runNWEventProcessing()
{
/* This function runs on nwEventProcessThrd — call runEventProcessingLoop()
* directly, it blocks until shutdown. No inner thread needed. */
RDK_LOG(RDK_LOG_INFO,LOG_SYSTIME,"[%s:%d]:CHRONY: Network event processing thread running\n",__FUNCTION__,__LINE__);
networkStatusMonitor.runEventProcessingLoop();
}
void SysTimeMgr::updateTime(void* args)
{
updateTimeSync(0);
for (auto const& it : m_timerSrc)
{
it->checkTime();
}
}
void SysTimeMgr::ntpFailed(void* args)
{
updateTimeSync(0);
m_state = eSYSMGR_STATE_NTP_FAIL;
publishStatus(ePUBLISH_NTP_FAIL,"Poor");
}
void SysTimeMgr::ntpAquired(void* args)
{
updateTimeSync(0);
//Publish NTP AVAILABLE Notification.
m_timequality = eTIMEQUALILTY_GOOD;
m_state = eSYSMGR_STATE_NTP_ACQUIRED;
m_timersrc = "NTP";
publishStatus(ePUBLISH_NTP_SUCCESS,"Good");
}
void SysTimeMgr::updateSecureTime(void* args)
{
timerExpiry(args);
m_state = eSYSMGR_STATE_RUNNING;
m_timequality = eTIMEQUALILTY_SECURE;
publishStatus(ePUBLISH_SECURE_TIME_SUCCESS,"Secure");
}
void SysTimeMgr::secureTimeAcquired(void* args)
{
updateTimeSync(0);
m_timequality = eTIMEQUALILTY_GOOD;
m_state = eSYSMGR_STATE_SECURE_TIME_ACQUIRED;
}
void SysTimeMgr::dttAquired(void* args)
{
updateTimeSync(0);
m_timequality = eTIMEQUALILTY_GOOD;
m_state = eSYSMGR_STATE_DTT_ACQUIRED;
m_timersrc = "DTT";
publishStatus(ePUBLISH_DTT_SUCCESS,"Good");
}
void SysTimeMgr::timerExpiry(void* args)
{
RDK_LOG(RDK_LOG_DEBUG,LOG_SYSTIME,"[%s:%d]:Entered Function \n",__FUNCTION__,__LINE__);
long long reftime = 0,filetime = 0,updateTime =0;
for (auto const& it : m_timerSrc)
{
if (it->isreference())
{
reftime = it->getTimeSec();
}
else
{
long long tempTime = it->getTimeSec();
if (tempTime != 0)
{
filetime = tempTime;
}
else
{
RDK_LOG(RDK_LOG_DEBUG,LOG_SYSTIME,"[%s:%d]:TimeSrc Returned Zero! \n",__FUNCTION__,__LINE__);
}
}
}
if ((reftime - filetime) <= 600)
{
updateTime = reftime;
}
updateTimeSync(updateTime);
}
void SysTimeMgr::updateTimeSync(long long updateTime)
{
for (auto const& i : m_timerSync)
{
i->updateTime(updateTime);
}
}
void SysTimeMgr::sendMessage(sysTimeMgrEvent event, void* args)
{
unique_lock<std::mutex> lk(m_queue_mutex);
//sysTimeMsg* ptr = new sysTimeMsg(event,args);
unique_ptr<sysTimeMsg> ptr(new sysTimeMsg(event,args));
m_queue.push(move(ptr));
lk.unlock();
m_cond_var.notify_one();
}
void SysTimeMgr::setInitialTime()
{
long long locTime = 0;
struct timespec stime;
string filepath = "/tmp/systimeset";
for (auto const& i : m_timerSync)
{
locTime = i->getTime();
}
ofstream ofs(filepath);
if (!ofs)
{
RDK_LOG(RDK_LOG_ERROR,LOG_SYSTIME,"[%s:%d]:Failed to create file(%s)\n",__FUNCTION__,__LINE__,filepath.c_str());
}
else
{
ofs.close();
RDK_LOG(RDK_LOG_INFO,LOG_SYSTIME,"[%s:%d]:Successfully created file (%s) to trigger systime-set target\n",__FUNCTION__,__LINE__,filepath.c_str());
}
if (locTime == 0)
{
RDK_LOG(RDK_LOG_ERROR,LOG_SYSTIME,"[%s:%d]:Returning from Setting initial time since localtime returned from timersync is zero \n",__FUNCTION__,__LINE__);
return;
}
struct timespec ts;
long long currenttime = 0;
m_timequality = eTIMEQUALILTY_POOR;
if (clock_gettime(CLOCK_REALTIME, &ts) == 0)
{
auto duration = seconds{ts.tv_sec} + nanoseconds{ts.tv_nsec};
currenttime = static_cast<long long>(system_clock::to_time_t(time_point<system_clock, seconds>(duration_cast<seconds>(duration))));
RDK_LOG(RDK_LOG_INFO,LOG_SYSTIME,"[%s:%d]: Clock_gettime Call succeeded with REAL time.\n",__FUNCTION__,__LINE__);
if (currenttime > locTime)
{
RDK_LOG(RDK_LOG_INFO,LOG_SYSTIME,"[%s:%d]: Clock Time is greater that time provided by Timesync, leaving it alone.\n",__FUNCTION__,__LINE__);
publishStatus(ePUBLISH_TIME_INITIAL,"Poor");
return;
}
}
stime.tv_sec = locTime;
stime.tv_nsec = 0;
if (clock_settime( CLOCK_REALTIME, &stime) != 0)
{
RDK_LOG(RDK_LOG_ERROR,LOG_SYSTIME,"[%s:%d]:Failed to set time \n",__FUNCTION__,__LINE__);
#ifdef T2_EVENT_ENABLED
t2CountNotify((char *) "SYST_ERROR_SYSTIME_FAIL",1);
#endif
}
else
{
char str[32];
struct timespec uptime;
unsigned long long uptimems;
RDK_LOG(RDK_LOG_INFO,LOG_SYSTIME,"[%s:%d]:Successfully to set time \n",__FUNCTION__,__LINE__);
#if !defined(MILESTONE_SUPPORT_DISABLED)
logMilestone("SYSTEM_TIME_SET");
#endif
if (clock_gettime(CLOCK_REALTIME, &uptime) == 0) {
uptimems = (unsigned long long)uptime.tv_sec * 1000 + uptime.tv_nsec / 1000000;
snprintf(str, sizeof(str), "%llu", uptimems);
#ifdef T2_EVENT_ENABLED
t2ValNotify((char *) "SYST_INFO_SETSYSTIME_split",str);
#endif
}
}
publishStatus(ePUBLISH_TIME_INITIAL,"Poor");
}
void SysTimeMgr::publishStatus(publishEvent event,string message)
{
TimerMsg msg;
msg.event = event;
msg.quality = m_timequality;
memset(msg.message,'\0',cTIMER_STATUS_MESSAGE_LENGTH);
snprintf(msg.message, cTIMER_STATUS_MESSAGE_LENGTH, "%s", message.c_str()); //CID:277715 Buffer not null terminated
snprintf(msg.timerSrc, cTIMER_STATUS_MESSAGE_LENGTH, "%s", m_timersrc.c_str()); //CID:277715 Buffer not null terminated
using namespace std::chrono;
//time_t timeinSec = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
time_t timeinSec = time(NULL);
struct timespec ts;
if (clock_gettime(CLOCK_REALTIME, &ts) == 0) {
auto duration = std::chrono::seconds{ts.tv_sec} + std::chrono::nanoseconds{ts.tv_nsec};
timeinSec = system_clock::to_time_t(time_point<system_clock, seconds>(duration_cast<seconds>(duration)));
RDK_LOG(RDK_LOG_INFO,LOG_SYSTIME,"[%s:%d]: clock_gettime Call succeeded with REAL time.\n",__FUNCTION__,__LINE__);
}
time_t monotimeinSec = time(NULL);
char timeStr[100] = {0};
char monotimeStr[100] = {0};
strftime(timeStr, sizeof(timeStr), "%A %c", localtime(&timeinSec));
strftime(monotimeStr, sizeof(monotimeStr), "%A %c", localtime(&monotimeinSec));
RDK_LOG(RDK_LOG_INFO,LOG_SYSTIME,"[%s:%d]:TIME Published = %ld, Converted Real Time(included in published time): %s, Converted Monotonic Time = %s \n",__FUNCTION__,__LINE__,timeinSec,timeStr,monotimeStr);
snprintf(msg.currentTime, cTIMER_STATUS_MESSAGE_LENGTH, "%s", std::to_string(timeinSec).c_str()); //CID:277715 Buffer not null terminated
m_publish->publish(cTIMER_STATUS_UPDATE,&msg);
}
int SysTimeMgr::getTimeStatus(void* args)
{
TimerMsg* pMsg = reinterpret_cast<TimerMsg*>(args);
SysTimeMgr* pInstance = get_instance();
if (pInstance != NULL)
{
pInstance->getTimeStatus(pMsg);
}
return 0;
}
void SysTimeMgr::getTimeStatus(TimerMsg* pMsg)
{
std::lock_guard<std::recursive_mutex> guard(g_state_mutex);
pMsg->quality = m_timequality;
memset(pMsg->message,'\0',cTIMER_STATUS_MESSAGE_LENGTH);
string populatedString;
switch (m_timequality)
{
case eTIMEQUALILTY_POOR:
{
populatedString = "Poor";
break;
}
case eTIMEQUALILTY_GOOD:
{
populatedString = "Good";
break;
}
case eTIMEQUALILTY_SECURE:
{
populatedString = "Secure";
break;
}
default:
{
populatedString = "Unknown";
break;
}
}
snprintf(pMsg->message, cTIMER_STATUS_MESSAGE_LENGTH, "%s", populatedString.c_str()); //CID:277708 Buffer not null terminated
snprintf(pMsg->timerSrc, cTIMER_STATUS_MESSAGE_LENGTH, "%s", m_timersrc.c_str()); //CID:277708 Buffer not null terminated
using namespace std::chrono;
//time_t timeinSec = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
time_t timeinSec = time(NULL);
struct timespec ts;
if (clock_gettime(CLOCK_REALTIME, &ts) == 0) {
auto duration = seconds{ts.tv_sec} + nanoseconds{ts.tv_nsec};
timeinSec = system_clock::to_time_t(time_point<system_clock, seconds>(duration_cast<seconds>(duration)));
RDK_LOG(RDK_LOG_INFO,LOG_SYSTIME,"[%s:%d]: Clock_gettime Call succeeded with REAL time.\n",__FUNCTION__,__LINE__);
}
time_t monotimeinSec = time(NULL);
char timeStr[100] = {0};
char monotimeStr[100] = {0};
strftime(timeStr, sizeof(timeStr), "%A %c", localtime(&timeinSec));
strftime(monotimeStr, sizeof(monotimeStr), "%A %c", localtime(&monotimeinSec));
RDK_LOG(RDK_LOG_INFO,LOG_SYSTIME,"[%s:%d]:TIME Returning for Query = %ld, Converted Real Time(included in TimeMsg): %s, Converted Monotonic Time = %s \n",__FUNCTION__,__LINE__,timeinSec,timeStr,monotimeStr);
snprintf(pMsg->currentTime, cTIMER_STATUS_MESSAGE_LENGTH, "%s", std::to_string(timeinSec).c_str()); //CID:277708 Buffer not null terminated
}
int SysTimeMgr::powerhandler(void* args)
{
RDK_LOG(RDK_LOG_INFO,LOG_SYSTIME,"[%s:%d]:Entering Power Change Event \n",__FUNCTION__,__LINE__);
string* message = reinterpret_cast<string*>(args);
SysTimeMgr* pInstance = get_instance();
if (pInstance == NULL) {
return 0;
}
if (*message == "DEEP_SLEEP_ON") {
pInstance->deepsleepon();
}
if (*message == "DEEP_SLEEP_OFF") {
pInstance->deepsleepoff();
}
return 1;
}
void SysTimeMgr::deepsleepoff()
{
//Reset State Machine
RDK_LOG(RDK_LOG_INFO,LOG_SYSTIME,"[%s:%d]:Deep Sleep is Turned off. Resetting State Machine and restarting ntp service. \n",__FUNCTION__,__LINE__);
std::string message;
{
std::lock_guard<std::recursive_mutex> guard(g_state_mutex);
if (m_timequality == eTIMEQUALILTY_SECURE) {
m_timequality = eTIMEQUALILTY_GOOD;
m_state = eSYSMGR_STATE_NTP_ACQUIRED;
}
string message;
m_timersrc = "Last Known";
switch (m_timequality)
{
case eTIMEQUALILTY_POOR:
{
message = "Poor";
break;
}
case eTIMEQUALILTY_GOOD:
{
message = "Good";
break;
}
case eTIMEQUALILTY_SECURE:
{
message = "Secure";
break;
}
default:
{
message = "Unknown";
break;
}
}
publishStatus(ePUBLISH_DEEP_SLEEP_ON,std::move(message));
}
//Turn on the NTP time sync.
int ret = v_secure_system("/bin/systemctl is-active --quiet systemd-timesyncd.service");
if (ret == 0) {
// timesyncd is running
RDK_LOG(RDK_LOG_INFO,LOG_SYSTIME,"[%s:%d]:systemd-timesyncd is active, restarting service\n",__FUNCTION__,__LINE__);
v_secure_system("/bin/systemctl reset-failed systemd-timesyncd.service");
v_secure_system("/bin/systemctl restart systemd-timesyncd.service");
} else {
// timesyncd not active, check chronyd
ret = v_secure_system("/bin/systemctl is-active --quiet chronyd.service");
if (ret == 0) {
// chronyd is running
RDK_LOG(RDK_LOG_INFO,LOG_SYSTIME,"[%s:%d]:chronyd is active, performing chronyctl_burst\n",__FUNCTION__,__LINE__);
ret = chronyctl_burst(NULL, NULL, 4, 6);
if (ret == CHRONYCTL_SUCCESS) {
RDK_LOG(RDK_LOG_INFO,LOG_SYSTIME,"[%s:%d]: [ChronyCTL] burst succeeded\n",__FUNCTION__,__LINE__);
} else {
RDK_LOG(RDK_LOG_WARN,LOG_SYSTIME,"[%s:%d]:[ChronyCTL] burst failed: %s\n",__FUNCTION__,__LINE__, chronyctl_strerror(ret));
}
// Wait for chronyd to synchronize with at least 1 source, for up to 20 tries.
RDK_LOG(RDK_LOG_INFO,LOG_SYSTIME,"[%s:%d]:chronyd is active, waiting for source selection\n",__FUNCTION__,__LINE__);
ret = chronyctl_waitsync(20,1);
if (ret != CHRONYCTL_SUCCESS) {
RDK_LOG(RDK_LOG_ERROR,LOG_SYSTIME,"[%s:%d]:[ChronyCTL] waitsync failed: %s\n",__FUNCTION__,__LINE__, chronyctl_strerror(ret));
}
RDK_LOG(RDK_LOG_INFO,LOG_SYSTIME,"[%s:%d]:chronyd is active, performing chronyctl_makestep\n",__FUNCTION__,__LINE__);
ret = chronyctl_makestep();
if (ret == CHRONYCTL_SUCCESS) {
RDK_LOG(RDK_LOG_INFO, LOG_SYSTIME, "[%s:%d]: [ChronyCTL] makestep succeeded\n", __FUNCTION__, __LINE__);
} else {
RDK_LOG(RDK_LOG_WARN, LOG_SYSTIME, "[%s:%d]: [ChronyCTL] makestep failed: ret=%d, error=%s\n", __FUNCTION__, __LINE__, ret, chronyctl_strerror(ret));
}
} else {
RDK_LOG(RDK_LOG_WARN,LOG_SYSTIME,"[%s:%d]:Neither systemd-timesyncd nor chronyd is running, skipping time sync actions.\n",__FUNCTION__,__LINE__);
}
}
}
void SysTimeMgr::deepsleepon()
{
//Turn on the NTP time sync.
RDK_LOG(RDK_LOG_INFO,LOG_SYSTIME,"[%s:%d]:Deep Sleep is turned on.\n",__FUNCTION__,__LINE__);
}
void SysTimeMgr::updateClockRealTime(void* args)
{
long long locTime = 0;
struct timespec stime;
bool clock_acquired = false;
for (auto const& i : m_timerSrc)
{
if (i->isclockProvider() && !clock_acquired) {
locTime = i->getTimeSec();
clock_acquired = true;
}
i->checkTime();
}
if (locTime != 0) {
stime.tv_sec = locTime;
stime.tv_nsec = 0;
if (clock_settime( CLOCK_REALTIME, &stime) != 0) {
RDK_LOG(RDK_LOG_ERROR,LOG_SYSTIME,"[%s:%d]:Failed to set time \n",__FUNCTION__,__LINE__);
}
else {
RDK_LOG(RDK_LOG_INFO,LOG_SYSTIME,"[%s:%d]:Successfully to set time \n",__FUNCTION__,__LINE__);
}
}
else {
RDK_LOG(RDK_LOG_ERROR,LOG_SYSTIME,"[%s:%d]:Time is not available to Set. Skipping Clock_settime. \n",__FUNCTION__,__LINE__);
}
updateTimeSync(0);
}