-
Notifications
You must be signed in to change notification settings - Fork 378
/
MaintenanceManager.cpp
1851 lines (1641 loc) · 77.2 KB
/
MaintenanceManager.cpp
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
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* If not stated otherwise in this file or this component's LICENSE
* file the following copyright and licenses apply:
*
* Copyright 2021 RDK Management
*
* 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.
**/
/**
* @file MaintenanceManager.cpp
* @author Livin Sunny
* @brief Thunder Plugin based Implementation for RDK MaintenanceManager service API's.
* @reference RDK-29959.
*/
#include <stdlib.h>
#include <errno.h>
#include <cstdio>
#include <regex>
#include <fstream>
#include <string>
#include <vector>
#include <map>
#include <sstream>
#include <ctime>
#include <iomanip>
#include <bits/stdc++.h>
#include <algorithm>
#include <array>
#include <unistd.h>
#include "MaintenanceManager.h"
#include "UtilsIarm.h"
#include "UtilsJsonRpc.h"
#include "UtilscRunScript.h"
#include "UtilsfileExists.h"
enum eRetval { E_NOK = -1,
E_OK };
#if defined(USE_IARMBUS) || defined(USE_IARM_BUS)
#include "libIARM.h"
#endif /* USE_IARMBUS || USE_IARM_BUS */
#ifdef ENABLE_DEVICE_MANUFACTURER_INFO
#include "mfrMgr.h"
#endif
#ifdef ENABLE_DEEP_SLEEP
#include "deepSleepMgr.h"
#endif
#include "maintenanceMGR.h"
using namespace std;
#define API_VERSION_NUMBER_MAJOR 1
#define API_VERSION_NUMBER_MINOR 0
#define API_VERSION_NUMBER_PATCH 36
#define SERVER_DETAILS "127.0.0.1:9998"
#define PROC_DIR "/proc"
#define MAINTENANCE_MANAGER_RFC_CALLER_ID "MaintenanceManager"
#define TR181_AUTOREBOOT_ENABLE "Device.DeviceInfo.X_RDKCENTRAL-COM_RFC.Feature.AutoReboot.Enable"
#define TR181_STOP_MAINTENANCE "Device.DeviceInfo.X_RDKCENTRAL-COM_RFC.Feature.StopMaintenance.Enable"
#define TR181_RDKVFWUPGRADER "Device.DeviceInfo.X_RDKCENTRAL-COM_RFC.Feature.RDKFirmwareUpgrader.Enable"
#if defined(ENABLE_WHOAMI)
#define TR181_PARTNER_ID "Device.DeviceInfo.X_RDKCENTRAL-COM_RFC.Bootstrap.PartnerName"
#define TR181_TARGET_OS_CLASS "Device.DeviceInfo.X_RDKCENTRAL-COM_RFC.Bootstrap.OsClass"
#define TR181_XCONFURL "Device.DeviceInfo.X_RDKCENTRAL-COM_RFC.Bootstrap.XconfUrl"
#endif /* WhoAmI */
#define INTERNET_CONNECTED_STATE 3
string notifyStatusToString(Maint_notify_status_t &status)
{
string ret_status="";
switch(status){
case MAINTENANCE_IDLE:
ret_status="MAINTENANCE_IDLE";
break;
case MAINTENANCE_STARTED:
ret_status="MAINTENANCE_STARTED";
break;
case MAINTENANCE_ERROR:
ret_status="MAINTENANCE_ERROR";
break;
case MAINTENANCE_COMPLETE:
ret_status="MAINTENANCE_COMPLETE";
break;
case MAINTENANCE_INCOMPLETE:
ret_status="MAINTENANCE_INCOMPLETE";
break;
default:
ret_status="MAINTENANCE_ERROR";
}
return ret_status;
}
bool checkValidOptOutModes(string OptoutModes){
vector<string> modes{
"ENFORCE_OPTOUT",
"BYPASS_OPTOUT",
"IGNORE_UPDATE",
"NONE"
};
if ( find( modes.begin(), modes.end(), OptoutModes) != modes.end() ){
return true;
}
else {
return false;
}
}
string moduleStatusToString(IARM_Maint_module_status_t &status)
{
string ret_status="";
switch(status){
case MAINT_DCM_COMPLETE:
ret_status="MAINTENANCE_DCM_COMPLETE";
break;
case MAINT_DCM_ERROR:
ret_status="MAINTENANCE_DCM_ERROR";
break;
case MAINT_RFC_COMPLETE:
ret_status="MAINTENANCE_RFC_COMPLETE";
break;
case MAINT_RFC_ERROR:
ret_status="MAINTENANCE_RFC_ERROR";
break;
case MAINT_LOGUPLOAD_COMPLETE:
ret_status="MAINTENANCE_LOGUPLOAD_COMPLETE";
break;
case MAINT_LOGUPLOAD_ERROR:
ret_status="MAINTENANCE_LOGUPLOAD_ERROR";
break;
case MAINT_PINGTELEMETRY_COMPLETE:
ret_status="MAINTENANCE_PINGTELEMETRY_COMPLETE";
break;
case MAINT_PINGTELEMETRY_ERROR:
ret_status="MAINTENANCE_PINGTELEMETRY_ERROR";
break;
case MAINT_FWDOWNLOAD_COMPLETE:
ret_status="MAINTENANCE_FWDOWNLOAD_COMPLETE";
break;
case MAINT_FWDOWNLOAD_ERROR:
ret_status="MAINTENANCE_FWDOWNLOAD_ERROR";
break;
case MAINT_REBOOT_REQUIRED:
ret_status="MAINTENANCE_REBOOT_REQUIRED";
break;
case MAINT_FWDOWNLOAD_ABORTED:
ret_status="MAINTENANCE_FWDOWNLOAD_ABORTED";
break;
case MAINT_CRITICAL_UPDATE:
ret_status="MAINTENANCE_CRITICAL_UPDATE";
break;
default:
ret_status="MAINTENANCE_EMPTY";
}
return ret_status;
}
/**
* @brief WPEFramework class for Maintenance Manager
*/
namespace WPEFramework {
namespace {
static Plugin::Metadata<Plugin::MaintenanceManager> metadata(
// Version (Major, Minor, Patch)
API_VERSION_NUMBER_MAJOR, API_VERSION_NUMBER_MINOR, API_VERSION_NUMBER_PATCH,
// Preconditions
{},
// Terminations
{},
// Controls
{}
);
}
namespace Plugin {
namespace {
// MaintenanceManager should use interfaces
uint32_t getServiceState(PluginHost::IShell* shell, const string& callsign, PluginHost::IShell::state& state)
{
uint32_t result;
auto interface = shell->QueryInterfaceByCallsign<PluginHost::IShell>(callsign);
if (interface == nullptr) {
result = Core::ERROR_UNAVAILABLE;
std::cout << "no IShell for " << callsign << std::endl;
} else {
result = Core::ERROR_NONE;
state = interface->State();
std::cout << "IShell state " << state << " for " << callsign << std::endl;
interface->Release();
}
return result;
}
}
//Prototypes
SERVICE_REGISTRATION(MaintenanceManager, API_VERSION_NUMBER_MAJOR, API_VERSION_NUMBER_MINOR, API_VERSION_NUMBER_PATCH);
/* Global time variable */
MaintenanceManager* MaintenanceManager::_instance = nullptr;
cSettings MaintenanceManager::m_setting(MAINTENANCE_MGR_RECORD_FILE);
string task_names_foreground[]={
"/lib/rdk/StartDCM_maintaince.sh",
"/lib/rdk/RFCbase.sh",
"/lib/rdk/swupdate_utility.sh >> /opt/logs/swupdate.log",
"/lib/rdk/Start_uploadSTBLogs.sh"
};
vector<string> tasks;
string script_names[]={
"DCMscript_maintaince.sh",
"RFCbase.sh",
"swupdate_utility.sh",
"uploadSTBLogs.sh"
};
static const array<string, 3> kDeviceInitContextKeyVals = {
"partnerId",
"osClass",
"regionalConfigService"
};
/**
* Register MaintenanceManager module as wpeframework plugin
*/
MaintenanceManager::MaintenanceManager()
:PluginHost::JSONRPC()
{
MaintenanceManager::_instance = this;
if (Utils::directoryExists(MAINTENANCE_MGR_RECORD_FILE))
{
std::cout << "File " << MAINTENANCE_MGR_RECORD_FILE << " detected as folder, deleting.." << std::endl;
if (rmdir(MAINTENANCE_MGR_RECORD_FILE) == 0)
{
cSettings mtemp(MAINTENANCE_MGR_RECORD_FILE);
MaintenanceManager::m_setting = mtemp;
}
else
{
std::cout << "Unable to delete folder: " << MAINTENANCE_MGR_RECORD_FILE << std::endl;
}
}
/**
* @brief Invoking Plugin API register to WPEFRAMEWORK.
*/
#ifdef DEBUG
Register("sampleMaintenanceManagerAPI", &MaintenanceManager::sampleAPI, this);
#endif /* DEBUG */
Register("getMaintenanceActivityStatus", &MaintenanceManager::getMaintenanceActivityStatus,this);
Register("getMaintenanceStartTime", &MaintenanceManager::getMaintenanceStartTime,this);
Register("setMaintenanceMode", &MaintenanceManager::setMaintenanceMode,this);
Register("startMaintenance", &MaintenanceManager::startMaintenance,this);
Register("stopMaintenance", &MaintenanceManager::stopMaintenance,this);
Register("getMaintenanceMode", &MaintenanceManager::getMaintenanceMode,this);
MaintenanceManager::m_task_map[task_names_foreground[0].c_str()]=false;
MaintenanceManager::m_task_map[task_names_foreground[1].c_str()]=false;
MaintenanceManager::m_task_map[task_names_foreground[2].c_str()]=false;
MaintenanceManager::m_task_map[task_names_foreground[3].c_str()]=false;
#if defined(ENABLE_WHOAMI)
MaintenanceManager::m_param_map[kDeviceInitContextKeyVals[0].c_str()] = TR181_PARTNER_ID;
MaintenanceManager::m_param_map[kDeviceInitContextKeyVals[1].c_str()] = TR181_TARGET_OS_CLASS;
MaintenanceManager::m_param_map[kDeviceInitContextKeyVals[2].c_str()] = TR181_XCONFURL;
MaintenanceManager::m_paramType_map[kDeviceInitContextKeyVals[0].c_str()] = DATA_TYPE::WDMP_STRING;
MaintenanceManager::m_paramType_map[kDeviceInitContextKeyVals[1].c_str()] = DATA_TYPE::WDMP_STRING;
MaintenanceManager::m_paramType_map[kDeviceInitContextKeyVals[2].c_str()] = DATA_TYPE::WDMP_STRING;
#endif /* WhoAmI */
}
void MaintenanceManager::task_execution_thread(){
uint8_t i=0;
string cmd="";
bool internetConnectStatus=false;
bool delayMaintenanceStarted = false;
std::unique_lock<std::mutex> wailck(m_waiMutex);
LOGINFO("Executing Maintenance tasks");
#if defined(ENABLE_WHOAMI)
/* Purposefully delaying MAINTENANCE_STARTED status to honor POWER compliance */
if (UNSOLICITED_MAINTENANCE == g_maintenance_type) {
delayMaintenanceStarted = true;
}
#endif
if (!delayMaintenanceStarted) {
m_statusMutex.lock();
MaintenanceManager::_instance->onMaintenanceStatusChange(MAINTENANCE_STARTED);
m_statusMutex.unlock();
}
/* cleanup if not empty */
if(!tasks.empty()){
tasks.erase (tasks.begin(),tasks.end());
}
/* Controlled by CFLAGS */
#if defined(SUPPRESS_MAINTENANCE) && !defined(ENABLE_WHOAMI)
bool activationStatus=false;
bool skipFirmwareCheck=false;
/* Activation check */
activationStatus = getActivatedStatus(skipFirmwareCheck);
/* we proceed with network check only if
* "activation-connect", "activation-ready"
* "not-activated", "activated" */
if(activationStatus){
/* Network check */
internetConnectStatus = isDeviceOnline();
}
#else /* WhoAmI */
internetConnectStatus = isDeviceOnline();
#endif
#if defined(ENABLE_WHOAMI)
string activation_status = checkActivatedStatus();
bool whoAmIStatus = false;
if (UNSOLICITED_MAINTENANCE == g_maintenance_type) {
/* WhoAmI check*/
whoAmIStatus = knowWhoAmI(activation_status);
if (whoAmIStatus) {
LOGINFO("knowWhoAmI() returned successfully");
}
else {
LOGINFO("knowWhoAmI() returned false");
}
}
if (false == whoAmIStatus && activation_status != "activated") {
LOGINFO("knowWhoAmI() returned false and Device is not already Activated");
g_listen_to_deviceContextUpdate = true;
LOGINFO("Waiting for onDeviceInitializationContextUpdate event");
task_thread.wait(wailck);
}
else if ( false == internetConnectStatus && activation_status == "activated" ) {
LOGINFO("Device is not connected to the Internet and Device is already Activated");
#else /* WhoAmI */
if ( false == internetConnectStatus ) {
#endif
m_statusMutex.lock();
MaintenanceManager::_instance->onMaintenanceStatusChange(MAINTENANCE_ERROR);
m_statusMutex.unlock();
LOGINFO("Maintenance is exiting as device is not connected to internet.");
if (UNSOLICITED_MAINTENANCE == g_maintenance_type && !g_unsolicited_complete){
g_unsolicited_complete = true;
g_listen_to_nwevents = true;
}
return;
}
if (delayMaintenanceStarted) {
m_statusMutex.lock();
MaintenanceManager::_instance->onMaintenanceStatusChange(MAINTENANCE_STARTED);
m_statusMutex.unlock();
}
LOGINFO("Reboot_Pending :%s",g_is_reboot_pending.c_str());
if (UNSOLICITED_MAINTENANCE == g_maintenance_type){
LOGINFO("---------------UNSOLICITED_MAINTENANCE--------------");
#ifndef ENABLE_WHOAMI
tasks.push_back(task_names_foreground[0].c_str());
#endif /* WhoAmI */
}
else if( SOLICITED_MAINTENANCE == g_maintenance_type){
LOGINFO("=============SOLICITED_MAINTENANCE===============");
}
#if defined(ENABLE_WHOAMI)
if (UNSOLICITED_MAINTENANCE == g_maintenance_type) {
tasks.push_back(task_names_foreground[1].c_str());
tasks.push_back(task_names_foreground[2].c_str());
tasks.push_back(task_names_foreground[0].c_str());
tasks.push_back(task_names_foreground[3].c_str());
} else {
tasks.push_back(task_names_foreground[1].c_str());
tasks.push_back(task_names_foreground[2].c_str());
tasks.push_back(task_names_foreground[3].c_str());
}
#elif defined(SUPPRESS_MAINTENANCE)
/* decide which all tasks are needed based on the activation status */
if (activationStatus){
if(skipFirmwareCheck){
/* set the task status of swupdate */
SET_STATUS(g_task_status,DIFD_SUCCESS);
SET_STATUS(g_task_status,DIFD_COMPLETE);
/* Add tasks */
tasks.push_back(task_names_foreground[1].c_str());
tasks.push_back(task_names_foreground[3].c_str());
}else{
tasks.push_back(task_names_foreground[1].c_str());
tasks.push_back(task_names_foreground[2].c_str());
tasks.push_back(task_names_foreground[3].c_str());
}
}
#else
tasks.push_back(task_names_foreground[1].c_str());
tasks.push_back(task_names_foreground[2].c_str());
tasks.push_back(task_names_foreground[3].c_str());
#endif
std::unique_lock<std::mutex> lck(m_callMutex);
for( i = 0; i < tasks.size() && !m_abort_flag; i++) {
cmd = tasks[i];
cmd += " &";
cmd += "\0";
m_task_map[tasks[i]] = true;
if ( !m_abort_flag ){
LOGINFO("Starting Script (SM) : %s \n",cmd.c_str());
system(cmd.c_str());
LOGINFO("Waiting to unlock.. [%d/%d]",i+1,(int)tasks.size());
task_thread.wait(lck);
}
}
m_abort_flag=false;
LOGINFO("Worker Thread Completed");
}
#if defined(ENABLE_WHOAMI)
bool MaintenanceManager::knowWhoAmI(string &activation_status)
{
bool success = false;
const char* secMgr_callsign = "org.rdk.SecManager";
const char* secMgr_callsign_ver = "org.rdk.SecManager.1";
PluginHost::IShell::state state;
WPEFramework::JSONRPC::LinkType<WPEFramework::Core::JSON::IElement>* thunder_client = nullptr;
do
{
if ((getServiceState(m_service, secMgr_callsign, state) == Core::ERROR_NONE) && (state == PluginHost::IShell::state::ACTIVATED)) {
LOGINFO("%s is active", secMgr_callsign);
thunder_client=getThunderPluginHandle(secMgr_callsign_ver);
if (thunder_client != nullptr) {
JsonObject params;
JsonObject joGetResult;
thunder_client->Invoke<JsonObject, JsonObject>(5000, "getDeviceInitializationContext", params, joGetResult);
if (joGetResult.HasLabel("success") && joGetResult["success"].Boolean()) {
static const char* kDeviceInitializationContext = "deviceInitializationContext";
if (joGetResult.HasLabel(kDeviceInitializationContext)) {
LOGINFO("%s found in the response", kDeviceInitializationContext);
success = setDeviceInitializationContext(joGetResult);
}
else {
LOGINFO("%s is not available in the response", kDeviceInitializationContext);
}
}
else {
LOGINFO("getDeviceInitializationContext failed");
}
} else {
LOGINFO("Failed to get plugin handle");
}
if (!g_subscribed_for_deviceContextUpdate) {
LOGINFO("onDeviceInitializationContextUpdate event not subscribed...");
g_subscribed_for_deviceContextUpdate = subscribeToDeviceInitializationEvent();
}
return success;
}
else {
g_subscribed_for_deviceContextUpdate = false;
if (activation_status != "activated") {
LOGINFO("%s is not active. Retry after %d seconds", secMgr_callsign, SECMGR_RETRY_INTERVAL);
sleep(SECMGR_RETRY_INTERVAL);
}
else {
LOGINFO("%s is not active. Device is already Activated. Hence exiting from knoWhoAmI()", secMgr_callsign);
return success;
}
}
}while(true);
}
#endif /* WhoAmI */
// Thunder plugin communication
WPEFramework::JSONRPC::LinkType<WPEFramework::Core::JSON::IElement>* MaintenanceManager::getThunderPluginHandle(const char* callsign)
{
string token;
WPEFramework::JSONRPC::LinkType<WPEFramework::Core::JSON::IElement>* thunder_client = nullptr;
auto security = m_service->QueryInterfaceByCallsign<PluginHost::IAuthenticate>("SecurityAgent");
if (security != nullptr) {
string payload = "http://localhost";
if (security->CreateToken(
static_cast<uint16_t>(payload.length()),
reinterpret_cast<const uint8_t*>(payload.c_str()),
token)
== Core::ERROR_NONE) {
std::cout << "MaintenanceManager got security token" << std::endl;
} else {
std::cout << "MaintenanceManager failed to get security token" << std::endl;
}
security->Release();
} else {
std::cout << "No security agent" << std::endl;
}
string query = "token=" + token;
Core::SystemInfo::SetEnvironment(_T("THUNDER_ACCESS"), _T(SERVER_DETAILS));
thunder_client = new WPEFramework::JSONRPC::LinkType<Core::JSON::IElement>(callsign, "", false, query);
return thunder_client;
}
bool MaintenanceManager::setRFC(const char* rfc, const char* value, DATA_TYPE dataType)
{
bool result = false;
WDMP_STATUS status;
status = setRFCParameter((char *)MAINTENANCE_MANAGER_RFC_CALLER_ID, rfc, value, dataType);
if ( WDMP_SUCCESS == status ){
LOGINFO("Successfuly set the tr181 parameter %s with value %s", rfc, value);
result = true;
} else {
LOGINFO("Failed setting %s parameter", rfc);
}
return result;
}
void MaintenanceManager::setPartnerId(string partnerid)
{
LOGINFO("Initiate setPartnerId...");
const char* authservice_callsign = "org.rdk.AuthService.1";
PluginHost::IShell::state state;
WPEFramework::JSONRPC::LinkType<WPEFramework::Core::JSON::IElement>* thunder_client = nullptr;
if ((getServiceState(m_service, "org.rdk.AuthService", state) == Core::ERROR_NONE) && (state == PluginHost::IShell::state::ACTIVATED)) {
thunder_client=getThunderPluginHandle(authservice_callsign);
if (thunder_client == nullptr) {
LOGINFO("Failed to get plugin handle");
} else {
JsonObject joGetParams;
JsonObject joGetResult;
joGetParams["partnerId"] = partnerid;
thunder_client->Invoke<JsonObject, JsonObject>(5000, "setPartnerId", joGetParams, joGetResult);
string responseJson;
joGetResult.ToString(responseJson);
LOGINFO("AuthService Response Data: %s", responseJson.c_str());
if (joGetResult.HasLabel("success") && joGetResult["success"].Boolean()) {
LOGINFO("Successfully set the partnerId via Authservice");
} else {
LOGINFO("Failed to set the partnerId through Authservice");
}
}
}
}
bool MaintenanceManager::subscribeForInternetStatusEvent(string event)
{
int32_t status = Core::ERROR_NONE;
bool result = false;
LOGINFO("Attempting to subscribe for %s events", event.c_str());
const char* network_callsign = "org.rdk.Network.1";
WPEFramework::JSONRPC::LinkType<WPEFramework::Core::JSON::IElement>* thunder_client = nullptr;
thunder_client = getThunderPluginHandle(network_callsign);
if (thunder_client == nullptr) {
LOGINFO("Failed to get plugin handle");
} else {
status = thunder_client->Subscribe<JsonObject>(5000, event, &MaintenanceManager::internetStatusChangeEventHandler, this);
if (status == Core::ERROR_NONE) {
result = true;
}
}
return result;
}
void MaintenanceManager::internetStatusChangeEventHandler(const JsonObject& parameters)
{
string value;
int state;
if (parameters.HasLabel("status") && parameters.HasLabel("state")) {
value = parameters["status"].String();
state = parameters["state"].Number();
LOGINFO("Received onInternetStatusChange event: [%s:%d]", value.c_str(), state);
if (g_listen_to_nwevents) {
if (state == INTERNET_CONNECTED_STATE) {
startCriticalTasks();
g_listen_to_nwevents = false;
}
}
}
}
void MaintenanceManager::deviceInitializationContextEventHandler(const JsonObject& parameters)
{
bool contextSet = false;
if (g_listen_to_deviceContextUpdate && UNSOLICITED_MAINTENANCE == g_maintenance_type) {
LOGINFO("onDeviceInitializationContextUpdate event is already subscribed and Maintenance Type is Unsolicited Maintenance");
if (parameters.HasLabel("deviceInitializationContext")) {
LOGINFO("deviceInitializationContext found");
contextSet = setDeviceInitializationContext(parameters);
if (contextSet) {
LOGINFO("setDeviceInitializationContext() success");
g_listen_to_deviceContextUpdate = false;
LOGINFO("Notify maintenance execution thread");
task_thread.notify_one();
}
else {
LOGINFO("setDeviceInitializationContext() failed");
}
}
else {
LOGINFO("deviceInitializationContext not found");
}
}
else {
LOGINFO("onDeviceInitializationContextUpdate event is not being listened already or Maintenance Type is not Unsolicited Maintenance");
}
}
void MaintenanceManager::startCriticalTasks()
{
LOGINFO("Starting Script /lib/rdk/StartDCM_maintaince.sh");
system("/lib/rdk/StartDCM_maintaince.sh &");
LOGINFO("Starting Script /lib/rdk/RFCbase.sh");
system("/lib/rdk/RFCbase.sh &");
LOGINFO("Starting Script /lib/rdk/xconfImageCheck.sh");
system("/lib/rdk/xconfImageCheck.sh >> /opt/logs/swupdate.log 2>&1 &");
}
const string MaintenanceManager::checkActivatedStatus()
{
JsonObject joGetParams;
JsonObject joGetResult;
std::string callsign = "org.rdk.AuthService.1";
uint8_t i = 0;
std::string ret_status("invalid");
/* check if plugin active */
PluginHost::IShell::state state = PluginHost::IShell::state::UNAVAILABLE;
if ((getServiceState(m_service, "org.rdk.AuthService", state) != Core::ERROR_NONE) || (state != PluginHost::IShell::state::ACTIVATED)) {
LOGINFO("AuthService plugin is not activated.Retrying.. \n");
//if plugin is not activated we need to retry
do{
if ((getServiceState(m_service, "org.rdk.AuthService", state) != Core::ERROR_NONE) || (state != PluginHost::IShell::state::ACTIVATED)) {
sleep(10);
i++;
LOGINFO("AuthService retries [%d/4] \n",i);
}
else{
break;
}
}while( i < MAX_ACTIVATION_RETRIES );
if (state != PluginHost::IShell::state::ACTIVATED){
LOGINFO("AuthService plugin is Still not active");
return ret_status;
}
else{
LOGINFO("AuthService plugin is Now active");
}
}
if (state == PluginHost::IShell::state::ACTIVATED){
LOGINFO("AuthService is active");
}
string token;
// TODO: use interfaces and remove token
auto security = m_service->QueryInterfaceByCallsign<PluginHost::IAuthenticate>("SecurityAgent");
if (security != nullptr) {
string payload = "http://localhost";
if (security->CreateToken(
static_cast<uint16_t>(payload.length()),
reinterpret_cast<const uint8_t*>(payload.c_str()),
token)
== Core::ERROR_NONE) {
std::cout << "MaintenanceManager got security token" << std::endl;
} else {
std::cout << "MaintenanceManager failed to get security token" << std::endl;
}
security->Release();
} else {
std::cout << "No security agent" << std::endl;
}
string query = "token=" + token;
Core::SystemInfo::SetEnvironment(_T("THUNDER_ACCESS"), _T(SERVER_DETAILS));
auto thunder_client = make_shared<WPEFramework::JSONRPC::LinkType<WPEFramework::Core::JSON::IElement> >(callsign.c_str(), "", false, query);
if (thunder_client != nullptr) {
uint32_t status = thunder_client->Invoke<JsonObject, JsonObject>(5000, "getActivationStatus", joGetParams, joGetResult);
LOGINFO("Invoke status : %d",status);
if (status > 0) {
LOGINFO("%s call failed %d", callsign.c_str(), status);
ret_status = "invalid";
LOGINFO("Setting Default to [%s]",ret_status.c_str());
} else if (joGetResult.HasLabel("status")) {
ret_status = joGetResult["status"].String();
LOGINFO("Activation Value [%s]",ret_status.c_str());
}
else {
LOGINFO("Failed to read the ActivationStatus");
ret_status = "invalid";
}
return ret_status;
}
LOGINFO("thunder client failed");
return ret_status;
}
bool MaintenanceManager::getActivatedStatus(bool &skipFirmwareCheck)
{
/* activation-connect, activation ready, not-activated - execute all except DIFD
* activation disconnect - dont run maintenance
* activated - run normal */
bool ret_result=false;
string activationStatus;
Auth_activation_status_t result;
const std::unordered_map<std::string,std::function<void()>> act{
{"activation-connect", [&](){ result = ACTIVATION_CONNECT; }},
{"activation-ready", [&](){ result = ACTIVATION_READY; }},
{"not-activated", [&](){ result = NOT_ACTIVATED; }},
{"activation-disconnect", [&](){ result = ACTIVATION_DISCONNECT; }},
{"activated", [&](){ result = ACTIVATED; }},
};
activationStatus = checkActivatedStatus();
LOGINFO("activation status : [ %s ]",activationStatus.c_str());
const auto end = act.end();
auto search = act.find(activationStatus);
if ( search != end ){
search->second();
}
else{
result = INVALID_ACTIVATION;
LOGINFO("result: invalid Activation");
}
switch(result){
case ACTIVATED:
ret_result = true;
break;
case ACTIVATION_DISCONNECT:
ret_result = false;
break;
case NOT_ACTIVATED:
case ACTIVATION_READY:
case ACTIVATION_CONNECT:
ret_result = true;
skipFirmwareCheck = true;
default:
ret_result = true;
}
LOGINFO("ret_result: [%s] skipFirmwareCheck:[%s]"
,(ret_result)? "true":"false",(skipFirmwareCheck)?"true":"false");
return ret_result;
}
bool MaintenanceManager::checkNetwork()
{
JsonObject joGetParams;
JsonObject joGetResult;
std::string callsign = "org.rdk.Network.1";
PluginHost::IShell::state state;
string token;
if ((getServiceState(m_service, "org.rdk.Network", state) == Core::ERROR_NONE) && (state == PluginHost::IShell::state::ACTIVATED)) {
LOGINFO("Network plugin is active");
if (UNSOLICITED_MAINTENANCE == g_maintenance_type && !g_subscribed_for_nwevents) {
// Subscribe for internetConnectionStatusChange event
bool subscribe_status = subscribeForInternetStatusEvent("onInternetStatusChange");
if (subscribe_status) {
LOGINFO("MaintenanceManager subscribed for onInternetStatusChange event");
g_subscribed_for_nwevents = true;
} else {
LOGINFO("Failed to subscribe for onInternetStatusChange event");
}
}
} else {
LOGINFO("Network plugin is not active");
return false;
}
// TODO: use interfaces and remove token
auto security = m_service->QueryInterfaceByCallsign<PluginHost::IAuthenticate>("SecurityAgent");
if (security != nullptr) {
string payload = "http://localhost";
if (security->CreateToken(
static_cast<uint16_t>(payload.length()),
reinterpret_cast<const uint8_t*>(payload.c_str()),
token)
== Core::ERROR_NONE) {
std::cout << "MaintenanceManager got security token" << std::endl;
} else {
std::cout << "MaintenanceManager failed to get security token" << std::endl;
}
security->Release();
} else {
std::cout << "No security agent" << std::endl;
}
string query = "token=" + token;
Core::SystemInfo::SetEnvironment(_T("THUNDER_ACCESS"), _T(SERVER_DETAILS));
auto thunder_client = make_shared<WPEFramework::JSONRPC::LinkType<WPEFramework::Core::JSON::IElement> >(callsign.c_str(), "", false, query);
if (thunder_client != nullptr) {
uint32_t status = thunder_client->Invoke<JsonObject, JsonObject>(5000, "isConnectedToInternet", joGetParams, joGetResult);
if (status > 0) {
LOGINFO("%s call failed %d", callsign.c_str(), status);
return false;
} else if (joGetResult.HasLabel("connectedToInternet")) {
LOGINFO("connectedToInternet status %s",(joGetResult["connectedToInternet"].Boolean())? "true":"false");
return joGetResult["connectedToInternet"].Boolean();
} else {
return false;
}
}
LOGINFO("thunder client failed");
return false;
}
bool MaintenanceManager::isDeviceOnline()
{
bool network_available = false;
LOGINFO("Checking device has network connectivity\n");
/* add 4 checks every 30 seconds */
network_available = checkNetwork();
if (!network_available) {
int retry_count = 0;
while (retry_count < MAX_NETWORK_RETRIES) {
LOGINFO("Network not available. Sleeping for %d seconds", NETWORK_RETRY_INTERVAL);
sleep(NETWORK_RETRY_INTERVAL);
LOGINFO("Network retries [%d/%d] \n", ++retry_count, MAX_NETWORK_RETRIES);
network_available = checkNetwork();
if (network_available) {
break;
}
}
}
return network_available;
}
bool MaintenanceManager::setDeviceInitializationContext(JsonObject response_data) {
bool setDone = false;
bool paramEmpty = false;
JsonObject getInitializationContext = response_data["deviceInitializationContext"].Object();
for (const string& key : kDeviceInitContextKeyVals)
{
// Retrieve deviceInitializationContext Value
string paramValue = getInitializationContext[key.c_str()].String();
if (!paramValue.empty())
{
if (strcmp(key.c_str(), "regionalConfigService") == 0)
{
paramValue = "https://" + paramValue;
}
LOGINFO("[deviceInitializationContext] %s : %s", key.c_str(), paramValue.c_str());
// Retrieve tr181 parameter from m_param_map
string rfc_parameter = m_param_map[key];
// Retrieve parameter data type from m_paramType_map
DATA_TYPE rfc_dataType = m_paramType_map[key];
// Set the RFC values for deviceInitializationContext parameters
setRFC(rfc_parameter.c_str(), paramValue.c_str(), rfc_dataType);
LOGINFO("deviceInitializationContext parameters set successfully via RFC");
if (strcmp(key.c_str(), "partnerId") == 0)
{
setPartnerId(paramValue);
}
}
else
{
LOGINFO("Not able to fetch %s value from deviceInitializationContext", key.c_str());
paramEmpty = true;
}
}
setDone = !paramEmpty;
return setDone;
}
bool MaintenanceManager::subscribeToDeviceInitializationEvent() {
int32_t status = Core::ERROR_NONE;
bool result = false;
string event = "onDeviceInitializationContextUpdate";
const char* secMgr_callsign_ver = "org.rdk.SecManager.1";
WPEFramework::JSONRPC::LinkType<WPEFramework::Core::JSON::IElement>* thunder_client = nullptr;
// subscribe to onDeviceInitializationContextUpdate event
LOGINFO("Attempting to subscribe for %s events", event.c_str());
thunder_client = getThunderPluginHandle(secMgr_callsign_ver);
if (thunder_client == nullptr) {
LOGINFO("Failed to get plugin handle");
}
else {
status = thunder_client->Subscribe<JsonObject>(5000, event, &MaintenanceManager::deviceInitializationContextEventHandler, this);
if (status == Core::ERROR_NONE) {
result = true;
}
}
g_subscribed_for_deviceContextUpdate = result;
if(g_subscribed_for_deviceContextUpdate) {
LOGINFO("MaintenanceManager subscribed for %s event", event.c_str());
return true;
}
else {
LOGINFO("Failed to subscribe for %s event", event.c_str());
return false;
}
}
MaintenanceManager::~MaintenanceManager()
{
MaintenanceManager::_instance = nullptr;
}
const string MaintenanceManager::Initialize(PluginHost::IShell* service)
{
ASSERT(service != nullptr);
ASSERT(m_service == nullptr);
m_service = service;
m_service->AddRef();
#if defined(ENABLE_WHOAMI)
subscribeToDeviceInitializationEvent();
#endif /* WhoAmI */
#if defined(USE_IARMBUS) || defined(USE_IARM_BUS)
InitializeIARM();
#endif /* defined(USE_IARMBUS) || defined(USE_IARM_BUS) */
/* On Success; return empty to indicate no error text. */
return (string());
}
void MaintenanceManager::Deinitialize(PluginHost::IShell* service)
{
#if defined(USE_IARMBUS) || defined(USE_IARM_BUS)
stopMaintenanceTasks();
DeinitializeIARM();
#endif /* defined(USE_IARMBUS) || defined(USE_IARM_BUS) */
ASSERT(service == m_service);
m_service->Release();
m_service = nullptr;
}
#if defined(USE_IARMBUS) || defined(USE_IARM_BUS)
void MaintenanceManager::InitializeIARM()
{
if (Utils::IARM::init()) {
IARM_Result_t res;
// Register for the Maintenance Notification Events
IARM_CHECK(IARM_Bus_RegisterEventHandler(IARM_BUS_MAINTENANCE_MGR_NAME, IARM_BUS_MAINTENANCEMGR_EVENT_UPDATE, _MaintenanceMgrEventHandler));
//Register for setMaintenanceStartTime
IARM_CHECK(IARM_Bus_RegisterEventHandler(IARM_BUS_MAINTENANCE_MGR_NAME, IARM_BUS_DCM_NEW_START_TIME_EVENT,_MaintenanceMgrEventHandler));
maintenanceManagerOnBootup();