Re-organized sub-directory by category
[staging/basesystem.git] / service / system / resource_manager / server / src / resm.cpp
1 /*
2  * @copyright Copyright (c) 2016-2020 TOYOTA MOTOR CORPORATION.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <stdio.h>
18 #include <unistd.h>
19 #include <string.h>
20 #include <stdlib.h>
21 #include <pthread.h>
22 #include <ctype.h>
23 #include <sys/ioctl.h>
24 #include <net/if.h>
25 #include <netinet/in.h>
26 #include <arpa/inet.h>
27 #include <stdint.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <sys/timerfd.h>
31 #include <sys/wait.h>
32 #include <sched.h>
33 #include <sys/stat.h>
34 #include <sys/types.h>
35 #include <signal.h>
36
37 // NSFW
38 #include <native_service/frameworkunified_dispatcher.h>
39 #include <native_service/frameworkunified_framework_if.h>
40 #include <native_service/ns_version_if.h>
41 #include <system_service/ss_services.h>
42 #include <native_service/frameworkunified_application.h>
43 #include <system_service/ss_system_if.h>
44 #include <system_service/ss_version.h>
45 #include <native_service/cl_process.h>
46 #include <system_service/ss_system_process.h>
47 #include <other_service/rpc.h>
48 #include "resmgr_srvr.h"
49 #include "resm_internal.h"
50 #include "resmgr_api.h"
51 #include "ss_resm_resourcemanagerlog.h"
52 #include "resm_cfg.h"
53 #include "proc_watch.h"
54
55
56 // NSFW
57 CFrameworkunifiedVersion g_FrameworkunifiedVersion(MAJORNO, MINORNO, REVISION);
58 /**********************************************
59  * Constant definitions
60  **********************************************/
61 #define Resm_Flag_ID_Base EV_Flag_ID_Base(RESMGR_MID)
62 #define RESM_SUB_PRIORITY (0)
63
64 // #define WTC_CPU_INTERVAL (3)
65
66 #define CPULOAD_INVALID (-2)
67 #define CPULOAD_READY (-1)
68 #define CPULOG_TIMER_CLEAR (1)
69 #define CPULOG_LOGGING (0)
70 #define CPULOG_NO_LOGGING (-1)
71
72 #define PROCNET_DEV_FILE "/proc/net/dev"
73 #define MEMINFO_FILE "/proc/meminfo"
74 #define PROC_STAT_FILE "/proc/stat"
75
76 #define BYTE_TO_KIBIBYTE (1024)
77 #define KIBIBYTE_TO_BYTE (1024)
78 #define PERF_PNAME_MAX  128  // Max path name of process
79 #define PERF_PATH  "/usr/bin/perf"
80 #define PERF_FILE  "/tmp/perf"
81 #define PERF_DUMP  "/tmp/perf_dump"
82 #define PERF_REPORT_DELAY  1   // 1 sec
83 #define PERF_REPORT_RETRY  3   // retry 3 times
84 #define CPULOAD_NICEVAL   10   // value of nice() to lower priority
85
86 #define DEBUG_INFO_DIRPATH  "/tmp/diag_analysis"
87 #define DEBUG_INFO_FPATH DEBUG_INFO_DIRPATH"/dispinfo_resource.dbg"
88 #define DEBUG_INFO_TMPPATH DEBUG_INFO_DIRPATH"/dispinfo_resource.tmp"
89 #define DEBUG_INFO_MEM_LETTERS  (25)
90 #define DEBUG_INFO_CPU_TOP_LINES  (10)
91 #define DEBUG_INFO_CMA_MIN  (160000)  // in KB
92 #define DEBUG_INFO_CMA_LETTERS  (20)
93 #define DEBUG_INFO_DSP_PG_PATH  "/usr/agl/bin/bs_analysis_dispinfo_debug"
94
95 #define DROP_CACHES_PG_PATH "/usr/agl/bin/drop_caches"
96
97 #define READLINE_MAX_SIZE       512
98 #define READ_MAX_SIZE          4096
99 #define LF (0x0A)
100
101 /**********************************************
102  * Structure definitions
103  **********************************************/
104 // App session information
105 typedef struct {
106   BOOL useFlag;
107   RESM_REQ_EVENT_t reqEv;     // event request
108 } SSN_INFO_t;
109
110 // CPU usage information
111 typedef struct {
112   char cpuname[8];
113   int32_t user;
114   int32_t nice;
115   int32_t system;
116   int32_t idle;
117   int32_t iowait;
118   int32_t irq;
119   int32_t softirq;
120   int32_t steal;
121   int32_t guest;
122   int32_t guest_nice;
123 } CPU_INFO_t;
124
125 //Context
126 typedef struct {
127   char procName[128];
128   HANDLE hApp;      // DispatcherHandle
129   int32_t nsFd;     // For receiving from the NSFW
130
131   // Session information
132   SSN_INFO_t ssnInfo[EV_MAX_IDS_IN_THREAD];
133
134   // Memory information
135   uint32_t restMem;     // Remaining memory information
136   BOOL restMemFlag;
137
138   // CMA information
139   uint32_t restCma;
140   BOOL restCmaFlag;
141
142
143   // CPU load information
144 //  int32_t cpuloadRate;
145 } SVC_COMMON_t;
146
147 // meminfo table
148 typedef struct {
149   const char* name;
150   uint32_t* value;
151 } meminfo_tbl;
152
153 /**********************************************
154  * External variable definitions
155  **********************************************/
156 // FRAMEWORKUNIFIEDLOG
157 FRAMEWORKUNIFIEDLOGPARAM g_FrameworkunifiedLogParams = {
158   FRAMEWORKUNIFIEDLOGOPTIONS, {
159     ZONE_TEXT_10, ZONE_TEXT_11, ZONE_TEXT_12,
160     ZONE_TEXT_13, ZONE_TEXT_14, ZONE_TEXT_15,
161     ZONE_TEXT_16, ZONE_TEXT_17, ZONE_TEXT_18,
162     ZONE_TEXT_19, ZONE_TEXT_20, ZONE_TEXT_21,
163     ZONE_TEXT_22, ZONE_TEXT_23, ZONE_TEXT_24,
164     ZONE_TEXT_25, ZONE_TEXT_26, ZONE_TEXT_27,
165     ZONE_TEXT_28, ZONE_TEXT_29, ZONE_TEXT_30,
166     ZONE_TEXT_31
167   }, FRAMEWORKUNIFIEDLOGZONES
168 };
169
170 int isNfs;                     // NFS env : 1
171
172 static SVC_COMMON_t g_resmgr;  // NOLINT (readability/nolint)
173 static int32_t g_sock = -1;
174 static uint32_t inactFile_kib;
175 static uint32_t mainFree_kib;
176 static uint32_t memTotal_kib;
177 static uint32_t cmaFree_kib;
178 static uint32_t cmaTotal_kib;
179 static uint32_t minRestMem;    // Minimum memory available
180 static uint32_t minRestCma;    // Minimum CMA available
181 static int32_t g_cpuloadRate1000;
182 static int g_cpu_num;
183 static CPU_INFO_t *g_cpuload_pre;
184 static CPU_INFO_t *g_cpuload;
185
186 static int32_t g_fifo_status = STATUS_IDOL;
187 static int32_t g_tss_status = STATUS_IDOL;
188 static int32_t g_fifo_timer = 0;
189 static int32_t g_tss_timer = 0;
190
191
192 /**********************************************
193  * Local function definition
194  **********************************************/
195 static void ctxCreate(SVC_COMMON_t* p_ctx, int32_t argc, char* argv[]);
196
197 // Session related
198 static int32_t get_new_id(uint32_t* ssnId);
199
200 // Memory monitoring
201 void watchMem(void);
202 static int32_t comp_meminfo_tbl(const void* a, const void* b);
203 static int32_t get_meminfo(void);
204
205 // Network monitoring
206 static int32_t getInetStatus(RESM_INET_STATUS_t* p_iStatus);
207 static char* get_aliasName(char* name, char* line);
208 static int32_t get_hwaddr(char* name, char* hwaddr);
209
210 // CPU monitoring
211
212 static void watchCPUStatus(void);
213 static void watchCPU(void);
214 static int32_t get_cpuload(CPU_INFO_t* p_cpu);
215 static int32_t calc_cpuloadRate(void);
216 static int32_t calc_cpuloadRate_each(int num);
217
218 // static int32_t chk_logging(int32_t cpuload, int32_t timer);
219 // static void logging_cpuload(void);
220
221 static void trim_end(char* buf);
222
223 // static void escape_percent(char* in, char* out);
224 static void init_cpuload(void);
225
226 // extern void logging_cpuload_custom(void);
227 static void exec_perf(int32_t t_pid);
228 extern unsigned long logging_cpuload_custom(int32_t tmode);
229
230
231 // Debug information output
232 void outputResouceInfo(void);
233 static int write_meminfo_work(FILE *wfp);
234 static int write_cpuinfo_work(FILE *wfp);
235 static int write_cmainfo_work(FILE *wfp);
236 static int write_resourcemanagerloginfo_work(void);
237
238 /*******************************************************************************
239  * RPC public API
240  *******************************************************************************/
241 /* Event issuance request */
242 RESM_ERR_t RESM_ReqEvent(uint32_t ssnId, const RESM_REQ_EVENT_t* p_reqEvent) {
243   // Argument check
244   if (p_reqEvent == NULL) {
245     FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "ResMgr ReqEvent Invalid Arg");
246     return RESM_E_PAR;
247   }
248
249   if (ssnId >= EV_MAX_IDS_IN_THREAD) {
250     FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "ResMgr ReqEvent Invalid Arg");
251     return RESM_E_PAR;
252   }
253
254   if (!g_resmgr.ssnInfo[ssnId].useFlag) {
255     FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "ResMgr ReqEvent Invalid Arg");
256     return RESM_E_PAR;
257   }
258
259   // Event type check
260   if (p_reqEvent->reqEvent == RESM_EV_MEM) {
261     // Record event issuance request
262     memcpy(&g_resmgr.ssnInfo[ssnId].reqEv, p_reqEvent,
263            sizeof(RESM_REQ_EVENT_t));
264   }
265
266   return RESM_E_OK;
267 }
268
269 /* Get system status */
270 RESM_ERR_t RESM_GetStatus(uint32_t ssnId, RESM_STATUS_t* p_status) {
271   int32_t ret;
272
273   // Argument check
274   if (p_status == NULL) {
275     FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "ResMgr GetStatus Invalid Arg");
276     return RESM_E_PAR;
277   }
278
279   if (ssnId >= EV_MAX_IDS_IN_THREAD) {
280     FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "ResMgr GetStatus Invalid Arg");
281     return RESM_E_PAR;
282   }
283
284   if (!g_resmgr.ssnInfo[ssnId].useFlag) {
285     FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "ResMgr GetStatus Invalid Arg");
286     return RESM_E_PAR;
287   }
288
289   if (!g_resmgr.restMemFlag) {
290     // No remaining memory information
291     FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "ResMgr GetStatus get restmem Error");  // LCOV_EXCL_BR_LINE 15:marco defined in "native_service/ns_logger_if.h"  // NOLINT[whitespace/line_length]
292     return RESM_E_NG;
293   }
294   p_status->restMemSize = g_resmgr.restMem;
295   p_status->nandWriteStatus = RESM_NAND_WRITE_ENABLE;   //[]Always possible
296
297   ret = getInetStatus(&p_status->inetStatus);
298   if (ret != 0) {
299     FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__,
300            "ResMgr GetStatus getInetStatus Error");
301     return RESM_E_NG;
302   }
303
304   return RESM_E_OK;
305 }
306
307 /*******************************************************************************
308  * Internal API
309  *******************************************************************************/
310 /* Session connection */
311 RESM_ERR_t RESM_SV_Open(const RESM_RSV_t* p_prim, uint32_t* p_ssnId) {
312   int32_t ret;
313
314   ret = get_new_id(p_ssnId);
315   if (ret != 0) {
316     return RESM_E_NG;
317   }
318   // FRAMEWORKUNIFIEDLOG(ZONE_INFO, __FUNCTION__, "ResMgr Open Session:ID=[%d]", *p_ssnId);
319
320   return RESM_E_OK;
321 }
322
323 /* Session disconnection */
324 RESM_ERR_t RESM_SV_Close(uint32_t ssnId) {
325   // Argument check
326   if (ssnId >= EV_MAX_IDS_IN_THREAD) {
327     FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "ResMgr Close Invalid Arg");
328     return RESM_E_PAR;
329   }
330
331   if (!g_resmgr.ssnInfo[ssnId].useFlag) {
332     FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "ResMgr Close Invalid Arg");
333     return RESM_E_PAR;
334   }
335
336   // Turn off used flag
337   g_resmgr.ssnInfo[ssnId].useFlag = FALSE;
338
339   // Clear event request
340   memset(&g_resmgr.ssnInfo[ssnId].reqEv, 0, sizeof(RESM_REQ_EVENT_t));
341
342   return RESM_E_OK;
343 }
344
345 /* Session ID check */
346 RESM_ERR_t RESM_SV_ChkSsnId(uint32_t ssnId) {
347   if (ssnId >= EV_MAX_IDS_IN_THREAD) {
348     FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "ResMgr ssnId[%d] over MAX", ssnId);
349     return RESM_E_NG;
350   }
351
352   if (!g_resmgr.ssnInfo[ssnId].useFlag) {
353     FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "ResMgr ssnId[%d] is unidentified",
354            ssnId);
355     return RESM_E_NG;
356   }
357
358   return RESM_E_OK;
359 }
360
361 /**********************************************
362  *  Initialization function
363  **********************************************/
364 /* Context Initialization */
365 static void ctxCreate(SVC_COMMON_t* p_ctx, int32_t argc, char* argv[]) {
366   EFrameworkunifiedStatus resourcemanagerRet;
367   FrameworkunifiedDefaultCallbackHandler cbFuncs;
368   FRAMEWORKUNIFIED_MAKE_DEFAULT_CALLBACK(cbFuncs);
369   FRAMEWORKUNIFIED_SET_ZONES();
370
371   memset(p_ctx, 0, sizeof(SVC_COMMON_t));
372   strcpy(p_ctx->procName, SS_RESOURCE_MANAGER);  // NOLINT
373
374   // Create a Dispatcher
375   resourcemanagerRet = FrameworkunifiedCreateDispatcherWithoutLoop(p_ctx->procName, p_ctx->hApp, argc,
376                                           argv, &cbFuncs, TRUE);
377   if (resourcemanagerRet != eFrameworkunifiedStatusOK) {  // LCOV_EXCL_BR_LINE 4: NSFW error case.
378     // LCOV_EXCL_START 4: NSFW error case.
379     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
380     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
381            "[RESM_ERR]ResMgr Create Dispatcher Failed. ret[%d]", resourcemanagerRet);
382     exit(EXIT_FAILURE);
383     // LCOV_EXCL_STOP 4: NSFW error case.
384   }
385
386   resourcemanagerRet = FrameworkunifiedGetDispatcherFD(p_ctx->hApp, &p_ctx->nsFd);
387   if (resourcemanagerRet != eFrameworkunifiedStatusOK) {  // LCOV_EXCL_BR_LINE 4: NSFW error case.
388     // LCOV_EXCL_START 4: NSFW error case.
389     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
390     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
391            "[RESM_ERR]ResMgr Get Dispatcher FD Failed. ret[%d]", resourcemanagerRet);
392     exit(EXIT_FAILURE);
393     // LCOV_EXCL_STOP 4: NSFW error case.
394   }
395
396   // Initialize session
397   memset(p_ctx->ssnInfo, 0, sizeof(p_ctx->ssnInfo));
398
399
400 //  // Initialize CPU Information
401 //  g_resmgr.cpuloadRate = CPULOAD_INVALID;
402
403
404   return;
405 }
406
407 /**********************************************
408  *  Get FRAMEWORKUNIFIEDLOG BasePF Flag
409  **********************************************/
410 static EFrameworkunifiedStatus resourcemanagerlog_output_debug_info;
411 #define RESOURCEMANAGERLOG_BASEPF_FLAG_ID (11)
412
413 EFrameworkunifiedStatus resourcemanagerlog_flag_check(UI_8 *mode) {
414   if (resourcemanagerlog_output_debug_info != eFrameworkunifiedStatusOK)
415     return eFrameworkunifiedStatusFail;
416
417   return NsLogGetFrameworkunifiedLogFlag(RESOURCEMANAGERLOG_BASEPF_FLAG_ID, mode);
418 }
419
420 /* drop_caches Start update Task */
421 static void start_drop_caches(void) {
422   pid_t pid = fork();
423   if (pid == 0) {
424     if (setuid(0) == -1) {  // LCOV_EXCL_BR_LINE 5: setuid's error case
425       // LCOV_EXCL_START 5: setuid's error case
426       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
427       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Failed to setuid(0)-1, errno=%d", errno);
428       // LCOV_EXCL_STOP
429     } else {
430       struct sched_param param;
431       // Exec drop_caches
432       param.sched_priority = 0;
433       if (sched_setscheduler(getpid(), SCHED_OTHER, &param) < 0) {  // LCOV_EXCL_BR_LINE 5: sched_setscheduler's error case
434         // LCOV_EXCL_START 5: sched_setscheduler's error case
435         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
436         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Failed to sched_setscheduler errno=%d",
437                errno);
438         // LCOV_EXCL_STOP
439       } else {
440         execl(DROP_CACHES_PG_PATH, basename(DROP_CACHES_PG_PATH), NULL);
441         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Failed to execl %s errno=%d",
442                DROP_CACHES_PG_PATH,
443                errno);
444       }
445     }
446     exit(1);
447   }
448   if (pid == (pid_t) -1) {  // LCOV_EXCL_BR_LINE 5: fork's error case
449     // LCOV_EXCL_START 5: fork's error case
450     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
451     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Failed to fork=-1, errno=%d", errno);
452     // LCOV_EXCL_STOP
453   }
454 }
455
456 /**********************************************
457  *  Main Function
458  **********************************************/
459 int32_t main(int32_t argc, char* argv[]) {
460   int32_t mainRet = -1;
461   int32_t rpcFd;
462   int32_t timerFd;
463   struct itimerspec tm;
464   int32_t timerFd2;
465   struct itimerspec tm2;
466   uint64_t exp;
467   int32_t maxFd = 0;
468   fd_set fds;
469   struct sched_param prcwParam;
470   pthread_t ptPRCW;
471   int32_t sec = 0;
472   int32_t ret;
473
474   int32_t cpu_ret;
475   bool fork_dsp_task = false;
476   CL_ProcessAttr_t attr;
477   const char *prName;
478   const char *args[iProcess_MAXIMUM_NUMBER_OF_PROCESS_ARGUMENTS];
479   UI_8 mode;
480   EFrameworkunifiedStatus eRet;
481   struct stat statbuf;
482
483   RPC_ID rpcId = RESMGR_RPC_ID;
484   SVC_COMMON_t* p_ctx = &g_resmgr;
485   EFrameworkunifiedStatus resourcemanagerRet = eFrameworkunifiedStatusOK;
486
487   {
488     const char* nfsenv = getenv("AGL_NFS");
489     isNfs = (nfsenv && strcmp(nfsenv, "y") == 0) ? 1 : 0;
490   }
491
492   /* Clear context */
493   ctxCreate(p_ctx, argc, argv);
494
495   /* Start debug information display task */
496   {
497     char *tmp;
498     tmp = getenv("AGL_DEVDIAG_FLAG");
499     if ((tmp == NULL) || strcmp(tmp, "ON")) {  // != "ON"
500       resourcemanagerlog_output_debug_info = eFrameworkunifiedStatusFail;
501     } else {
502       resourcemanagerlog_output_debug_info = eFrameworkunifiedStatusOK;
503     }
504   }
505   eRet = resourcemanagerlog_flag_check(&mode);
506   if (eRet == eFrameworkunifiedStatusOK && mode == FRAMEWORKUNIFIEDLOG_FLAG_MODE_DEBUG) {
507     fork_dsp_task = true;
508   }
509   if (fork_dsp_task) {
510     // LCOV_EXCL_START 8: there is no bs_analysis_dispinfo_debug
511     if (0 == stat(DEBUG_INFO_DSP_PG_PATH, &statbuf)) {
512       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
513       if (0 != CL_ProcessCreateAttrInit(&attr)) {  // LCOV_EXCL_BR_LINE 4: NSFW error case.
514         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
515         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "CL_ProcessCreateAttrInit Error");  // LCOV_EXCL_LINE 4: NSFW error case.
516       }
517       prName = basename(DEBUG_INFO_DSP_PG_PATH);
518       if (0 != CL_ProcessCreateAttrSetName(&attr, prName)) {  // LCOV_EXCL_BR_LINE 4: NSFW error case.
519         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
520         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Set Name Error");  // LCOV_EXCL_LINE 4: NSFW error case.
521       }
522       args[0] = prName;
523       args[1] = NULL;
524       if (CL_ProcessCreate(DEBUG_INFO_DSP_PG_PATH, (char* const *) args, NULL,
525                            &attr) < 0) {  // LCOV_EXCL_BR_LINE 4: NSFW error case.
526         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
527         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "CL_ProcessCreate Error");  // LCOV_EXCL_LINE 4: NSFW error case.
528       }
529     }
530     // LCOV_EXCL_STOP 8: there is no bs_analysis_dispinfo_debug
531   }
532
533   /* Create socket */
534   g_sock = socket(AF_INET, SOCK_DGRAM, 0);
535   if (g_sock < 0) {  // LCOV_EXCL_BR_LINE 5: socket error case
536     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
537     FRAMEWORKUNIFIEDLOG(ZONE_WARN, __FUNCTION__, "[RESM_ERR]ResMgr Create Socket Failed");  // LCOV_EXCL_LINE 5: socket error case
538   }
539
540   FRAMEWORKUNIFIEDLOG(ZONE_INFO, __FUNCTION__, "[%s:%d] ResMgr Wakeup", p_ctx->procName,
541          getpid());
542
543   RPC_START_SERVER(rpcId);    // Start RPC Server
544   RPC_get_fd(rpcId, &rpcFd);      // Event reception FD of RPC
545
546   /* Create proc_watch thread */
547   ret = pthread_create(&ptPRCW, NULL, &PRCW_main, reinterpret_cast<void*>(NULL));
548   if (ret != 0) {  // LCOV_EXCL_BR_LINE 5: pthread_create error case
549     // LCOV_EXCL_START 5: pthread_create error case
550     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
551     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
552            "[RESM_ERR]ResMgr Create Thread Failed. code[%d]", ret);
553     // LCOV_EXCL_STOP 5: pthread_create error case
554   } else {
555     prcwParam.sched_priority = RESM_SUB_PRIORITY;
556     ret = pthread_setschedparam(ptPRCW, SCHED_OTHER, &prcwParam);
557     if (ret != 0) {  // LCOV_EXCL_BR_LINE 5: pthread_setschedparam error case
558       // LCOV_EXCL_START 5: pthread_setschedparam error case
559       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
560       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
561              "[RESM_ERR]ResMgr Set Thread Schedparam Failed. code[%d]", ret);
562       // LCOV_EXCL_STOP 5: pthread_setschedparam error case
563     }
564   }
565
566   /* Create timer */
567   if ((timerFd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC)) == -1) {
568     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
569            "[RESM_ERR]ResMgr Create timerFd Failed. errno[%d]", errno);
570     exit(EXIT_FAILURE);
571   }
572   // for drop_caches
573   {
574     if ((timerFd2 = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC)) == -1) {
575       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
576              "[RESM_ERR]ResMgr Create timerFd2 Failed. errno[%d]", errno);
577       exit(EXIT_FAILURE);
578     }
579   }
580
581   // Initialize remaining memory acquisition
582   mainFree_kib = 0;
583   inactFile_kib = 0;
584   memTotal_kib = 0;
585   cmaFree_kib = 0;
586   cmaTotal_kib = 0;
587   get_meminfo();
588   g_resmgr.restMem = mainFree_kib + inactFile_kib;
589   minRestMem = g_resmgr.restMem;
590   g_resmgr.restMemFlag = TRUE;
591   g_resmgr.restCma = cmaFree_kib;
592   minRestCma = g_resmgr.restCma;
593   g_resmgr.restCmaFlag = TRUE;
594
595   tm.it_value.tv_sec = MONITORING_START_DELAT_TIME;
596   tm.it_value.tv_nsec = 0;
597   tm.it_interval.tv_sec = 1;
598   tm.it_interval.tv_nsec = 0;
599   if (timerfd_settime(timerFd, 0, &tm, NULL) == -1) {
600     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
601            "[RESM_ERR]ResMgr Set timerFd Failed. errno[%d]", errno);
602     exit(EXIT_FAILURE);
603   }
604
605   tm2.it_value.tv_sec = DROP_CACHES_START_DELAT_TIME;
606   tm2.it_value.tv_nsec = 0;
607   tm2.it_interval.tv_sec = 0;
608   tm2.it_interval.tv_nsec = 0;
609   if (timerfd_settime(timerFd2, 0, &tm2, NULL) == -1) {  // LCOV_EXCL_BR_LINE 11:Gcov constraints (coverage measurement revision by DeathTest)
610     // LCOV_EXCL_START 11:Gcov constraints (coverage measurement revision by DeathTest)
611     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
612            "[RESM_ERR]ResMgr Set timerFd2 Failed. errno[%d]", errno);
613     exit(EXIT_FAILURE);
614     // LCOV_EXCL_END 11:Gcov constraints (coverage measurement revision by DeathTest)
615   }
616
617   /* API to Publish Service Availability Notification. */
618   resourcemanagerRet = FrameworkunifiedPublishServiceAvailability(p_ctx->hApp, TRUE);
619   if (eFrameworkunifiedStatusOK != resourcemanagerRet) {  // LCOV_EXCL_BR_LINE 4: NSFW error case.
620     // LCOV_EXCL_START 4: NSFW error case.
621     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
622     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
623            "Failed to Publish Service Availability Notification:0x%x", resourcemanagerRet);
624     exit(EXIT_FAILURE);
625     // LCOV_EXCL_STOP 4: NSFW error case.
626   }
627
628
629   /* CPU Load init */
630   g_fifo_status = STATUS_CHECK_CPU;
631   g_tss_status = STATUS_CHECK_CPU;
632   g_cpuloadRate1000 = 0;
633   init_cpuload();
634   cpu_ret = get_cpuload(g_cpuload);
635   if ( cpu_ret != 0 ) {  // LCOV_EXCL_BR_LINE 200: cpu_ret must be 0
636     // LCOV_EXCL_START 200: cpu_ret must be 0
637     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
638     FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "Get cpuload Failed");
639     g_cpuloadRate1000 = 0;
640     // LCOV_EXCL_STOP
641   }
642
643
644   while (1) {
645     FD_ZERO(&fds);
646     FD_SET(rpcFd, &fds);
647     maxFd = MY_MAX(maxFd, rpcFd);
648
649     FD_SET(p_ctx->nsFd, &fds);
650     maxFd = MY_MAX(maxFd, p_ctx->nsFd);
651
652     FD_SET(timerFd, &fds);
653     maxFd = MY_MAX(maxFd, timerFd);
654
655     if (timerFd2 != -1) {
656       FD_SET(timerFd2, &fds);
657       maxFd = MY_MAX(maxFd, timerFd2);
658     }
659     ret = select(maxFd + 1, &fds, NULL, NULL, NULL);
660     if (ret < 0) {  // LCOV_EXCL_BR_LINE 5: select error case
661       // LCOV_EXCL_START 5: select error case
662       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
663       if (errno != EINTR) {
664         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "[RESM_ERR]ResMgr Handle Error");
665         exit(EXIT_FAILURE);
666       }
667       continue;
668       // LCOV_EXCL_STOP 5: select error case
669     }
670     /* API CALL from RPC */
671     if ((timerFd2 != -1) && FD_ISSET(timerFd2, &fds)) {
672       start_drop_caches();
673       timerFd2 = -1;
674     }
675
676     /* API CALL from RPC */
677     if (FD_ISSET(rpcFd, &fds)) {
678       RPC_process_API_request(rpcId);
679     }
680     /* Events from the NSFW */
681     if (FD_ISSET(p_ctx->nsFd, &fds)) {
682       FrameworkunifiedDispatchProcessWithoutLoop(p_ctx->hApp);
683     }
684
685     /* Timer expiration */
686     if (FD_ISSET(timerFd, &fds)) {
687       read(timerFd, &exp, sizeof(uint64_t));
688       /* CPU load monitoring */
689       if ((sec % WTC_CPU_INTERVAL) == 0) {
690         watchCPUStatus();
691       }
692
693       if (sec >= RESET_SEC) {
694         sec = 0;
695       }
696       sec++;
697     }
698   }
699
700   // Close socket
701   close(g_sock);
702
703   mainRet = 0;
704   RPC_end(rpcId);
705
706   return mainRet;
707 }
708
709 /*********************************************************************************
710  * Session Related
711  *********************************************************************************/
712 /* Numbering session ID */
713 static int32_t get_new_id(uint32_t* ssnId) {
714   int32_t i;
715   SSN_INFO_t* p_ssnInfo;
716
717   for (i = 0; i < EV_MAX_IDS_IN_THREAD; i++) {
718     p_ssnInfo = &g_resmgr.ssnInfo[i];
719
720     if (p_ssnInfo->useFlag) {
721       // in-use
722       continue;
723     }
724     *ssnId = i;
725     p_ssnInfo->useFlag = TRUE;
726
727     return 0;
728   }
729
730   return -1;
731 }
732
733 /*********************************************************************************
734  * Memory monitoring
735  *********************************************************************************/
736 /* Memory monitoring */
737 void watchMem(void) {
738   uint32_t restMem_b;
739   SSN_INFO_t* p_ssnInfo;
740   uint32_t ssnId;
741   int32_t i;
742   int32_t ret;
743
744   // Get remaining memory
745   mainFree_kib = 0;
746   inactFile_kib = 0;
747   memTotal_kib = 0;
748   cmaFree_kib = 0;
749   cmaTotal_kib = 0;
750   g_resmgr.restMemFlag = FALSE;
751   g_resmgr.restCmaFlag = FALSE;
752   ret = get_meminfo();
753   // KiB -> Byte
754   // [Note] Unit of the value gotten by the meminfo is KiB
755   restMem_b = (mainFree_kib + inactFile_kib) * KIBIBYTE_TO_BYTE;
756
757   if (ret != 0) {
758     // Failed to get remaining memory info
759     FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "ResMgr get_meminfo Failed");
760     return;
761   }
762   g_resmgr.restMem = mainFree_kib + inactFile_kib;
763   g_resmgr.restMemFlag = TRUE;
764   g_resmgr.restCma = cmaFree_kib;
765   g_resmgr.restCmaFlag = TRUE;
766
767   if (g_resmgr.restMem < minRestMem) {
768     // Update minimum available memory
769     minRestMem = g_resmgr.restMem;
770   }
771   if (g_resmgr.restCma < minRestCma) {
772     // Update minimum available CMA
773     minRestCma = g_resmgr.restCma;
774   }
775
776   for (i = 0; i < RESM_INET_IF_MAX; i++) {
777     p_ssnInfo = &g_resmgr.ssnInfo[i];
778     if (!p_ssnInfo->useFlag) {
779       // Unused sessions
780       continue;
781     }
782     ssnId = i;
783
784     // Check event type
785     if (p_ssnInfo->reqEv.reqEvent != RESM_EV_MEM) {
786       // Other than memory monitoring
787       continue;
788     }
789     // Check free memory
790     if (p_ssnInfo->reqEv.prm.restMemThresh > restMem_b) {
791       // Issue event
792       ret = EV_set_flag(Resm_Flag_ID_Base + ssnId, RESM_EV_MEM);
793       if (ret != EV_OK) {  // LCOV_EXCL_BR_LINE 200: EV_set_flag will not return ng
794         // LCOV_EXCL_START 200: EV_set_flag will not return ng
795         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
796         FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__,
797                "ResMgr EV_set_flag Failed. ssnId[%d]", ssnId);
798         // LCOV_EXCL_STOP 200: EV_set_flag will not return ng
799       }
800     }
801   }
802
803   return;
804 }
805
806 void FlushMemInfo(void) {
807   FRAMEWORKUNIFIEDLOG(
808     ZONE_INFO,
809     __FUNCTION__,
810     "MEMORY Info(KB):<PEAK>REST(%d) [Memtotal(%d)] / CMA Info(KB):<PEAK>REST(%d) [CMAtotal(%d)]",
811     minRestMem, memTotal_kib, minRestCma, cmaTotal_kib);
812 }
813
814 /* Compare memory information */
815 static int32_t comp_meminfo_tbl(const void* data1, const void* data2) {
816   return strcmp(((const meminfo_tbl*) data1)->name,
817                 ((const meminfo_tbl*) data2)->name);
818 }
819
820 /* Get memory information */
821 static int32_t get_meminfo(void) {
822   int32_t meminfo_fd = -1;
823   char srch_name[16];
824   char buf[2048];
825   meminfo_tbl target = { srch_name, NULL };
826   meminfo_tbl* found;
827   char* head;
828   char* tail;
829   int32_t read_byte;
830   /* Strings must be in ascending order when adding entries to this table (for bsearch) */
831   static const meminfo_tbl mem_table[] = {
832     { "CmaFree", &cmaFree_kib },
833     { "CmaTotal", &cmaTotal_kib },
834     { "Inactive(file)", &inactFile_kib },
835     { "MemFree", &mainFree_kib },
836     { "MemTotal", &memTotal_kib },
837   };
838   const int32_t mem_table_count = sizeof(mem_table) / sizeof(meminfo_tbl);
839
840   if (meminfo_fd == -1) {
841     meminfo_fd = open(MEMINFO_FILE, O_RDONLY);
842     if (meminfo_fd == -1) {
843       fflush(NULL);
844       return -1;
845     }
846   }
847
848   lseek(meminfo_fd, 0L, SEEK_SET);
849   read_byte = read(meminfo_fd, buf, sizeof buf - 1);
850   if (read_byte < 0) {  // LCOV_EXCL_BR_LINE 200: if file exist, it will not be -1
851     // LCOV_EXCL_START 200: if file exist, it will not be -1
852     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
853     fflush(NULL);
854     close(meminfo_fd);
855     return -1;
856     // LCOV_EXCL_STOP 200: if file exis, it will not be -1
857   }
858   buf[read_byte] = '\0';
859
860   head = buf;
861   while (1) {
862     tail = strchr(head, ':');
863     if (!tail) {
864       break;
865     }
866
867     *tail = '\0';
868     if (strlen(head) >= sizeof(srch_name)) {
869       head = tail + 1;
870     } else {
871       strcpy(srch_name, head);  // NOLINT
872       found = reinterpret_cast<meminfo_tbl *>(bsearch(&target, mem_table, mem_table_count,
873                                       sizeof(meminfo_tbl), comp_meminfo_tbl));
874       head = tail + 1;
875       if (found) {
876         *(found->value) = strtoul(head, &tail, 10);
877       }
878     }
879     tail = strchr(head, '\n');
880     if (!tail)
881       break;
882     head = tail + 1;
883   }
884   close(meminfo_fd);
885
886   return 0;
887 }
888
889 /*********************************************************************************
890  * Network monitoring
891  *********************************************************************************/
892 /* Get system information */
893 static int32_t getInetStatus(RESM_INET_STATUS_t* p_iStatus) {
894   FILE* fh;
895   char buf[READLINE_MAX_SIZE];
896   char* tmp;
897   char name[IFNAMSIZ];
898   char hwaddr[HWADDR_LEN];
899   uint32_t rx_b;
900   uint32_t rx_pckt;
901   uint32_t rx_err;
902   uint32_t rx_drp;
903   uint32_t rx_fifo;
904   uint32_t rx_frm;
905   uint32_t rx_mlt;
906   uint32_t tx_b;
907   uint32_t tx_pckt;
908   uint32_t tx_err;
909   uint32_t tx_drp;
910   uint32_t tx_fifo;
911   uint32_t tx_cll;
912   uint32_t tx_crr;
913   int32_t ret;
914
915   // Open file
916   fh = fopen(PROCNET_DEV_FILE, "r");
917   if (fh == NULL) {
918     FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__,
919            "ResMgr getInetStatus() File Open Error. errno[%d]", errno);
920     return -1;
921   }
922
923   // Initialize interface count
924   p_iStatus->ifNum = 0;
925
926   while (fgets(buf, sizeof(buf), fh)) {
927     // Get Alias name
928     tmp = get_aliasName(name, buf);
929     if (tmp == NULL) {
930       // No alias name
931       continue;
932     }
933     // Get amount of receive/transmit data
934     ret = sscanf(tmp, "%u%u%u%u%u%u%u%*u%u%u%u%u%u%u%u", &rx_b, &rx_pckt,
935                  &rx_err, &rx_drp, &rx_fifo, &rx_frm, &rx_mlt, &tx_b, &tx_pckt,
936                  &tx_err, &tx_drp, &tx_fifo, &tx_cll, &tx_crr);
937     if (ret != 14) {  // LCOV_EXCL_BR_LINE 200: ret is always 14
938       // LCOV_EXCL_START 200: ret is always 14
939       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
940       FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__,
941              "ResMgr getInetStatus() GET Rx and Tx size Failed");
942       continue;
943       // LCOV_EXCL_STOP 200: ret is always 14
944     }
945     // Get hardware address
946     ret = get_hwaddr(name, hwaddr);
947     if (ret != 0) {  // LCOV_EXCL_BR_LINE 5: get_hwaddr will not return !0
948       // LCOV_EXCL_START 5: get_hwaddr will not return !0
949       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
950       FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__,
951              "ResMgr getInetStatus() GET hwaddr Failed");
952       continue;
953       // LCOV_EXCL_STOP 5: get_hwaddr will not return !0
954     }
955
956     // Set values in the system information structure
957     strcpy(p_iStatus->ifInfo[p_iStatus->ifNum].name, name);  // NOLINT
958     p_iStatus->ifInfo[p_iStatus->ifNum].rxSize = rx_b / BYTE_TO_KIBIBYTE;
959     p_iStatus->ifInfo[p_iStatus->ifNum].txSize = tx_b / BYTE_TO_KIBIBYTE;
960     memcpy(p_iStatus->ifInfo[p_iStatus->ifNum].hwaddr, hwaddr, HWADDR_LEN);
961
962     p_iStatus->ifNum++;
963
964     if (p_iStatus->ifNum >= RESM_INET_IF_MAX) {
965       break;
966     }
967   }
968
969   // Termination processing
970   fclose(fh);
971
972   if (p_iStatus->ifNum == 0) {
973     return -1;
974   }
975   return 0;
976 }
977
978 /* Get Alias name */
979 static char *get_aliasName(char* name, char* line) {
980   char* dot;
981   char* dotname;
982
983   while (isspace(*line)) {
984     line++;
985   }
986   while (*line) {
987     if (isspace(*line)) {
988       *name++ = '\0';
989       return NULL;
990     }
991
992     if (*line == ':') {
993       dot = line, dotname = name;
994       *name++ = *line++;
995
996       while (isdigit(*line)) {
997         *name++ = *line++;
998       }
999       if (*line != ':') {
1000         line = dot;
1001         name = dotname;
1002       }
1003       if (*line == '\0') {
1004         return NULL;
1005       }
1006       line++;
1007       break;
1008     }
1009     *name++ = *line++;
1010   }
1011   *name++ = '\0';
1012
1013   return line;
1014 }
1015
1016 /* Get hardware address */
1017 static int32_t get_hwaddr(char* name, char* hwaddr) {
1018   struct ifreq ifr;
1019   int32_t ret;
1020
1021   if (g_sock < 0) {  // LCOV_EXCL_BR_LINE 6: g_sock is not -1
1022     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1023     return -1;    // LCOV_EXCL_LINE 6: g_sock is not -1
1024   }
1025   // Initialization
1026   memset(&ifr, 0, sizeof(ifr));
1027
1028   // Set alias name
1029   strncpy(ifr.ifr_name, name, (sizeof(ifr.ifr_name) - 1));
1030
1031   // Get hardware address
1032   ret = ioctl(g_sock, SIOCGIFHWADDR, &ifr);
1033   if (ret < 0) {  // LCOV_EXCL_BR_LINE 5: ioctl error case
1034     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1035     return -1;  // LCOV_EXCL_LINE 5: ioctl error case
1036   }
1037   memcpy(hwaddr, ifr.ifr_hwaddr.sa_data, HWADDR_LEN);
1038
1039   return 0;
1040 }
1041
1042 /*********************************************************************************
1043  * CPU monitoring
1044  *********************************************************************************/
1045 // // CPU monitoring
1046 // static void watchCPU() {
1047 // Main processing of CPU monitoring
1048 static void watchCPUStatus() {
1049   unsigned long fifo_task_occ = 0;
1050   unsigned long tss_task_occ = 0;
1051   int32_t fifo_status = g_fifo_status;
1052   int32_t tss_status = g_tss_status;
1053   int32_t cpu_load_status = CPU_TASK_INIT;
1054
1055 //  int32_t ret;
1056 //  static int32_t cpuLogTimer = 0;
1057   if ((g_fifo_status == STATUS_CHECK_CPU) || (g_tss_status == STATUS_CHECK_CPU)) {
1058     watchCPU();
1059
1060 //  if (cpuLogTimer > 0) {  // LCOV_EXCL_BR_LINE 6:Because the condition cannot be set
1061 //    // Make to progress the timer
1062 //    cpuLogTimer -= WTC_CPU_INTERVAL;  // LCOV_EXCL_LINE 6:Because the condition cannot be set
1063 //  }
1064     if (g_cpuloadRate1000 >= CPU_LOAD_THRESHOLD) {
1065       FRAMEWORKUNIFIEDLOG(ZONE_INFO, __FUNCTION__, "CPU TOTAL:(%d.%d%%)",g_cpuloadRate1000/10, g_cpuloadRate1000%10);
1066       int i;
1067       int32_t cpuloadRate1000;
1068       for (i = 1; i < g_cpu_num; i++) {
1069         char buf[16];
1070         cpuloadRate1000 = calc_cpuloadRate_each(i);
1071         sprintf (buf, "%s(%d.%d%%) ", g_cpuload[i].cpuname, cpuloadRate1000/10, cpuloadRate1000%10);
1072         FRAMEWORKUNIFIEDLOG (ZONE_INFO, __FUNCTION__, "%s", buf);
1073       }
1074       if (g_fifo_status == STATUS_CHECK_CPU) {  // LCOV_EXCL_BR_LINE 6: g_fifo_status must be STATUS_CHECK_CPU
1075         fifo_status = STATUS_WATCH_PROCESS;
1076         g_fifo_timer = 0;
1077       }
1078       if (g_tss_status == STATUS_CHECK_CPU) {  // LCOV_EXCL_BR_LINE 6: g_tss_status must be STATUS_CHECK_CPU
1079         tss_status = STATUS_WATCH_PROCESS;
1080         g_tss_timer = 0;
1081       }
1082       if ((g_fifo_status != STATUS_WATCH_PROCESS ) && ( g_tss_status != STATUS_WATCH_PROCESS)) {  // LCOV_EXCL_BR_LINE 6: g_fifo_status must be STATUS_CHECK_CPU and g_tss_status must be STATUS_CHECK_CPU   // NOLINT[whitespace/line_length]
1083         logging_cpuload_custom(CPU_TASK_INIT);
1084       }
1085     }
1086   }
1087
1088 #if 0
1089   // Get CPU usage
1090   if (g_resmgr.cpuloadRate == CPULOAD_INVALID) {
1091     // First time
1092     init_cpuload();
1093     ret = get_cpuload(g_cpuload);
1094     if (ret == 0) {  // LCOV_EXCL_BR_LINE 5: get_cpuload will not return -1
1095       g_resmgr.cpuloadRate = CPULOAD_READY;
1096     } else {
1097       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1098       FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "watchCPU() Get cpuload Failed");  // LCOV_EXCL_LINE 5: get_cpuload will not return -1  // NOLINT[whitespace/line_length]
1099     }
1100 #endif
1101   if ((g_fifo_status == STATUS_WATCH_PROCESS) || (g_tss_status == STATUS_WATCH_PROCESS)) {
1102     if (g_fifo_status == STATUS_WATCH_PROCESS) {
1103       g_fifo_timer = g_fifo_timer + WTC_CPU_INTERVAL;
1104       if ((g_fifo_timer == WTC_CPU_INTERVAL) || (g_fifo_timer >= FIFO_TIMER_LIMIT)) {  // LCOV_EXCL_BR_LINE 200: g_fifo_timer must be bigger than WTC_CPU_INTERVAL/FIFO_TIMER_LIMIT  // NOLINT[whitespace/line_length]
1105         cpu_load_status = CPU_TASK_SHOW_AF;
1106       } else {
1107         // LCOV_EXCL_START 200: g_fifo_timer must be bigger than WTC_CPU_INTERVAL/FIFO_TIMER_LIMIT
1108         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1109         logging_cpuload_custom(FIFO_TASK_SHOW);
1110         // LCOV_EXCL_STOP
1111       }
1112     }
1113 #if 0
1114     return;
1115   } else {
1116     memcpy(g_cpuload_pre, g_cpuload, sizeof(*g_cpuload_pre)*g_cpu_num);
1117     ret = get_cpuload(g_cpuload);
1118     if (ret != 0) {  // LCOV_EXCL_BR_LINE 5: get_cpuload will not return -1
1119       // LCOV_EXCL_START 5: get_cpuload will not return -1
1120       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1121       FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "watchCPU() Get cpuload Failed");
1122       return;
1123       // LCOV_EXCL_STOP 5: get_cpuload will not return -1
1124 #endif
1125     if (g_tss_status == STATUS_WATCH_PROCESS) {
1126       g_tss_timer = g_tss_timer + WTC_CPU_INTERVAL;
1127       if ((g_tss_timer == WTC_CPU_INTERVAL) || (g_tss_timer >= TSS_TIMER_LIMIT)) {
1128         cpu_load_status = CPU_TASK_SHOW_AF;
1129       } else {
1130         logging_cpuload_custom(TSS_TASK_SHOW);
1131       }
1132     }
1133 #if 0
1134   }
1135   // Calculate CPU usage (Notes! Return as a thousandth rate(10 times of %)
1136   g_cpuloadRate1000 = calc_cpuloadRate();
1137   g_resmgr.cpuloadRate = g_cpuloadRate1000 / 10;
1138
1139   ret = chk_logging(g_resmgr.cpuloadRate, cpuLogTimer);
1140   if (ret == CPULOG_LOGGING) {
1141     // Logging
1142 #endif
1143     if (cpu_load_status == CPU_TASK_SHOW_AF) {
1144 #if 0
1145       int i;
1146       int32_t cpuloadRate1000;
1147       char *cpunames = (char *) malloc(  // NOLINT
1148           sizeof("[CpuHighLoad]") + (sizeof("cpuXX(xxx%) ") * g_cpu_num));
1149       cpuloadRate1000 = calc_cpuloadRate();
1150       sprintf(cpunames, "[CpuHighLoad]%s(%d%%) ", g_cpuload[0].cpuname, cpuloadRate1000/10);  // NOLINT
1151       for (i = 1; i < g_cpu_num; i++) {
1152         char buf[16];
1153         cpuloadRate1000 = calc_cpuloadRate_each(i);
1154         sprintf(buf, "%s(%d%%) ", g_cpuload[i].cpuname, cpuloadRate1000 / 10);  // NOLINT
1155         strcat(cpunames, buf);  // NOLINT
1156       }
1157       free(cpunames);
1158       FRAMEWORKUNIFIEDLOG(ZONE_INFO, __FUNCTION__, "%s", cpunames);
1159     }
1160 #endif
1161       logging_cpuload_custom(cpu_load_status);
1162     }
1163     if (g_fifo_status == STATUS_WATCH_PROCESS) {
1164       fifo_task_occ = logging_cpuload_custom(CPU_FIFO_TASK_GET_OCCUPANCY);
1165       if ((fifo_task_occ >= TASK_STAT_THRESHOLD) && (g_fifo_timer >= FIFO_TIMER_LIMIT)) {
1166         fifo_status = STATUS_IDOL;
1167         g_fifo_timer = 0;
1168         exec_perf(logging_cpuload_custom(CPU_FIFO_TASK_GET_ID));
1169       } else if (fifo_task_occ < TASK_STAT_THRESHOLD) {
1170         fifo_status = STATUS_CHECK_CPU;
1171         g_fifo_timer = 0;
1172         logging_cpuload_custom(CPU_FIFO_TASK_GET_ID);
1173       }
1174     }
1175     if (g_tss_status == STATUS_WATCH_PROCESS) {
1176       tss_task_occ = logging_cpuload_custom(CPU_TSS_TASK_GET_OCCUPANCY);
1177       if ((tss_task_occ >= TASK_STAT_THRESHOLD) && (g_tss_timer >= TSS_TIMER_LIMIT)) {
1178         tss_status = STATUS_IDOL;
1179         g_tss_timer = 0;
1180         exec_perf(logging_cpuload_custom(CPU_TSS_TASK_GET_ID));
1181       } else if(tss_task_occ < TASK_STAT_THRESHOLD) {
1182         tss_status = STATUS_CHECK_CPU;
1183         g_tss_timer = 0;
1184         logging_cpuload_custom(CPU_TSS_TASK_GET_ID);
1185       }
1186     }
1187 #if 0
1188     logging_cpuload_custom();
1189     logging_cpuload();
1190     // Set timer
1191     cpuLogTimer = CPU_HIGH_LOAD_LOG_FREQ;
1192   } else if (ret == CPULOG_TIMER_CLEAR) {
1193     // Clear Timer
1194     cpuLogTimer = 0;
1195   }
1196
1197   return;
1198 #endif
1199     logging_cpuload_custom(CPU_TASK_SHOW_BF);
1200   }
1201   if ((g_fifo_status == STATUS_IDOL) || (g_tss_status == STATUS_IDOL)) {
1202     if (g_fifo_status == STATUS_IDOL) {
1203       g_fifo_timer = g_fifo_timer + WTC_CPU_INTERVAL;
1204       if (g_fifo_timer >= CPU_HIGH_LOAD_LOG_FREQ) {
1205         fifo_status = STATUS_CHECK_CPU;
1206         g_fifo_timer = 0;
1207       }
1208     }
1209     if (g_tss_status == STATUS_IDOL) {
1210       g_tss_timer = g_tss_timer + WTC_CPU_INTERVAL;
1211       if (g_tss_timer >= CPU_HIGH_LOAD_LOG_FREQ) {
1212         tss_status = STATUS_CHECK_CPU;
1213         g_tss_timer = 0;
1214       }
1215     }
1216   }
1217   g_fifo_status = fifo_status;
1218   g_tss_status = tss_status;
1219
1220   return;
1221 }
1222
1223
1224
1225 // CPU monitoring
1226 static void
1227 watchCPU() {
1228   int32_t ret;
1229
1230   memcpy(g_cpuload_pre, g_cpuload, sizeof(*g_cpuload_pre)*g_cpu_num);
1231   ret = get_cpuload(g_cpuload);
1232   if ( ret != 0 ) {
1233     FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "watchCPU() Get cpuload Failed");
1234     g_cpuloadRate1000 = 0;
1235   } else {
1236     // Calculate CPU usage (Notes! Return as a thousandth rate(10 times of percentage)
1237     g_cpuloadRate1000 = calc_cpuloadRate();
1238   }
1239
1240   return;
1241 }
1242
1243
1244 static void init_cpuload(void) {
1245   int fd;
1246   char buf[READ_MAX_SIZE];
1247   int32_t ret;
1248   CPU_INFO_t p_cpu;
1249   ssize_t rsize;
1250   char *p, *ep;
1251   struct timespec req = { 0, 1000000 };  // 1msec
1252
1253   g_cpu_num = 0;
1254   g_cpuload_pre = NULL;
1255
1256   fd = open(PROC_STAT_FILE, O_RDONLY);
1257   if (fd == -1) {  // LCOV_EXCL_BR_LINE 5: open error case
1258     // LCOV_EXCL_START 5: open error case
1259     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1260     FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "ResMgr File Open Error. errno[%d]",
1261            errno);
1262     return;
1263     // LCOV_EXCL_STOP 5: open error case
1264   }
1265   rsize = read(fd, buf, sizeof(buf));
1266   if (rsize == -1) {  // LCOV_EXCL_BR_LINE 5: read error case
1267     // LCOV_EXCL_START 5: read error case
1268     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1269     FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "ResMgr File Read Error. errno[%d]",
1270            errno);
1271     close(fd);
1272     return;
1273     // LCOV_EXCL_STOP 5: read error case
1274   }
1275   nanosleep(&req, NULL);
1276   p = buf;
1277   ep = buf + rsize;
1278   while (p < ep) {
1279     if (strncmp(p, "cpu", 3) == 0) {
1280       ret = sscanf(p, "%8s %d %d %d %d %d %d %d %d %d %d", &p_cpu.cpuname[0],
1281                    &p_cpu.user, &p_cpu.nice, &p_cpu.system, &p_cpu.idle,
1282                    &p_cpu.iowait, &p_cpu.irq, &p_cpu.softirq, &p_cpu.steal,
1283                    &p_cpu.guest, &p_cpu.guest_nice);
1284       if (ret < 11) {  // LCOV_EXCL_BR_LINE 200: ret will always 11
1285         // LCOV_EXCL_START 200: ret will always 11
1286         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1287         FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__,
1288                "ResMgr get_cpuload() File Read Error");
1289         close(fd);
1290         return;
1291         // LCOV_EXCL_STOP 200: ret will always 11
1292       }
1293       g_cpu_num++;
1294       while (++p < ep) {
1295         if (*p == LF) {
1296           p++;
1297           break;
1298         }
1299       }
1300     } else {
1301       break;
1302     }
1303   }
1304   close(fd);
1305
1306   g_cpuload_pre = reinterpret_cast<CPU_INFO_t *>(malloc(sizeof(CPU_INFO_t) * g_cpu_num));
1307   g_cpuload = reinterpret_cast<CPU_INFO_t *>(malloc(sizeof(CPU_INFO_t) * g_cpu_num));
1308   if ((g_cpuload_pre == NULL) || (g_cpuload == NULL)) {  // LCOV_EXCL_BR_LINE 5: malloc error case
1309     // LCOV_EXCL_START 5: malloc error case
1310     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1311     FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__,
1312            "ResMgr malloc Error. g_cpu_num[%d] errno[%d]", g_cpu_num, errno);
1313     return;
1314     // LCOV_EXCL_STOP 5: malloc error case
1315   }
1316
1317   FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "ResMgr cpu_num:%d", g_cpu_num);
1318
1319   return;
1320 }
1321
1322 // Get CPU usage
1323 static int32_t get_cpuload(CPU_INFO_t* p_cpu) {
1324   int fd;
1325   char buf[READ_MAX_SIZE];
1326   int32_t ret;
1327   int i = 0;
1328   ssize_t rsize;
1329   char *p, *ep;
1330   struct timespec req = { 0, 1000000 };  // 1msec
1331
1332   // Open file
1333   fd = open(PROC_STAT_FILE, O_RDONLY);
1334   if (fd == -1) {  // LCOV_EXCL_BR_LINE 5: open's error case
1335     // LCOV_EXCL_START 5: open's error case
1336     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1337     FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__,
1338            "ResMgr get_cpuload() File Open Error. errno[%d]", errno);
1339     return -1;
1340     // LCOV_EXCL_STOP
1341   }
1342   rsize = read(fd, buf, sizeof(buf));
1343   if (rsize == -1) {  // LCOV_EXCL_BR_LINE 5: read error case
1344     // LCOV_EXCL_START 5: read error case
1345     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1346     FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "ResMgr File Read Error. errno[%d]",
1347            errno);
1348     close(fd);
1349     return -1;
1350     // LCOV_EXCL_STOP 5: read error case
1351   }
1352   nanosleep(&req, NULL);
1353   p = buf;
1354   ep = buf + rsize;
1355   while (p < ep) {
1356     if (strncmp(p, "cpu", 3) == 0) {
1357       ret = sscanf(p, "%8s %d %d %d %d %d %d %d %d %d %d", &p_cpu[i].cpuname[0],
1358                    &p_cpu[i].user, &p_cpu[i].nice, &p_cpu[i].system,
1359                    &p_cpu[i].idle, &p_cpu[i].iowait, &p_cpu[i].irq,
1360                    &p_cpu[i].softirq, &p_cpu[i].steal, &p_cpu[i].guest,
1361                    &p_cpu[i].guest_nice);
1362       if (ret < 11) {  // LCOV_EXCL_BR_LINE 200: ret will always 11
1363         // LCOV_EXCL_START 200: ret will always 11
1364         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1365         FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__,
1366                "ResMgr get_cpuload() File Read Error");
1367         close(fd);
1368         return -1;
1369         // LCOV_EXCL_STOP 200: ret will always 11
1370       }
1371       i++;
1372       while (++p < ep) {
1373         if (*p == LF) {
1374           p++;
1375           break;
1376         }
1377       }
1378     } else {
1379       break;
1380     }
1381   }
1382   close(fd);
1383
1384   return 0;
1385 }
1386
1387 // Calcurate CPU usage
1388 static int32_t calc_cpuloadRate(void) {
1389   int val;
1390   int val_others;
1391   int total;
1392   int rate;
1393   CPU_INFO_t* info;
1394   CPU_INFO_t* info_pre;
1395
1396   info = &g_cpuload[0];
1397   info_pre = &g_cpuload_pre[0];
1398
1399   val = (info->user - info_pre->user)
1400       + (info->system - info_pre->system)
1401       + (info->irq - info_pre->irq)
1402       + (info->softirq - info_pre->softirq);
1403
1404   val_others = (info->idle - info_pre->idle)
1405       + (info->iowait - info_pre->iowait);
1406
1407   total = val + val_others;
1408   rate = (total > 0) ? (val*1000 / total) : 0;
1409
1410   return rate;
1411 }
1412
1413 // Calcurate CPU usage for each CPU
1414 static int32_t calc_cpuloadRate_each(int num) {
1415   int val, valn;
1416   int rate;
1417   CPU_INFO_t* info;
1418   CPU_INFO_t* info_pre;
1419
1420   // cpu
1421   info = &g_cpuload[0];
1422   info_pre = &g_cpuload_pre[0];
1423   val = (info->user - info_pre->user)
1424       + (info->system - info_pre->system)
1425       + (info->irq - info_pre->irq)
1426       + (info->softirq - info_pre->softirq);
1427
1428   // cpu-num
1429   info = &g_cpuload[num];
1430   info_pre = &g_cpuload_pre[num];
1431   valn = (info->user - info_pre->user)
1432     + (info->system - info_pre->system)
1433     + (info->softirq - info_pre->softirq);
1434
1435   rate = valn * 1000 / val;
1436   return rate;
1437 }
1438
1439
1440 //// Logging check at CPU overload
1441 //static int32_t chk_logging(int32_t cpuload, int32_t timer) {
1442 //  if (cpuload >= CPU_LOAD_THRESHOLD) {
1443 //    if (timer > 0) {
1444 //      return CPULOG_NO_LOGGING;
1445 //    }
1446 //    return CPULOG_LOGGING;
1447 //  }
1448 //
1449 //  return CPULOG_TIMER_CLEAR;
1450 //}
1451
1452
1453 // Check if cmd to perf
1454   // LCOV_EXCL_START 8: dead code
1455 bool valid_perf_cmd(char *buf) {  // LCOV_EXCL_BR_LINE 8: dead code
1456   const char *cmd2exclude[] = { "top", "init", "bash", NULL };
1457   char cmdstr[64];
1458
1459   for (int i = 0;; i++) {
1460     if (cmd2exclude[i] == NULL) {
1461       break;
1462     }
1463     sprintf(cmdstr, " %s ", cmd2exclude[i]);  // NOLINT
1464     if (strstr(buf, cmdstr) == NULL) {
1465       continue;
1466     } else {
1467       return false;
1468     }
1469   }
1470   return true;
1471 }
1472   // LCOV_EXCL_STOP 8: dead code
1473
1474 //// exec perf to pids
1475 //static pid_t pids[PERF_MAX_PROCS];
1476
1477
1478 static bool lower_sched_priority(int niceval) {
1479   struct sched_param sparam = { };
1480   sparam.sched_priority = 0;
1481   if (sched_setscheduler(0, SCHED_OTHER, &sparam) == -1) {  // LCOV_EXCL_BR_LINE 5: sched_setscheduler's error case
1482     // LCOV_EXCL_START 5: sched_setscheduler's error case
1483     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1484     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Failed change scheduler to TSS, errno=%d",
1485            errno);
1486     return false;
1487     // LCOV_EXCL_STOP
1488   }
1489   if (nice(niceval) == -1) {  // LCOV_EXCL_BR_LINE 5: nice's error case
1490     // LCOV_EXCL_START 5: nice's error case
1491     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1492     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Failed to add nice val %d, errno=%d",
1493            niceval, errno);
1494     return false;
1495     // LCOV_EXCL_STOP
1496   }
1497   return true;
1498 }
1499
1500 /*********************************************************************************
1501  * exec_perf sub function RECORD perf data processing
1502  *********************************************************************************/
1503 static void exec_perf_Record_Perf_Data(
1504     pid_t* c_pids, char* perf_file, char* pidstr, int* status,
1505
1506 //    char pnames[PERF_MAX_PROCS][PERF_PNAME_MAX]) {
1507     pid_t pids[PERF_MAX_PROCS]) {
1508
1509   int i;
1510   int fd;
1511   pid_t term_pid;
1512   int waitret;
1513   bool do_sigkill = false;
1514
1515   FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "+");
1516
1517   /* RECORD perf data */
1518   for (i = 0; i < PERF_MAX_PROCS; i++) {
1519     if (pids[i] <= 0) {
1520       break;
1521     }
1522     sprintf(perf_file, PERF_FILE"%06d", pids[i]);  // NOLINT
1523     sprintf(pidstr, "%d", pids[i]);  // NOLINT
1524     if ((c_pids[i] = fork()) == 0) {
1525       if (lower_sched_priority(CPULOAD_NICEVAL) == false) {  // LCOV_EXCL_BR_LINE 200: lower_sched_priority() must be true
1526         // LCOV_EXCL_START 200: lower_sched_priority() must be true
1527         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1528         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Failed to lower scheduler-1");
1529         exit(1);
1530         // LCOV_EXCL_STOP
1531       }
1532       if (setuid(0) == -1) {  // LCOV_EXCL_BR_LINE 5: setuid's error case
1533         // LCOV_EXCL_START 5: setuid's error case
1534         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1535         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Failed to setuid(0)-1, errno=%d",
1536                errno);
1537         exit(1);
1538         // LCOV_EXCL_STOP
1539       }
1540       // Redirect STDERR
1541       fd = open("/dev/null", O_WRONLY);
1542       if (fd > 0) {  // LCOV_EXCL_BR_LINE 5: open's error case
1543         dup2(fd, 2);
1544       }
1545       // Exec perf
1546       execl(PERF_PATH, basename(PERF_PATH), "record", "-p", pidstr, "-o",
1547             perf_file, NULL);
1548       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Failed to execl %s record, errno=%d",
1549              PERF_PATH,
1550              errno);
1551       exit(1);
1552     }
1553     if (c_pids[i] == (pid_t) -1) {  // LCOV_EXCL_BR_LINE 5: fork's error case
1554       // LCOV_EXCL_START 5: fork's error case
1555       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1556       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Failed to fork-1, errno=%d", errno);
1557       continue;
1558       // LCOV_EXCL_STOP
1559     }
1560     // Kill perf after PERF_RECORD_SPAN sec
1561     // (Killed by child process to avoid making resm process super-user with setuid.)
1562     if ((term_pid = fork()) == 0) {
1563       const struct timespec delay = { PERF_RECORD_SPAN, 0 };
1564       if (setuid(0) == -1) {  // LCOV_EXCL_BR_LINE 5: setuid's error case
1565         // LCOV_EXCL_START 5: setuid's error case
1566         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1567         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Failed to setuid(0)-2, errno=%d",
1568                errno);
1569         exit(1);
1570         // LCOV_EXCL_STOP
1571       }
1572       nanosleep(&delay, NULL);  // Let perf record run for a while before kill it.
1573       if (kill(c_pids[i], SIGINT) == -1) {  // LCOV_EXCL_BR_LINE 5: kill's error case
1574         // LCOV_EXCL_START 5: kill's error case
1575         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1576         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
1577                "Failed to kill(SIGINT), pid=%d, errno=%d", (int) c_pids[i],
1578                errno);
1579         // LCOV_EXCL_STOP
1580       }
1581       nanosleep(&delay, NULL);  // Allow perf to do ending procedure.
1582       exit(0);
1583     } else if (term_pid == (pid_t) -1) {  // LCOV_EXCL_BR_LINE 5: fork's error case
1584       // LCOV_EXCL_START 5: fork's error case
1585       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1586       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Failed to fork-2, errno=%d", errno);
1587       continue;
1588       // LCOV_EXCL_STOP
1589     } else {
1590       if (waitpid(term_pid, status, 0) == -1) {  // LCOV_EXCL_BR_LINE 5: waitpid's error case
1591         // LCOV_EXCL_START 5: waitpid's error case
1592         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1593         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
1594                "Failed to waitpid of killer %d, errno=%d", term_pid, errno);
1595         continue;
1596         // LCOV_EXCL_STOP
1597       }
1598     }
1599     FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "");
1600     // NOT block even if perf is not terminated
1601     if ((waitret = waitpid(c_pids[i], status, WNOHANG)) == -1) {  // LCOV_EXCL_BR_LINE 5: waitpid's error case
1602       // LCOV_EXCL_START 5: waitpid's error case
1603       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1604       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Failed to waitpid of RECORD %d, errno=%d",
1605              c_pids[i], errno);
1606       // LCOV_EXCL_STOP
1607     } else if (waitret == 0) {
1608       // NOT exited
1609       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Failed to terminate perf record, pid=%d",
1610              c_pids[i]);
1611       pids[i] = -2;  // Skip following sequences
1612       do_sigkill = true;
1613     } else if (WEXITSTATUS(*status) != 0 && WEXITSTATUS(*status) != 2) {
1614
1615 //      FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
1616 //             "perf record %d exited abnormally, target=%s(%d), status=%d",
1617 //             c_pids[i], pnames[i], pids[i], WEXITSTATUS(*status));
1618       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
1619              "perf record %d exited abnormally, target=(%d), status=%d",
1620              c_pids[i], pids[i], WEXITSTATUS(*status));
1621
1622       pids[i] = -2;  // Skip following sequences
1623       do_sigkill = false;
1624     }
1625     FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "");
1626     if (pids[i] == -2) {
1627       if ((term_pid = fork()) == 0) {
1628         const struct timespec delay = { PERF_RECORD_SPAN, 0 };
1629         if (setuid(0) == -1) {  // LCOV_EXCL_BR_LINE 5: setuid's error case
1630           // LCOV_EXCL_START 5: setuid's error case
1631           AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1632           FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Failed to setuid(0)-2B, errno=%d",
1633                  errno);
1634           exit(1);
1635           // LCOV_EXCL_STOP
1636         }
1637         // Kill "perf record" by SIGKILL signal
1638         if (do_sigkill) {
1639           int sigret = kill(c_pids[i], SIGKILL);
1640           if (sigret == 0) {  // LCOV_EXCL_BR_LINE 5: kill case
1641             FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
1642                    "SIGKILL has been sent to perf record process, pid=%d",
1643                    c_pids[i]);
1644           } else {
1645             // LCOV_EXCL_START 5: kill case
1646             AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1647             FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
1648                    "sending SIGKILL to perf record failed, pid=%d, errno=%d",
1649                    c_pids[i], errno);
1650             // LCOV_EXCL_STOP 5: kill case
1651           }
1652         }
1653         nanosleep(&delay, NULL);
1654         // remove perf data file possibly made
1655         unlink(perf_file);
1656         FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "");
1657         exit(0);
1658       } else if (term_pid == (pid_t) -1) {  // LCOV_EXCL_BR_LINE 5: fork's error case
1659         // LCOV_EXCL_START 5: fork's error case
1660         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1661         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Failed to fork-2B, errno=%d", errno);
1662         // LCOV_EXCL_STOP
1663       } else {
1664         if (waitpid(term_pid, status, 0) == -1) {    // LCOV_EXCL_BR_LINE 5: waitpid's error case
1665           // LCOV_EXCL_START 5: waitpid's error case
1666           AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1667           FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
1668                  "Failed to waitpid of killer-2 %d, errno=%d", term_pid, errno);
1669           // LCOV_EXCL_STOP
1670         }
1671         if (do_sigkill) {
1672           if ((waitret = waitpid(c_pids[i], status, WNOHANG)) == -1) { // LCOV_EXCL_BR_LINE 5: waitpid's error case
1673             // LCOV_EXCL_START 5: waitpid's error case
1674             AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1675             FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
1676                    "Failed to waitpid of RECORD(2) %d, errno=%d", c_pids[i],
1677                    errno);
1678             // LCOV_EXCL_STOP
1679           } else if (waitret == 0) {
1680             FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
1681                    "Failed to terminate perf record by SIGKILL, pid=%d",
1682                    c_pids[i]);
1683           }
1684         }
1685       }
1686     }
1687   }
1688   FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "");
1689 }
1690
1691 /*********************************************************************************
1692  * exec_perf sub function make perf file available to default user processing
1693  *********************************************************************************/
1694
1695 //static int32_t exec_perf_Make_Perf_File(pid_t* c_pids, char* perf_file) {
1696 static int32_t exec_perf_Make_Perf_File(pid_t* c_pids, char* perf_file, pid_t pids[PERF_MAX_PROCS]) {
1697
1698   int i;
1699
1700   /* make perf file available to default user */
1701   if ((c_pids[0] = fork()) == 0) {
1702     if (setuid(0) == -1) {  // LCOV_EXCL_BR_LINE 5: setuid's error case
1703       // LCOV_EXCL_START 5: setuid's error case
1704       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1705       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Failed to setuid(0)-3, errno=%d", errno);
1706       exit(1);
1707       // LCOV_EXCL_STOP
1708     }
1709     for (i = 0; i < PERF_MAX_PROCS; i++) {
1710       if (pids[i] == -2) {
1711         // killed by SIGKILL
1712         continue;
1713       }
1714       if (pids[i] <= 0) {
1715         break;
1716       }
1717       sprintf(perf_file, PERF_FILE"%06d", pids[i]);  // NOLINT
1718       if (chmod(perf_file, 0666) != 0) {  // LCOV_EXCL_BR_LINE 5: chmod's error case
1719         // LCOV_EXCL_START 5: chmod's error case
1720         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1721         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Failed to chmod %s, errno=%d\n",
1722                perf_file, errno);
1723         // LCOV_EXCL_STOP
1724       }
1725     }
1726     exit(0);
1727   }
1728   if (c_pids[0] == (pid_t) -1) {  // LCOV_EXCL_BR_LINE 5: fork's error case
1729     // LCOV_EXCL_START 5: fork's error case
1730     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1731     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Failed to fork-3, errno=%d", errno);
1732     return -1;
1733     // LCOV_EXCL_STOP
1734   }
1735   if (waitpid(c_pids[0], NULL, 0) == -1) {  // LCOV_EXCL_BR_LINE 5: waitpid's error case
1736     // LCOV_EXCL_START 5: waitpid's error case
1737     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1738     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Failed to waitpid of CHMOD %d, errno=%d\n",
1739            c_pids[0], errno);
1740   // LCOV_EXCL_STOP
1741   }
1742   FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "");
1743   return 0;
1744 }
1745
1746 /*********************************************************************************
1747  * exec_perf sub function REPORT perf data into dump file processing
1748  *********************************************************************************/
1749 static void exec_perf_Report_Perf_Data(pid_t* c_pids, char* perf_file,
1750
1751 //                                       char* perf_dump, int* status) {
1752                                        char* perf_dump, int* status, pid_t pids[PERF_MAX_PROCS]) {
1753
1754   int i;
1755   int fd;
1756   int waitret;
1757
1758   FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "");
1759   /* REPORT perf data into dump file */
1760   for (i = 0; i < PERF_MAX_PROCS; i++) {
1761     const struct timespec delay = { PERF_REPORT_DELAY, 0 };
1762     if (pids[i] == -2) {
1763       // killed by SIGKILL
1764       continue;
1765     }
1766     if (pids[i] <= 0) {
1767       break;
1768     }
1769     sprintf(perf_file, PERF_FILE"%06d", pids[i]);  // NOLINT
1770     sprintf(perf_dump, PERF_DUMP"%06d", pids[i]);  // NOLINT
1771     if ((c_pids[i] = fork()) == 0) {
1772       if (lower_sched_priority(CPULOAD_NICEVAL) == false) {  // LCOV_EXCL_BR_LINE 200: lower_sched_priority() will not return false
1773         // LCOV_EXCL_START 200: lower_sched_priority() will not return false
1774         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1775         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Failed to lower scheduler-2");
1776         exit(1);
1777         // LCOV_EXCL_STOP
1778       }
1779       if ((fd = open(perf_dump, (O_CREAT | O_WRONLY), 0666)) < 0) {  // LCOV_EXCL_BR_LINE 5: open error case
1780         // LCOV_EXCL_START 5: open error case
1781         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1782         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Failed to open %s, errno=%d\n",
1783                perf_dump, errno);
1784         // LCOV_EXCL_STOP 5: open error case
1785       } else {
1786         // Redirect STDOUT
1787         dup2(fd, 1);
1788         close(fd);
1789         // Redirect STDERR
1790         fd = open("/dev/null", O_WRONLY);
1791         if (fd > 0) {  // redirect stderr  // LCOV_EXCL_BR_LINE 5: open's error case
1792           dup2(fd, 2);
1793           close(fd);
1794         }
1795         // Exec perf
1796         FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "execl perf report");
1797         execl(PERF_PATH, basename(PERF_PATH), "report", "-i", perf_file, NULL);
1798         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Failed to execl %s report, errno=%d",
1799                PERF_PATH,
1800                errno);
1801       }
1802       exit(1);
1803     }
1804     if (c_pids[i] == (pid_t) -1) {  // LCOV_EXCL_BR_LINE 5: fork's error case
1805       // LCOV_EXCL_START 5: fork's error case
1806       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1807       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Failed to fork-4, errno=%d", errno);
1808       continue;
1809       // LCOV_EXCL_STOP
1810     }
1811     int ii = 0;
1812     for (; ii < PERF_REPORT_RETRY; ii++) {
1813       nanosleep(&delay, NULL);  // Make sure waitpid() to killer returns after perf process exited.
1814       if ((waitret = waitpid(c_pids[i], status, WNOHANG)) == -1) {  // LCOV_EXCL_BR_LINE 5: waitpid's error case
1815         // LCOV_EXCL_START 5: waitpid's error case
1816         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1817         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
1818                "Failed to waitpid for REPORT %d, errno=%d", c_pids[i], errno);
1819         pids[i] = -2;  // Skip FRAMEWORKUNIFIEDLOG perf data
1820         break;
1821         // LCOV_EXCL_STOP
1822       } else if (waitret == c_pids[i]) {
1823         break;
1824       }
1825     }
1826     if (ii >= PERF_REPORT_RETRY) {
1827       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "perf report Failed to exit, pid=%d",
1828              c_pids[i]);
1829       pids[i] = -2;  // Skip FRAMEWORKUNIFIEDLOG perf data
1830     }
1831     if (pids[i] == -2) {
1832       // Terminate perf report with SIGKILL
1833       const struct timespec delay = { PERF_RECORD_SPAN, 0 };
1834       int sigret = kill(c_pids[i], SIGKILL);
1835       if (sigret != 0) {  // LCOV_EXCL_BR_LINE 5: kill's error case
1836         // LCOV_EXCL_START 5: kill's error case
1837         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1838         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
1839                "Failed in sending SIGKILL to perf report, pid=%d, errno=%d",
1840                c_pids[i], errno);
1841         // LCOV_EXCL_STOP
1842       } else {
1843         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
1844                "SIGKILL has been sent to perf report process, pid=%d",
1845                c_pids[i]);
1846       }
1847       nanosleep(&delay, NULL);  // Make sure waitpid() to killer returns after perf process exited.
1848       if ((waitret = waitpid(c_pids[i], status, WNOHANG)) == -1) {  // LCOV_EXCL_BR_LINE 5: waitpid's error case
1849         // LCOV_EXCL_START 5: waitpid's error case
1850         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1851         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
1852                "Failed to waitpid of REPORT(2) %d, errno=%d", c_pids[i], errno);
1853         // LCOV_EXCL_STOP
1854       } else if (waitret == 0) {
1855         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
1856                "Failed to terminate perf report by SIGKILL, pid=%d", c_pids[i]);
1857       }
1858       // Cleanup
1859       unlink(perf_dump);
1860       unlink(perf_file);
1861     }
1862   }
1863 }
1864
1865 /*********************************************************************************
1866  * exec_perf FRAMEWORKUNIFIEDLOG perf data processing
1867  *********************************************************************************/
1868 static void exec_perf_Resourcemanagerlog_Perf_Data(
1869     char* perf_file, char* perf_dump,
1870
1871 //    char pnames[PERF_MAX_PROCS][PERF_PNAME_MAX]) {
1872     pid_t pids[PERF_MAX_PROCS]) {
1873
1874   int i;
1875   int perf_lines;
1876   char buf[READLINE_MAX_SIZE];
1877   FILE *rfd;
1878
1879   FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "");
1880   /* FRAMEWORKUNIFIEDLOG perf data */
1881   for (i = 0; i < PERF_MAX_PROCS; i++) {
1882     if (pids[i] == -2) {
1883       // killed by SIGKILL
1884       continue;
1885     }
1886     if (pids[i] <= 0) {
1887       break;
1888     }
1889     sprintf(perf_file, PERF_FILE"%06d", pids[i]);  // NOLINT
1890     sprintf(perf_dump, PERF_DUMP"%06d", pids[i]);  // NOLINT
1891     if ((rfd = fopen(perf_dump, "r")) == NULL) {  // LCOV_EXCL_BR_LINE 5: fopen error case
1892       // LCOV_EXCL_START 5: fopen error case
1893       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1894       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Failed to open-2 %s, errno=%d\n",
1895              perf_dump, errno);
1896       continue;
1897       // LCOV_EXCL_STOP 5: fopen error case
1898     }
1899     perf_lines = 0;
1900     while (fgets(buf, sizeof(buf), rfd) > 0) {
1901       if (perf_lines >= PERF_MAX_LINES) {
1902         break;
1903       }
1904       /* skip header */
1905       if (buf[0] == '#') {
1906         continue;
1907       }
1908       if (buf[0] == '\n' || buf[0] == '\r') {
1909         continue;
1910       }
1911       trim_end(buf);
1912       if (perf_lines == 0) {
1913
1914 //        FRAMEWORKUNIFIEDLOG(ZONE_WARN, __FUNCTION__, "[CpuHLPerf:%s(%d)]report by result of 'perf record -p %d'",
1915 //               pnames[i], pids[i], pids[i]);
1916         FRAMEWORKUNIFIEDLOG(ZONE_WARN, __FUNCTION__, "[CpuHLPerf:(%d)]report by result of 'perf record -p %d'",
1917                pids[i], pids[i]);
1918
1919       }
1920       FRAMEWORKUNIFIEDLOG(ZONE_WARN, __FUNCTION__, "[CpuHLPerf]%s\n", buf);
1921       perf_lines++;
1922     }
1923     fclose(rfd);
1924     // Check if no line is acquired
1925     if (perf_lines == 0) {
1926
1927 //      FRAMEWORKUNIFIEDLOG(ZONE_WARN, __FUNCTION__, "[CpuHLPerf:%s(%d)] NO_DATA_acquired",
1928 //             pnames[i], pids[i]);
1929       FRAMEWORKUNIFIEDLOG(ZONE_WARN, __FUNCTION__, "[CpuHLPerf:(%d)] NO_DATA_acquired",
1930              pids[i]);
1931
1932     }
1933     // Cleanup
1934     unlink(perf_dump);
1935     unlink(perf_file);
1936   }
1937   FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "-");
1938 }
1939
1940 /*********************************************************************************
1941  * exec_perf Main processing
1942  *********************************************************************************/
1943
1944 //static void exec_perf(char pnames[PERF_MAX_PROCS][PERF_PNAME_MAX]) {
1945 static void exec_perf(int32_t t_pid) {
1946
1947   pid_t c_pids[PERF_MAX_PROCS];   // max process to exec perf(forked child pids)
1948
1949   pid_t pids[PERF_MAX_PROCS];
1950   char perf_file[128];
1951   char perf_dump[128];
1952   char pidstr[64];
1953   struct stat statbuf;
1954   int status;
1955
1956   /* Check existance of perf exec file */
1957   if (stat(PERF_PATH, &statbuf) == -1 || !(statbuf.st_mode & S_IXUSR)) {
1958     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "%s is not available", PERF_PATH);
1959     return;
1960   }
1961
1962   FRAMEWORKUNIFIEDLOG (ZONE_INFO, __FUNCTION__, "[CpuHighLoad]Please check User backtrace of following processes in kernel.log");
1963 //  print_backtrace_pid(t_pid);
1964   for (int i = 0; i < PERF_MAX_PROCS; i++) {
1965     pids[i] = -1;
1966   }
1967
1968   pids[0] = t_pid;
1969
1970
1971   /* RECORD perf data */
1972
1973 //  exec_perf_Record_Perf_Data(c_pids, perf_file, pidstr, &status, pnames);
1974   exec_perf_Record_Perf_Data(c_pids, perf_file, pidstr, &status, pids);
1975
1976
1977   /* make perf file available to default user */
1978
1979 //  if (exec_perf_Make_Perf_File(c_pids, perf_file) != 0)
1980   if (exec_perf_Make_Perf_File(c_pids, perf_file, pids) != 0)
1981
1982     return;
1983
1984   /* REPORT perf data into dump file */
1985
1986 //  exec_perf_Report_Perf_Data(c_pids, perf_file, perf_dump, &status);
1987   exec_perf_Report_Perf_Data(c_pids, perf_file, perf_dump, &status, pids);
1988
1989
1990   /* FRAMEWORKUNIFIEDLOG perf data */
1991
1992 //  exec_perf_Resourcemanagerlog_Perf_Data(perf_file, perf_dump, pnames);
1993   exec_perf_Resourcemanagerlog_Perf_Data(perf_file, perf_dump, pids);
1994
1995 }
1996
1997 // Logging at CPU overload
1998 #define WAIT_RETRY 3           // 3sec
1999
2000
2001 #if 0
2002 static void logging_cpuload(void) {
2003   int32_t pipe_fd[2];  // 0:stdin,1:stdout
2004   pid_t c_pid;
2005   char buf[READLINE_MAX_SIZE];
2006   char buf2[READLINE_MAX_SIZE];
2007   char tmp[READLINE_MAX_SIZE];
2008   int32_t logLine = 0;
2009   char* ptr;
2010   int32_t ret;
2011   int32_t status;
2012   int32_t perfNum = 0;
2013   char pnames[PERF_MAX_PROCS][PERF_PNAME_MAX] = { };
2014   int save_0 = -1;
2015   int kill_flag = 1;
2016   int waitret;
2017
2018   FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "+");
2019
2020   // Create pipe
2021   ret = pipe(pipe_fd);
2022
2023   if (ret != 0) {  // LCOV_EXCL_BR_LINE 5: pipe error case
2024     // LCOV_EXCL_START 5: pipe error case
2025     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
2026     FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__,
2027            "ResMgr logging_cpuload() pipe Error");
2028     return;
2029     // LCOV_EXCL_STOP 5: pipe error case
2030   }
2031
2032   // Create child process
2033   c_pid = fork();
2034   if (c_pid < 0) {  // LCOV_EXCL_BR_LINE 5: fork error case
2035     // LCOV_EXCL_START 5: fork error case
2036     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
2037     FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__,
2038            "ResMgr logging_cpuload() fork Error");
2039     close(pipe_fd[0]);
2040     close(pipe_fd[1]);
2041
2042     return;
2043     // LCOV_EXCL_STOP 5: fork error case
2044   }
2045
2046   if (c_pid == 0) {
2047     /*******************************************************
2048      * Child-process
2049      *   The use of dup() and Close() between fork()-> exec() has been
2050      *   confirmed no probrem.
2051      *******************************************************/
2052     if (lower_sched_priority(CPULOAD_NICEVAL) == false) {
2053       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Failed to lower scheduler");
2054       exit(1);
2055     }
2056     close(pipe_fd[0]);     // Unneeded pipes (close stdin)
2057
2058     close(1);              // Close stdout
2059     dup2(pipe_fd[1], 1);   // Duplicate stdout to pipe_fd[1]
2060     close(pipe_fd[1]);
2061
2062     FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "execl top");
2063     execl("/usr/bin/top", "top", "-n", "1", "-b", NULL);
2064     // error
2065     FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "ResMgr logging_cpuload() execl Error");
2066     exit(1);
2067   } else {
2068     close(pipe_fd[1]);      // Unneeded pipes(Close stdout)
2069
2070     save_0 = dup(0);
2071     close(0);               // Close stdin
2072     dup2(pipe_fd[0], 0);    // Duplicate stdin to pipe_fd[0]
2073     close(pipe_fd[0]);
2074
2075     for (int i = 0; i < PERF_MAX_PROCS; i++) {
2076       pids[i] = -1;
2077     }
2078
2079     {
2080       fd_set fds;
2081       int32_t maxFd;
2082       int ret;
2083       struct timeval tmout = { TOP_TIMEOUT, 0 };
2084
2085       FD_ZERO(&fds);
2086       FD_SET(STDIN_FILENO, &fds);
2087       maxFd = STDIN_FILENO;
2088       ret = select(maxFd + 1, &fds, NULL, NULL, &tmout);
2089       if (ret < 0) {  // LCOV_EXCL_BR_LINE 5: select error case
2090         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
2091         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "[RESM]Handle Error errno:%d", errno);  // LCOV_EXCL_LINE 5: select error case
2092       } else if (FD_ISSET(STDIN_FILENO, &fds)) {
2093         kill_flag = 0;
2094       } else {
2095         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
2096                "[RESM]'top': No response during %d seconds", TOP_TIMEOUT);
2097       }
2098       if (kill_flag) {
2099         // Kill top after TOP_TIMEOUT sec
2100         // (Killed by child process to avoid making resm process super-user with setuid.)
2101         if (kill(c_pid, SIGKILL) == -1) {  // LCOV_EXCL_BR_LINE 5: kill error case
2102           // LCOV_EXCL_START 5: kill error case
2103           AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
2104           FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
2105                  "Failed to kill(SIGKILL), pid=%d, errno=%d", (int) c_pid,
2106                  errno);
2107           // LCOV_EXCL_STOP 5: kill error case
2108         }
2109       } else {
2110         while (fgets(buf, sizeof(buf), stdin) > 0) {
2111           // Save ProcessName and Process ID to exec perf
2112           if (logLine >= 2 && perfNum < PERF_MAX_PROCS) {
2113             buf2[0] = 0;
2114             strncat(buf2, buf, sizeof(buf2) - 1);
2115             buf2[sizeof(buf2) - 1] = 0;
2116             if (valid_perf_cmd(buf2)) {
2117               pids[perfNum] = atoi(buf2);
2118               trim_end(buf2);
2119               strncat(pnames[perfNum], rindex(buf2, ' ') + 1,
2120                       sizeof(pnames[0]) - 1);
2121               if (pids[perfNum] >= 0
2122                   && strnlen(pnames[perfNum], sizeof(pnames[perfNum]) - 1)) {
2123                 perfNum++;
2124               } else {
2125                 pids[perfNum] = -1;
2126               }
2127             }
2128           }
2129           if (logLine == 0) {
2130             if ((buf[0] != 'C') && (buf[0] != '%')) {
2131               continue;
2132             }
2133             ptr = strstr(buf, "sy");
2134             if (ptr == NULL) {
2135               continue;
2136             }
2137             while (isalpha(*ptr)) {
2138               ptr++;
2139             }
2140             *ptr = '\0';
2141             escape_percent(buf, tmp);
2142             FRAMEWORKUNIFIEDLOG(ZONE_WARN, __FUNCTION__, "[CpuHighLoad]%s", tmp);
2143             logLine++;
2144           } else if (logLine == 1) {
2145             ptr = strstr(buf, "PID");
2146             if (ptr == NULL) {
2147               continue;
2148             }
2149             trim_end(buf);
2150             escape_percent(buf, tmp);
2151             FRAMEWORKUNIFIEDLOG(ZONE_WARN, __FUNCTION__, "[CpuHighLoad]%s", tmp);
2152             logLine++;
2153           } else if (logLine < (CPU_HIGH_LOAD_P_LOG_NUM + 2)) {
2154             trim_end(buf);
2155             FRAMEWORKUNIFIEDLOG(ZONE_WARN, __FUNCTION__, "[CpuHighLoad]%s", buf);
2156             logLine++;
2157           }
2158         }
2159       }
2160     }
2161     FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "wait pid(%d) kill_flag(%d)", c_pid, kill_flag);
2162     if (kill_flag) {
2163       const struct timespec delay = {1, 0};
2164       int i;
2165       for (i = 0; i < WAIT_RETRY; i++) {
2166         nanosleep(&delay, NULL);
2167         if ((waitret = waitpid(c_pid, &status, WNOHANG)) == -1) {
2168           FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Failed to waitpid for top %d, errno=%d", c_pid, errno);
2169           break;
2170         } else if (waitret == c_pid) {
2171           FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "waitpid OK");
2172           break;
2173         }
2174       }
2175       if (i >= WAIT_RETRY) {
2176         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "top Failed to exit, pid=%d", c_pid);
2177       }
2178     } else {
2179       if ((waitret = waitpid(static_cast<int>(c_pid), &status, 0)) < 0) {
2180         FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "waitpid(%d) Error errno(%d)", c_pid, errno);
2181       }
2182     }
2183     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "waitpid(%d) returned (%d) errno(%d) status=%d",
2184            c_pid, waitret, errno, WEXITSTATUS(*status));
2185     if (save_0 >= 0) {
2186       dup2(save_0, 0);    // Reset the stdin to 0
2187       close(save_0);
2188     }
2189     if (!kill_flag) {
2190       exec_perf(pnames);
2191     }
2192   }
2193   FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "-");
2194
2195   return;
2196 }
2197 #endif
2198
2199
2200 // Tail adjustment
2201 static void trim_end(char* buf) {
2202   int32_t len;
2203
2204   len = strlen(buf);
2205   while (len > 0) {
2206     if (isspace(buf[len - 1])) {
2207       buf[len - 1] = '\0';
2208       len--;
2209       continue;
2210     }
2211     break;
2212   }
2213
2214   return;
2215 }
2216
2217
2218 #if 0
2219 // Escape character "%"
2220 static void escape_percent(char* in, char* out) {
2221   char* head;
2222   char* tail;
2223
2224   head = in;
2225
2226   out[0] = '\0';
2227
2228   while (1) {
2229     tail = strchr(head, '%');
2230     if (tail == NULL) {
2231       strcat(out, head);  // NOLINT
2232       break;
2233     }
2234     *tail = '\0';
2235
2236     strcat(out, head);  // NOLINT
2237     strcat(out, "%%");  // NOLINT
2238
2239     tail++;
2240     head = tail;
2241   }
2242
2243   return;
2244 }
2245 #endif
2246
2247
2248 /*********************************************************************************
2249  * Output debug information display
2250  *********************************************************************************/
2251 void outputResouceInfo(void) {
2252   static bool madedir = false;
2253   struct stat sbuf;
2254   FILE *wfp;
2255
2256   // Create directory
2257   if (!madedir) {
2258     if (stat(DEBUG_INFO_DIRPATH, &sbuf) != 0) {  // LCOV_EXCL_BR_LINE 5: stat's error case
2259       if (mkdir(DEBUG_INFO_DIRPATH, 0777) != 0) {  // LCOV_EXCL_BR_LINE 5: mkdir's error case
2260         // LCOV_EXCL_START 5: mkdir's error case
2261         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
2262         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Failed to mkdir %s, errno=%d",
2263                DEBUG_INFO_DIRPATH,
2264                errno);
2265         return;
2266         // LCOV_EXCL_STOP
2267       }
2268     }
2269     madedir = true;
2270   }
2271   // Open files to work
2272   if ((wfp = fopen(DEBUG_INFO_TMPPATH, "w")) == NULL) {  // LCOV_EXCL_BR_LINE 5: fopen error case
2273     // LCOV_EXCL_START 5: fopen error case
2274     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
2275     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Failed to open %s, errno=%d",
2276            DEBUG_INFO_TMPPATH,
2277            errno);
2278     return;
2279     // LCOV_EXCL_STOP 5: fopen error case
2280   }
2281   // Output memory information work
2282   if (write_meminfo_work(wfp) != 0) {  // LCOV_EXCL_BR_LINE 6: write_meminfo_work will not be error
2283     // LCOV_EXCL_START 6: write_meminfo_work will not be error
2284     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
2285     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
2286            "Failed to edit and output in write_meminfo_work()");
2287     fclose(wfp);
2288     return;
2289     // LCOV_EXCL_STOP 6: write_meminfo_work will not be error
2290   }
2291   // Get CMA MEMORY information and output working info
2292   if (write_cmainfo_work(wfp) != 0) {  // LCOV_EXCL_BR_LINE 6: write_cmainfo_work will not be error
2293     // LCOV_EXCL_START 6: write_cmainfo_work will not be error
2294     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
2295     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
2296            "Failed to edit and output in write_cmainfo_work()");
2297     fclose(wfp);
2298     return;
2299     // LCOV_EXCL_STOP 6: write_cmainfo_work will not be error
2300   }
2301   // Get top information and output work info
2302   if (write_cpuinfo_work(wfp) != 0) {  // LCOV_EXCL_BR_LINE 6: write_cpuinfo_work will not be error
2303     // LCOV_EXCL_START 6: write_cpuinfo_work will not be error
2304     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
2305     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
2306            "Failed to edit and output in write_cpuinfo_work()");
2307     fclose(wfp);
2308     return;
2309     // LCOV_EXCL_STOP 6: write_cpuinfo_work will not be error
2310   }
2311   fclose(wfp);
2312   // Create output file
2313   if (rename(DEBUG_INFO_TMPPATH, DEBUG_INFO_FPATH) != 0) {  // LCOV_EXCL_BR_LINE 5:rename error case
2314     // LCOV_EXCL_START 5:rename error case
2315     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
2316     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Failed to make output file %s, errno=%d",
2317            DEBUG_INFO_FPATH,
2318            errno);
2319     // LCOV_EXCL_STOP 5:rename error case
2320   }
2321   // Write information and output FRAMEWORKUNIFIEDLOG
2322   if (write_resourcemanagerloginfo_work() != 0) {  // LCOV_EXCL_BR_LINE 6: write_resourcemanagerloginfo_work will not be error
2323     // LCOV_EXCL_START 6: write_resourcemanagerloginfo_work will not be error
2324     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
2325     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
2326            "Failed to output in write_resourcemanagerloginfo_work()");
2327     // LCOV_EXCL_STOP 6: write_resourcemanagerloginfo_work will not be error
2328   }
2329 }
2330
2331 // Output memory information work
2332 static int write_meminfo_work(FILE *wfp) {
2333   float total;
2334   float avail;
2335   float used;
2336   float min_remain;
2337   uint32_t used_rate;
2338   uint32_t used_letters;
2339   // Output meminfo: Getting info from the proc/meminfo is performed at 5-second intervals in watchMem, so it is diverted.
2340   avail = static_cast<float>((mainFree_kib + inactFile_kib));
2341   total = static_cast<float>(memTotal_kib);
2342   used = total - avail;
2343   min_remain = static_cast<float>(minRestMem);
2344   // "*MEMORY   @@@@@@ Warning!! @@@@@"
2345   fprintf(wfp, "*MEMORY");
2346   if (avail * 10 < total) {  // (Less than 1/10)
2347     fprintf(wfp, "   @@@@@@ Warning!! @@@@@\n");
2348   } else {
2349     fprintf(wfp, "   \n");
2350   }
2351   // "used/avail/total/used max   xxx.xMB / xxx.xMB / xxx.xMB(xx.x%) / xxx.xMB
2352   used /= 1024;
2353   avail /= 1024;
2354   total /= 1024;
2355   min_remain /= 1024;
2356   if (total == 0) {
2357     used_rate = 0;
2358   } else {
2359     used_rate = (uint32_t) (used * 1000 / total);
2360     if (used_rate >= 1000) {
2361       used_rate = 999;
2362     }
2363   }
2364   fprintf(
2365     wfp,
2366     " used/avail/total/min remain   %5.1fMB / %5.1fMB / %5.1fMB(%2d.%d%%) / %5.1fMB\n",
2367     used, avail, total, used_rate / 10, used_rate % 10, min_remain);
2368   if (total == 0) {
2369     used_letters = 0;
2370   } else {
2371     used_letters = (uint32_t) (DEBUG_INFO_MEM_LETTERS * used / total);
2372     if (used_letters > DEBUG_INFO_MEM_LETTERS) {
2373       used_letters = DEBUG_INFO_MEM_LETTERS;
2374     }
2375   }
2376   // "------------------*******"
2377   int i;
2378   for (i = 0; i < static_cast<int>(used_letters); i++) {
2379     fprintf(wfp, "-");
2380   }
2381   for (; i < DEBUG_INFO_MEM_LETTERS; i++) {
2382     fprintf(wfp, "*");
2383   }
2384   fprintf(wfp, "\n\n");
2385
2386   return 0;
2387 }
2388 // Get top information and Output work
2389 static int write_cpuinfo_work(FILE *wfp) {
2390   int32_t pipe_fd[2];  // 0:stdin,1:stdout
2391   pid_t c_pid;
2392   char buf[READLINE_MAX_SIZE];
2393   int32_t logLine = 0;
2394   char* ptr;
2395   int32_t ret;
2396   int32_t status;
2397   int save_0 = -1;
2398   int32_t cpu_rate;
2399   char fields[12][128];
2400   int kill_flag = 1;
2401   int waitret;
2402
2403   // Output CPU load
2404   cpu_rate = g_cpuloadRate1000 < 0 ? 0 : g_cpuloadRate1000;
2405   fprintf(wfp, "*CPU      %2d.%d%%\n", cpu_rate / 10, cpu_rate % 10);
2406
2407   // Create pipe
2408   ret = pipe(pipe_fd);
2409
2410   if (ret != 0) {  // LCOV_EXCL_BR_LINE 5: pipe error case
2411     // LCOV_EXCL_START 5: pipe error case
2412     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
2413     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "pipe Error");
2414     return -1;
2415     // LCOV_EXCL_STOP 5: pipe error case
2416   }
2417
2418   // Create child process
2419   c_pid = fork();
2420   if (c_pid < 0) {  // LCOV_EXCL_BR_LINE 5: fork error case
2421     // LCOV_EXCL_START 5: fork error case
2422     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
2423     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "fork Error");
2424     close(pipe_fd[0]);
2425     close(pipe_fd[1]);
2426
2427     return -1;
2428     // LCOV_EXCL_STOP 5: fork error case
2429   }
2430
2431   if (c_pid == 0) {
2432     /*******************************************************
2433      * Child process
2434      *******************************************************/
2435     if (lower_sched_priority(CPULOAD_NICEVAL) == false) {  // LCOV_EXCL_BR_LINE 200: lower_sched_priority can't be false
2436       // LCOV_EXCL_START 200: lower_sched_priority can't be false
2437       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
2438       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Failed to lower scheduler");
2439       exit(1);
2440       // LCOV_EXCL_STOP
2441     }
2442     close(pipe_fd[0]);     // Unneeded pipes (close stdin)
2443
2444     close(1);              // Close stdout
2445     dup2(pipe_fd[1], 1);   // Duplicate stdout to pipe_fd[1]
2446     close(pipe_fd[1]);
2447
2448     execl("/usr/bin/top", "top", "-n", "1", "-b", NULL);
2449     // error
2450     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "execl top Error");
2451     exit(1);
2452   } else {
2453     close(pipe_fd[1]);      // Unneeded pipes(Close stdout)
2454
2455     save_0 = dup(0);
2456     close(0);               // Close stdin
2457     dup2(pipe_fd[0], 0);    // Duplicate stdin to pipe_fd[0]
2458     close(pipe_fd[0]);
2459
2460     {
2461       fd_set fds;
2462       int32_t maxFd;
2463       int ret;
2464       struct timeval tmout = { TOP_TIMEOUT, 0 };
2465
2466       FD_ZERO(&fds);
2467       FD_SET(STDIN_FILENO, &fds);
2468       maxFd = STDIN_FILENO;
2469       ret = select(maxFd + 1, &fds, NULL, NULL, &tmout);
2470       if (ret < 0) {  // LCOV_EXCL_BR_LINE 5: select error case
2471         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
2472         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "[RESM]Handle Error errno:%d", errno);  // LCOV_EXCL_LINE 5: select error case
2473       } else if (FD_ISSET(STDIN_FILENO, &fds)) {  // LCOV_EXCL_BR_LINE 5: FD_ISSET's error case
2474         kill_flag = 0;
2475       } else {
2476         // LCOV_EXCL_START 5: FD_ISSET's error case
2477         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
2478         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
2479                "[RESM]'top': No response during %d seconds", TOP_TIMEOUT);
2480         // LCOV_EXCL_STOP
2481       }
2482       if (kill_flag) {  // LCOV_EXCL_BR_LINE 200: kill_flag must be 0
2483         // LCOV_EXCL_START 200: kill_flag must be 0
2484         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
2485         // Kill top after TOP_TIMEOUT sec
2486         // (Killed by child process to avoid making resm process super-user with setuid.)
2487         if (kill(c_pid, SIGKILL) == -1) {
2488           FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
2489                  "Failed to kill(SIGKILL), pid=%d, errno=%d", (int) c_pid,
2490                  errno);
2491         }
2492         // LCOV_EXCL_STOP
2493       } else {
2494         while (fgets(buf, sizeof(buf), stdin) > 0) {
2495           if (logLine == 0) {
2496             if (buf[0] != 'C') {
2497               continue;
2498             }
2499             if (strstr(buf, "Cpu(s)") == NULL || strstr(buf, "sy") == NULL) {
2500               continue;
2501             }
2502             logLine++;
2503           } else if (logLine == 1) {
2504             ptr = strstr(buf, "PID");
2505             if (ptr == NULL) {
2506               continue;
2507             }
2508             logLine++;
2509           } else if (logLine < (DEBUG_INFO_CPU_TOP_LINES + 2)) {
2510             ret = sscanf(buf, "%128s %128s %128s %128s %128s %128s %128s %128s %128s %128s %128s %128s", fields[0],
2511                          fields[1], fields[2], fields[3], fields[4], fields[5],
2512                          fields[6], fields[7], fields[8], fields[9], fields[10],
2513                          fields[11]);
2514             fprintf(wfp, "%4s%%  %s\n", fields[8], fields[11]);
2515             logLine++;
2516           }
2517         }
2518         fprintf(wfp, "\n\n");
2519       }
2520     }
2521     ret = 0;
2522     if (kill_flag) {  // LCOV_EXCL_BR_LINE 200: kill_flag must be 0
2523       // LCOV_EXCL_START 200: kill_flag must be 0
2524       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
2525       const struct timespec delay = {1, 0};
2526       int i;
2527       for (i = 0; i < WAIT_RETRY; i++) {
2528         nanosleep(&delay, NULL);
2529         if ((waitret = waitpid(c_pid, &status, WNOHANG)) == -1) {
2530           ret = -1;
2531           FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Failed to waitpid for top %d, errno=%d", c_pid, errno);
2532           break;
2533         } else if (waitret == c_pid) {
2534           FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "waitpid OK");
2535           break;
2536         }
2537       }
2538       if (i >= WAIT_RETRY) {
2539         ret = -1;
2540         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "top Failed to exit, pid=%d", c_pid);
2541       }
2542       // LCOV_EXCL_STOP
2543     } else {
2544       if ((waitret = waitpid(static_cast<int>(c_pid), &status, 0)) < 0) {  // LCOV_EXCL_BR_LINE 5: waitpid's error case
2545         // LCOV_EXCL_START 5: waitpid's error case
2546         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
2547         ret = -1;
2548         FRAMEWORKUNIFIEDLOG(ZONE_RESM_DEBUG, __FUNCTION__, "waitpid(%d) Error errno(%d)", c_pid, errno);
2549         // LCOV_EXCL_STOP
2550       }
2551     }
2552     if (ret < 0) {  // LCOV_EXCL_BR_LINE 200: ret must be 0
2553       // LCOV_EXCL_START 200: ret must be 0
2554       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
2555       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "wait Error");
2556       if (save_0 >= 0) {
2557         close(save_0);
2558       }
2559       return -1;
2560       // LCOV_EXCL_STOP
2561     }
2562     if (save_0 >= 0) {
2563       dup2(save_0, 0);    // Reset the stdin to 0
2564       close(save_0);
2565     }
2566   }
2567
2568   return 0;
2569 }
2570 // Get CMA information and Output work
2571 static int write_cmainfo_work(FILE *wfp) {
2572   float total;
2573   float avail;
2574   float used;
2575   float min_remain;
2576   uint32_t used_rate;
2577   uint32_t used_letters;
2578
2579   avail = static_cast<float>(cmaFree_kib);
2580   total = static_cast<float>(cmaTotal_kib);
2581   used = total - avail;
2582   min_remain = static_cast<float>(minRestCma);
2583   // "*CMA MEMORY   @@@@@@ Warning!! @@@@@"
2584   fprintf(wfp, "*CMA MEMORY");
2585   if (used * 5 > total * 4) {  // (4/5 Or more)
2586     fprintf(wfp, "   @@@@@@ Warning!! @@@@@\n");
2587   } else {
2588     fprintf(wfp, "   \n");
2589   }
2590   // "used/avail/total   xxx.xMB / xxx.xMB / xxx.xMB(xx.x%)
2591   used /= 1024;
2592   avail /= 1024;
2593   total /= 1024;
2594   min_remain /= 1024;
2595   if (total != 0) {
2596     used_rate = (uint32_t) (used * 1000 / total);
2597   } else {
2598     used_rate = 0;
2599   }
2600   if (used_rate >= 1000) {
2601     used_rate = 999;
2602   }
2603   fprintf(
2604     wfp,
2605     " used/avail/total/min remain   %5.1fMB / %5.1fMB / %5.1fMB(%2d.%d%%) / %5.1fMB\n",
2606     used, avail, total, used_rate / 10, used_rate % 10, min_remain);
2607   if (total == 0) {
2608     used_letters = 0;
2609   } else {
2610     used_letters = (uint32_t) (DEBUG_INFO_CMA_LETTERS * used / total);
2611     if (used_letters > DEBUG_INFO_CMA_LETTERS) {
2612       used_letters = DEBUG_INFO_CMA_LETTERS;
2613     }
2614   }
2615   // "------------------*******"
2616   int i;
2617   for (i = 0; i < static_cast<int>(used_letters); i++) {
2618     fprintf(wfp, "-");
2619   }
2620   for (; i < DEBUG_INFO_CMA_LETTERS; i++) {
2621     fprintf(wfp, "*");
2622   }
2623   fprintf(wfp, "\n\n");
2624
2625   return 0;
2626 }
2627 // Write information and Output FRAMEWORKUNIFIEDLOG
2628 static int write_resourcemanagerloginfo_work(void) {
2629   FILE *wfp;
2630   char l_read[READLINE_MAX_SIZE];
2631   int ret;
2632
2633   wfp = fopen(DEBUG_INFO_FPATH, "r");
2634   if (wfp == NULL) {  // LCOV_EXCL_BR_LINE 5: fopen error case
2635     // LCOV_EXCL_START 5: fopen case error
2636     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
2637     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Failed to open %s, errno=%d",
2638            DEBUG_INFO_FPATH,
2639            errno);
2640     return -1;
2641     // LCOV_EXCL_STOP 5: fopen case error
2642   }
2643   while (1) {
2644     if (fgets(l_read, READLINE_MAX_SIZE, wfp) == NULL) {
2645       ret = feof(wfp);
2646       if (ret == 0) {  // LCOV_EXCL_BR_LINE 5: feof case error
2647         // LCOV_EXCL_START 5: feof case error
2648         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
2649         FRAMEWORKUNIFIEDLOG(ZONE_PERFORMANCE, __FUNCTION__, "Failed to fgets %s",
2650                DEBUG_INFO_FPATH);
2651         // LCOV_EXCL_STOP 5: feof case error
2652       }
2653       break;
2654     } else {
2655       char *line;
2656       line = strchr(l_read, '\n');
2657       if (line != NULL) {
2658         *line = '\0';
2659       }
2660       if (l_read[0] != '\0') {
2661         FRAMEWORKUNIFIEDLOG(ZONE_PERFORMANCE, __FUNCTION__, "%s", l_read);
2662       }
2663     }
2664   }
2665   fclose(wfp);
2666   return 0;
2667 }