Remove unused directories and files in video_in_hal
[staging/basesystem.git] / systemservice / logger_service / server / lib / ss_logger_store_logs.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 ///////////////////////////////////////////////////////////////////////////////
18 /// \ingroup  tag_SystemServices_Logger
19 /// \brief    This file supports the logger service interface for SystemManager.
20 ///
21 ///////////////////////////////////////////////////////////////////////////////
22 #include "system_service/ss_logger_store_logs.h"
23 #include <stdio.h>
24 #include <string.h>
25 #include <fcntl.h>
26 #include <dirent.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include <errno.h>
30 #include <libtar_listhash.h>
31 #include <libtar.h>
32 #include <zlib.h>
33 #include <sys/klog.h>
34
35 #include <stdlib.h>
36 #include <native_service/frameworkunified_application.h>
37 #include <native_service/frameworkunified_types.h>
38 #include <native_service/frameworkunified_framework_types.h>
39 #include <native_service/frameworkunified_framework_if.h>
40 #include <system_service/ss_system_types.h>
41 #include <native_service/ns_ringbuffer.h>
42 #include <native_service/ns_logger_if.h>
43 #include <native_service/ns_config_parser_if.h>
44 #include <native_service/cl_lockid.h>
45 #include <stub/Clock_API.h>
46 #include <vector>
47 #include <sstream>
48 #include <iomanip>
49 #include <string>
50 #include <algorithm>
51 #include "ss_logger_store_logs_loggerservicelog.h"
52 #include "ss_logger_cfg.h"
53
54 #define LOGGERSERVICELOG_CONFIG_PATH       "/usr/agl/conf/BS/ss/logger_service/rodata/ss_logger.cfg"
55 #define LOGGER_TMP_FN            "__LOGGER.tmp"
56 #define LOGGERSERVICELOG_TMP_OUTPUT_PATH   "/tmp"
57 #define PSTORE_DIR_PATH          "/dev/pstore"
58 #define KERNEL_BOOT_LOG_FN       "kernelboot.log"
59 #define KERNEL_LOG_FN            "kernel.log"
60 #define COMMUNICATION_DIR_NAME   "communication"
61 #define ACCOFFON_DIR_NAME        "accoffon"
62
63 #define PATHNAME_SEPARATOR       '/'
64 #define PATHNAME_SEPARATOR_STR   "/"
65 #define SS_STORE_FILENAME_SYSILG_TERM "_SYS_ILG_RESET.tar.gz"
66 #define SS_STORE_FILENAME__CWORD52__TERM "__CWORD52_.log"
67 #define LOGARCHIVE_FILENAME_STORE_ARCHIVE "/tmp/ss_logger_ilgfilenum"
68 #define TMPFILE_MODE                     0640
69 #define SSLOGGER_PATHNAME                (255 + 1)
70 #define FILENUMBER_UPPER_LIMIT_OVER      100000u
71 #define FILENUMBER_LOWER_LIMIT           1u
72 #define FILENUMBER_DIGIT_NUM             5
73 #define INVALID_FILENUMBER               (FILENUMBER_UPPER_LIMIT_OVER)
74
75
76 /* Read all messages remaining in the ring buffer. (allowed for non-root) */
77 #define SYSLOG_ACTION_READ_ALL       3
78 /* Return size of the log buffer */
79 #define SYSLOG_ACTION_SIZE_BUFFER   10
80
81 #define ENABLE_DEBUG_LOG 0
82 #if ENABLE_DEBUG_LOG
83 #define DEB_LOGGERSERVICELOG(zone,funcname,print_fmt, ...) if(zone!=ZONE_FUNC) \
84 fprintf(stderr,"%d/%s/%d:="print_fmt"\n", zone, funcname, __LINE__,##__VA_ARGS__)
85 #else
86 #define DEB_LOGGERSERVICELOG(zone,funcname,print_fmt, ...)
87 #endif
88
89 typedef struct {
90   std::string output_path;
91   SI_32 output_max;
92   SI_32 output_errmax;
93   SI_32 external_log_num;
94   SI_32 external_log_max;
95 } CfgInfo;
96
97 typedef struct {
98   std::string file_path;
99   std::string dest_name;
100   BOOL tmp_file_delete;
101 } LogInfo;
102
103 typedef struct {
104   std::string path;
105   int index;
106 } LoggerservicelogInfo;
107
108
109 static const char* sys_illegal_log[] = {
110                                                "frameworkunified_sys.log",
111                                        };
112
113
114 typedef enum {
115   SS_STORELOGS_KERNEL_LOG = 0,
116   SS_STORELOGS_KERNEL_BOOT_LOG
117 } SS_STORELOGS_KERNEL_LOG_TYPE;
118
119 typedef void (*GetLogFileFunc)(SS_STORELOGS_OPE_TYPE type,
120                                std::vector<LogInfo>& list);  // NOLINT (runtime/references)
121
122 static const UI_8 MAX_DIRECTORY_DEPTH = 4;
123 static const UI_32 TARMODE = 0644;
124
125 static EFrameworkunifiedStatus addToArchive(TAR* f_pTarInfo, std::string f_filePathAndName,
126                                std::string f_destinationName, UI_8 f_depth =
127                                  MAX_DIRECTORY_DEPTH);
128 static EFrameworkunifiedStatus addDirectoryToArchive(TAR* f_pTarInfo, std::string f_path,
129                                         std::string f_destinationName,
130                                         UI_8 f_depth = MAX_DIRECTORY_DEPTH);
131 static SI_32 gzOpenArchive(PCHAR f_pcPathname, SI_32 f_siOflags,
132                            SI_32 f_siMode);
133 static SI_32 gzCloseArchive();
134 static ssize_t gzWriteArchive(int fd, const void* buf, size_t count);
135 static ssize_t gzReadArchive(int fd, void* buf, size_t count);
136 static EFrameworkunifiedStatus addFileToArchive(TAR* f_pTarInfo, std::string f_filename,
137                                    std::string f_destinationName);
138 static EFrameworkunifiedStatus addAllFileToArchive (TAR* f_pTarInfo, std::string collectDir);
139 static EFrameworkunifiedStatus copyFile(std::string f_source, std::string f_destination);
140 static EFrameworkunifiedStatus copyDirectory (std::string f_source, std::string f_destination);
141 static EFrameworkunifiedStatus copyUntyped (std::string f_source, std::string f_destination);
142 static EFrameworkunifiedStatus copyFileToAccOffOnDir(std::vector<LogInfo>& list, SS_STORELOGS_OPE_TYPE type);
143 static void getLoggerservicelogFile(SS_STORELOGS_OPE_TYPE type,
144                           std::vector<LogInfo>& list,  // NOLINT (runtime/references)
145                           std::vector<LoggerservicelogInfo> &loggerservicelogList);  // NOLINT (runtime/references)
146 static void getKernellogFile(SS_STORELOGS_OPE_TYPE type,
147                              std::vector<LogInfo>& list);  // NOLINT (runtime/references)
148 static void getLastKernelLog(std::vector<LogInfo>& list);  // NOLINT (runtime/references)
149 static void getKernelLog(std::vector<LogInfo>& list);  // NOLINT (runtime/references)
150 static void getKernelBootLog(SS_STORELOGS_OPE_TYPE type,
151                              std::vector<LogInfo>& list);  // NOLINT (runtime/references)
152 static void getCommunicationlogFile(SS_STORELOGS_OPE_TYPE type,
153                                     std::vector<LogInfo>& list);  // NOLINT (runtime/references)
154 static void getExternallogFile(SS_STORELOGS_OPE_TYPE type,
155                              std::vector<LogInfo>& list);  // NOLINT (runtime/references)
156
157 //static std::string getFileName(std::string &path, uint32_t f_time,  // NOLINT (runtime/references)
158 //                               SS_STORELOGS_OPE_TYPE type);
159 static std::string getFileName(std::string &path, uint32_t f_time,  // NOLINT (runtime/references)
160                                SS_STORELOGS_OPE_TYPE type, UI_32 l_counter);
161
162 static void getEmmcCounter(std::string &path, UI_32& f_counter);  // NOLINT (runtime/references)
163 static void getConfigInfo(CfgInfo& f_cfginfo);  // NOLINT (runtime/references)
164 static EFrameworkunifiedStatus deleteOldEmmcLog(CfgInfo& f_cfginfo,  // NOLINT (runtime/references)
165                                    std::string& f_archive_destination,  // NOLINT (runtime/references)
166                                    SS_STORELOGS_OPE_TYPE type);
167 static EFrameworkunifiedStatus storeLogs(SS_STORELOGS_OPE_TYPE type);
168 static EFrameworkunifiedStatus deleteOldLog(std::string log_path,
169                                std::vector<std::string>& l_vector,  // NOLINT (runtime/references)
170                                std::string& f_archive_destination,  // NOLINT (runtime/references)
171                                UI_32 max_num);
172 static size_t deleteRequestLogs(std::string f_emmcpath, ELOGGERSERVICELOGTYPE f_reqtype,
173                                 size_t f_reqsize, ELOGGERSERVICELOGTYPE f_deltype);
174 static EFrameworkunifiedStatus forceDeleteOldLog(std::string f_archive_destination,
175                                     size_t f_req_size);
176 static ELOGGERSERVICELOGTYPE QueryLoggerservicelogType(std::string f_logname);
177 static void SyncDir(std::string f_dir_path);
178 static BOOL RemoveSubDirectory(std::string &f_cPath);  // NOLINT (runtime/references)
179 static void CreateSaveFinFlag(SS_STORELOGS_OPE_TYPE type);
180 static void ClearLoggerservicelogBuffer(std::vector<LoggerservicelogInfo> &loggerservicelogList);  // NOLINT (runtime/references)
181 static void copyLoggerservicelogFile(std::string distPath);
182 static void deleteTmpAccOffOn(std::string accOffOnDir);
183 static void deleteAccOffOnDir(std::string deletePath);
184 static void deleteAccOffOnUntyped(std::string deletePath);
185
186 static EFrameworkunifiedStatus getFileNumber(const std::string &filename,UI_32 &number);
187 static bool compareFileNumber(UI_32 filename1_number,const std::string &filename2);
188 static EFrameworkunifiedStatus removeFiles(const std::string &log_path, std::vector<std::string> &l_vector,
189                               size_t begin_pos, size_t end_pos);
190 static EFrameworkunifiedStatus removeSameNumFiles(std::vector<std::string>::iterator &itr, const std::string &log_path,
191                                      std::vector<std::string> &l_vector);
192 static EFrameworkunifiedStatus deleteOldLogAbnrm(const std::string& log_path, std::vector<std::string>& l_vector,
193                                     const std::string& f_archive_destination, SI_32 max_num, UI_32 abnrm_total);
194 static EFrameworkunifiedStatus storeTempArchive(const std::string &real_name);
195 static EFrameworkunifiedStatus getFileNumberFromTempArchive(UI_32 &filenumber);
196
197
198 static std::string m_pathAndName;  // NOLINT (runtime/string)
199 static std::string m_tmpName;  // NOLINT (runtime/string)
200
201 const GetLogFileFunc GetLogFuncTbl[] = { getKernellogFile,
202                                          getCommunicationlogFile,
203                                          getExternallogFile
204                                        };
205 // GZF save variables
206 static gzFile g_gztype;
207
208 // ->Bus-Error avoidance
209 static tartype_t l_gztype;
210
211 static EFrameworkunifiedStatus openArchive(TAR** f_pTarInfo, std::string f_pathAndName) {
212   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "+");
213   EFrameworkunifiedStatus l_eFrameworkunifiedStatus = eFrameworkunifiedStatusOK;
214
215 // ->Bus-Error avoidance (because of local variables, content becomes indeterminate when functions exit)
216 //  tartype_t l_gztype;
217
218   *f_pTarInfo = NULL;
219   g_gztype = NULL;
220   l_gztype.openfunc = (openfunc_t) &gzOpenArchive;
221   l_gztype.closefunc = (closefunc_t) &gzCloseArchive;
222   l_gztype.readfunc = (readfunc_t) &gzReadArchive;
223   l_gztype.writefunc = (writefunc_t) &gzWriteArchive;
224
225   m_pathAndName = f_pathAndName;
226
227   /* check if directory exists */
228   size_t l_found = f_pathAndName.find_last_of('/');
229   std::string l_path = f_pathAndName.substr(0, l_found);
230
231   if (0 != access(l_path.c_str(), F_OK)) {
232     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Directory does not exist. Creating...");
233     return eFrameworkunifiedStatusFail;
234   }
235
236   /* create archive in tmp */
237   m_tmpName = "/tmp/log.tar.gz";
238
239   int l_tarRetVal = tar_open(f_pTarInfo, const_cast<char*>(m_tmpName.c_str()), &l_gztype,
240                               O_WRONLY | O_CREAT, TARMODE, TAR_GNU);
241
242   if ((l_tarRetVal != 0) || (*f_pTarInfo == NULL) || g_gztype == NULL) {  // LCOV_EXCL_BR_LINE 6: tar_open must return ok  // NOLINT[whitespace/line_length]
243     // LCOV_EXCL_START 6: tar_open must return ok
244     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
245     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Could not open TAR-Archive!");
246     l_eFrameworkunifiedStatus = eFrameworkunifiedStatusAccessError;
247     // LCOV_EXCL_STOP
248   }
249
250   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
251   return (l_eFrameworkunifiedStatus);
252 }
253
254 static EFrameworkunifiedStatus addToArchive(TAR* f_pTarInfo, std::string f_filePathAndName,
255                                std::string f_destinationName, UI_8 f_depth) {
256   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "+");
257   EFrameworkunifiedStatus l_eFrameworkunifiedStatus = eFrameworkunifiedStatusFileLoadError;
258   struct stat l_stat;
259   int l_statRetVal;
260
261   if (0 != access(f_filePathAndName.c_str(), F_OK)) {
262     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
263            " Error. The specified file path and name does not exist: %s",
264            f_filePathAndName.c_str());
265   } else if (0 != (l_statRetVal = stat(f_filePathAndName.c_str(), &l_stat))) {  // LCOV_EXCL_BR_LINE 5: stat's error case  // NOLINT[whitespace/line_length]
266     // LCOV_EXCL_START 5: stat's error case
267     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
268     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
269            " Error. stat() for file or directory returned error: %s -> %d",
270            f_filePathAndName.c_str(), l_statRetVal);
271     // LCOV_EXCL_STOP
272   } else if (0 != S_ISDIR(l_stat.st_mode)) {
273     if (0 < f_depth) {  // LCOV_EXCL_BR_LINE 6: f_depth must be greater than 0
274       l_eFrameworkunifiedStatus = addDirectoryToArchive(f_pTarInfo, f_filePathAndName,
275                                            f_destinationName, f_depth);
276     } else {
277       // LCOV_EXCL_START 6: f_depth must be greater than 0
278       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
279       FRAMEWORKUNIFIEDLOG(ZONE_WARN, __FUNCTION__,
280              "Maximum recursive depth reached! File %s not added to archive.",
281              f_filePathAndName.c_str());
282       // LCOV_EXCL_STOP
283     }
284   } else if (0 != S_ISREG(l_stat.st_mode)) {
285     char path[PATH_MAX];
286     if (realpath(f_filePathAndName.c_str(), path) != NULL) {
287       f_filePathAndName = path;
288       l_eFrameworkunifiedStatus = addFileToArchive(f_pTarInfo, f_filePathAndName,
289                                       f_destinationName);
290     } else {
291       FRAMEWORKUNIFIEDLOG(ZONE_WARN, __FUNCTION__,
292              "Archive not opened or could not access file: \"%s\"",
293              f_filePathAndName.c_str());
294     }
295   } else {
296     FRAMEWORKUNIFIEDLOG(
297       ZONE_ERR,
298       __FUNCTION__,
299       " Error. specified file may be a symbolic link or other non 'regular' type. File: %s, mode: 0x%04X.",
300       f_filePathAndName.c_str(), l_stat.st_mode);
301   }
302
303   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
304   return (l_eFrameworkunifiedStatus);
305 }
306
307
308 static EFrameworkunifiedStatus getFileNumberFromTempArchive(UI_32 &filenumber)
309 {
310   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "+");
311   char      buf[FILENUMBER_DIGIT_NUM + 1];
312   int       fd;
313   int       result;
314   EFrameworkunifiedStatus    l_eFrameworkunifiedStatus = eFrameworkunifiedStatusOK;
315
316   fd = open(LOGARCHIVE_FILENAME_STORE_ARCHIVE, O_RDONLY);
317   if (fd == -1) {
318     FRAMEWORKUNIFIEDLOG(ZONE_ERR,__FUNCTION__," Error. open(). path = %s ,errno = %d", LOGARCHIVE_FILENAME_STORE_ARCHIVE, errno);
319     return eFrameworkunifiedStatusAccessError;
320   }
321
322   result = read(fd, buf, FILENUMBER_DIGIT_NUM);
323   if (result != FILENUMBER_DIGIT_NUM) {
324     FRAMEWORKUNIFIEDLOG(ZONE_ERR,__FUNCTION__," Error. read(). path = %s ,result = %d, errno = %d",
325            LOGARCHIVE_FILENAME_STORE_ARCHIVE, result, errno);
326     l_eFrameworkunifiedStatus  = eFrameworkunifiedStatusAccessError;
327   } else {
328     char    *endptr;
329     int      error_number;
330     int      temp_value;
331     buf[FILENUMBER_DIGIT_NUM]  = '\x0';
332     errno         = EOK;
333     temp_value    = strtol(buf, &endptr, 10);
334     error_number  = errno;
335     if ((error_number != EOK) || (*endptr != '\x0')) {
336       FRAMEWORKUNIFIEDLOG(ZONE_ERR,__FUNCTION__," Error. Failed to comvert string. source = %s ,errno = %d", buf, errno);
337       l_eFrameworkunifiedStatus  = eFrameworkunifiedStatusInvldParam;
338     } else {
339       filenumber = temp_value;
340     }
341   }
342   result = close(fd);
343   if (result != 0) {  // LCOV_EXCL_BR_LINE 6: close() must return ok
344     // LCOV_EXCL_START 6: close() must return ok
345     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
346     FRAMEWORKUNIFIEDLOG(ZONE_ERR,__FUNCTION__," Error. close(). path = %s ,errno = %d", LOGARCHIVE_FILENAME_STORE_ARCHIVE, errno);
347     // LCOV_EXCL_STOP
348   }
349   result = remove(LOGARCHIVE_FILENAME_STORE_ARCHIVE);
350   if (result != 0) {  // LCOV_EXCL_BR_LINE 6: remove() must return ok
351     // LCOV_EXCL_START 6: remove() must return ok
352     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
353     FRAMEWORKUNIFIEDLOG(ZONE_ERR,__FUNCTION__," Error. remove(). path = %s ,errno = %d", LOGARCHIVE_FILENAME_STORE_ARCHIVE, errno);
354     // LCOV_EXCL_STOP
355   }
356   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
357   return l_eFrameworkunifiedStatus;
358 }
359
360 static EFrameworkunifiedStatus storeTempArchive(const std::string &real_name)
361 {
362   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "+");
363   std::string filename;
364   size_t      pos;
365   int         fd;
366   int         result;
367   const char  *p_real_filename;
368   EFrameworkunifiedStatus  l_eFrameworkunifiedStatus = eFrameworkunifiedStatusOK;
369
370   fd = open(LOGARCHIVE_FILENAME_STORE_ARCHIVE, O_CREAT | O_WRONLY, TMPFILE_MODE);
371   if (fd == -1) {  // LCOV_EXCL_BR_LINE 5: open's error case
372     // LCOV_EXCL_START 5: open's error case
373     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
374     FRAMEWORKUNIFIEDLOG(ZONE_ERR,__FUNCTION__," Error. open(). path = %s ,errno = %d", LOGARCHIVE_FILENAME_STORE_ARCHIVE, errno);
375     return eFrameworkunifiedStatusAccessError;
376     // LCOV_EXCL_STOP
377   }
378
379   pos = real_name.find_last_of(PATHNAME_SEPARATOR);
380   if (pos == std::string::npos) {  // LCOV_EXCL_BR_LINE 6: there must be '/' in string real_name
381     // LCOV_EXCL_START 6: there must be '/' in string real_name
382     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
383     p_real_filename  = real_name.c_str();
384     // LCOV_EXCL_STOP
385   } else {
386     p_real_filename  = &real_name[pos + 1];
387   }
388
389   result = write(fd, p_real_filename, FILENUMBER_DIGIT_NUM);
390   if (result != FILENUMBER_DIGIT_NUM) {  // LCOV_EXCL_BR_LINE 5: write's error case
391     // LCOV_EXCL_START 5: write's error case
392     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
393     FRAMEWORKUNIFIEDLOG(ZONE_ERR,__FUNCTION__," Error. write(). path = %s ,result = %d, errno = %d",
394            LOGARCHIVE_FILENAME_STORE_ARCHIVE, result, errno);
395     l_eFrameworkunifiedStatus = eFrameworkunifiedStatusAccessError;
396     // LCOV_EXCL_STOP
397   }
398
399   result = close(fd);
400   if (result != 0) {  // LCOV_EXCL_BR_LINE 5: close's error case
401     // LCOV_EXCL_START 5: close's error case
402     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
403     FRAMEWORKUNIFIEDLOG(ZONE_ERR,__FUNCTION__," Error. close(). path = %s ,errno = %d", LOGARCHIVE_FILENAME_STORE_ARCHIVE, errno);
404     l_eFrameworkunifiedStatus = eFrameworkunifiedStatusAccessError;
405     // LCOV_EXCL_STOP
406   }
407   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
408   return l_eFrameworkunifiedStatus;
409 }
410
411
412
413 //static EFrameworkunifiedStatus closeArchive(TAR* f_pTarInfo) {
414 static EFrameworkunifiedStatus closeArchive(TAR* f_pTarInfo, SS_STORELOGS_OPE_TYPE type) {
415
416   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "+");
417   EFrameworkunifiedStatus l_eFrameworkunifiedStatus = eFrameworkunifiedStatusOK;
418
419   if (0 != tar_append_eof(f_pTarInfo)) {  // LCOV_EXCL_BR_LINE 5: tar_append_eof's error case
420     // LCOV_EXCL_START 5: tar_append_eof's error case
421     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
422     FRAMEWORKUNIFIEDLOG(ZONE_INFO, __PRETTY_FUNCTION__, "tar_append_eof()");
423     l_eFrameworkunifiedStatus = eFrameworkunifiedStatusFail;
424     // LCOV_EXCL_STOP
425   }
426   if (0 != tar_close(f_pTarInfo)) {  // LCOV_EXCL_BR_LINE 5: tar_close's error case
427     // LCOV_EXCL_START 5: tar_close's error case
428     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
429     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Could not close archive");
430     l_eFrameworkunifiedStatus = eFrameworkunifiedStatusFail;
431     // LCOV_EXCL_STOP
432   }
433
434   if (eFrameworkunifiedStatusOK == l_eFrameworkunifiedStatus) {  // LCOV_EXCL_BR_LINE 6: l_eFrameworkunifiedStatus must be eFrameworkunifiedStatusOK
435     l_eFrameworkunifiedStatus = copyFile(m_tmpName, m_pathAndName);
436     if (eFrameworkunifiedStatusOK == l_eFrameworkunifiedStatus) {
437
438       if (type == SS_STORELOGS_ILLEGAL) {
439         l_eFrameworkunifiedStatus = storeTempArchive(m_pathAndName);
440         if (eFrameworkunifiedStatusOK != l_eFrameworkunifiedStatus) {
441           FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Error. Failed to store temporary file.");
442         }
443       }
444
445       l_eFrameworkunifiedStatus =
446         (0 == remove(m_tmpName.c_str())) ? eFrameworkunifiedStatusOK : eFrameworkunifiedStatusFault;
447       if (eFrameworkunifiedStatusOK != l_eFrameworkunifiedStatus) {  // LCOV_EXCL_BR_LINE 5: remove's error case
448         // LCOV_EXCL_START 5: remove's error case
449         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
450         FRAMEWORKUNIFIEDLOG(
451           ZONE_WARN,
452           __FUNCTION__,
453           " Warning. Failed to remove temporary archive. Will overwrite on next event");
454         // LCOV_EXCL_STOP
455       }
456     } else if (eFrameworkunifiedStatusErrNoEAGAIN == l_eFrameworkunifiedStatus) {  // LCOV_EXCL_BR_LINE 4: no space error case
457       // LCOV_EXCL_START 4: no space error case
458       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
459       // disk space full
460       struct stat st_buf;
461       size_t req_size;
462       if (stat(m_tmpName.c_str(), &st_buf) != -1) {
463         req_size = st_buf.st_size;
464         if (eFrameworkunifiedStatusOK == forceDeleteOldLog(m_pathAndName, req_size)) {
465           l_eFrameworkunifiedStatus = copyFile(m_tmpName, m_pathAndName);
466           if (eFrameworkunifiedStatusOK != l_eFrameworkunifiedStatus) {
467             FRAMEWORKUNIFIEDLOG(
468               ZONE_ERR,
469               __FUNCTION__,
470               "Try Again but Error. Failed to copy to destination.%s, size=%d",
471               m_pathAndName.c_str(), req_size);
472           }
473         } else {
474           FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
475                  "Error. force delete failed.%s, size=%d",
476                  m_pathAndName.c_str(), req_size);
477         }
478         FRAMEWORKUNIFIEDLOG(ZONE_INFO, __FUNCTION__, " emmc full: dest=%s, size=%d",
479                m_pathAndName.c_str(), req_size);
480       } else {
481         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
482                "Warning. Failed to get tmp log file stat. dest=%s",
483                m_pathAndName.c_str());
484       }
485       // LCOV_EXCL_STOP
486     } else {
487       /* should we copy lost archive to emmc?? */
488       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
489              " Error. Failed to copy to destination. %s", m_pathAndName.c_str());
490     }
491     remove(m_tmpName.c_str());
492     m_tmpName = "";
493   }
494
495   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
496   return (l_eFrameworkunifiedStatus);
497 }
498
499 static EFrameworkunifiedStatus addFileToArchive(TAR* f_pTarInfo, std::string f_filename,
500                                    std::string f_destinationName) {
501   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "+");
502   EFrameworkunifiedStatus l_eFrameworkunifiedStatus = eFrameworkunifiedStatusOK; /* check if Tar is open and if file can be read */
503
504   if ((NULL != f_pTarInfo) && (0 == access(f_filename.c_str(), R_OK))
505       && (0 != f_destinationName.length())) {
506     int l_tarRetVal = tar_append_file(f_pTarInfo, const_cast<char*>(f_filename.c_str()),
507                                       const_cast<char*>(f_destinationName.c_str()));
508     if (0 != l_tarRetVal) {
509       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
510              "Could not add file \'%s\' to tar archive.", f_filename.c_str());
511       l_eFrameworkunifiedStatus = eFrameworkunifiedStatusAccessError;
512     }
513   } else {
514     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
515            "Archive not opened or could not access file: \"%s\"",
516            f_filename.c_str());
517     l_eFrameworkunifiedStatus = eFrameworkunifiedStatusInvldParam;
518   }
519
520   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
521   return (l_eFrameworkunifiedStatus);
522 }
523
524 static EFrameworkunifiedStatus addAllFileToArchive (TAR* f_pTarInfo, std::string collectDir)
525 {
526   struct dirent l_pDirent;
527   struct dirent* next;
528   EFrameworkunifiedStatus l_eStatus  = eFrameworkunifiedStatusFail;
529   DEB_LOGGERSERVICELOG(ZONE_FUNC, __FUNCTION__, "+");
530   DIR * l_pDir = opendir(collectDir.c_str());
531   if (l_pDir == NULL) {
532     DEB_LOGGERSERVICELOG(ZONE_ERR, __FUNCTION__, "Could not open directory: %s", collectDir.c_str());
533   } else {
534     while (0 == readdir_r(l_pDir,&l_pDirent,&next) && next != NULL) {
535       if ( ( 0   != strcmp( l_pDirent.d_name, "."  ) ) &&
536       ( 0   != strcmp( l_pDirent.d_name, ".." ))  &&
537       ( 0   != strcmp( l_pDirent.d_name, "lost+found" ))  &&
538       ( '.' != l_pDirent.d_name[0] ) ) {
539         std::string l_fileSource = collectDir;
540         l_fileSource.append("/");
541         l_fileSource.append(l_pDirent.d_name);
542         std::string l_fileDestination = l_pDirent.d_name;
543         l_eStatus = addToArchive(f_pTarInfo,l_fileSource,l_fileDestination);
544         if (l_eStatus != eFrameworkunifiedStatusOK) {
545           break;
546         }
547       }
548     }
549     closedir (l_pDir);
550   }
551   DEB_LOGGERSERVICELOG(ZONE_FUNC, __FUNCTION__, "-");
552   return l_eStatus;
553 }
554
555 static EFrameworkunifiedStatus addDirectoryToArchive(TAR* f_pTarInfo, std::string f_path,
556                                         std::string f_destinationName,
557                                         UI_8 f_depth) {
558   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "+");
559   EFrameworkunifiedStatus l_eFrameworkunifiedStatus = eFrameworkunifiedStatusOK;
560
561   DIR *l_pDir = opendir(f_path.c_str());
562   if (l_pDir != NULL) {
563     struct dirent* l_pDirent;
564     while ((l_pDirent = readdir(l_pDir)) != NULL) {
565       if ((0 != strcmp(l_pDirent->d_name, ".")) && /* Ignore special  . directory.                     */
566           (0 != strcmp(l_pDirent->d_name, "..")) && /* Ignore special .. directory.                     */
567           ('.' != l_pDirent->d_name[0])) {  /* Ignore hidden files                              */
568         std::string l_extension = "/";
569         std::string l_fileName = f_path;
570         std::string l_destName = f_destinationName;
571         l_extension.append(l_pDirent->d_name);
572         l_fileName.append(l_extension);
573         l_destName.append(l_extension);
574         l_eFrameworkunifiedStatus = addToArchive(f_pTarInfo, l_fileName, l_destName,
575                                     static_cast<UI_8>(f_depth - 1));
576       }
577     }
578     closedir(l_pDir);
579   }
580
581   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
582   return (l_eFrameworkunifiedStatus);
583 }
584
585 static SI_32 gzOpenArchive(PCHAR f_pcPathname, SI_32 f_siOflags,
586                            SI_32 f_siMode) {
587   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "+");
588   SI_32 l_siFileDescriptor = -1;
589
590   if (f_pcPathname) {
591     PCHAR l_pcGzoflags;
592
593     switch (f_siOflags & O_ACCMODE) {  // LCOV_EXCL_BR_LINE 200: only O_WRONLY be set
594     case O_WRONLY:
595       l_pcGzoflags = (PCHAR) "wb";
596       break;
597     // LCOV_EXCL_START 200: only O_WRONLY be set
598     case O_RDONLY:
599       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
600       l_pcGzoflags = (PCHAR) "rb";
601       break;
602     // LCOV_EXCL_STOP
603     case O_RDWR:
604     default:
605       return -1;
606     }
607     if (-1 == (l_siFileDescriptor = open(f_pcPathname, f_siOflags, f_siMode))) {
608       FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
609       return -1;
610     }
611
612     if ((f_siOflags & O_CREAT) && fchmod(l_siFileDescriptor, f_siMode)) {
613       close(l_siFileDescriptor);
614       FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
615       return -1;
616     }
617
618     g_gztype = gzdopen(l_siFileDescriptor, l_pcGzoflags);
619     if (!g_gztype) {
620       close(l_siFileDescriptor);
621       FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
622       return -1;
623     }
624   } else {
625     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Source Path empty.");
626   }
627
628   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
629   return (SI_32) l_siFileDescriptor;
630 }
631
632 static SI_32 gzCloseArchive() {
633   return gzclose(g_gztype);
634 }
635
636 static ssize_t gzWriteArchive(int fd, const void* buf, size_t count) {
637   return gzwrite(g_gztype, const_cast<void*>(buf), (unsigned int) count);
638 }
639
640 static ssize_t gzReadArchive(int fd, void* buf, size_t count) {
641   return gzread(g_gztype, buf, (unsigned int) count);
642 }
643
644 static EFrameworkunifiedStatus copyFile(std::string f_source, std::string f_destination) {
645   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "+");
646   EFrameworkunifiedStatus l_eStatus = eFrameworkunifiedStatusOK;
647   ssize_t l_nrd;
648   ssize_t l_nwr;
649   char l_buf[1024];
650
651   int l_if = open(f_source.c_str(), O_RDONLY | O_CLOEXEC);
652   if (-1 == l_if) {
653     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
654            "Error. Failed to open file: %s for reading.", f_source.c_str());
655     l_eStatus = eFrameworkunifiedStatusFail;
656   } else {
657     std::string l_tmpDest;
658     size_t l_pos = f_destination.find_last_of('/');
659
660     if (std::string::npos != l_pos) {  // LCOV_EXCL_BR_LINE 6: there must be '/' in string f_destination
661       l_tmpDest = f_destination.substr(0, l_pos);
662       l_tmpDest.append("/");
663       l_tmpDest.append(LOGGER_TMP_FN);
664       if (unlink(l_tmpDest.c_str()) != 0) {
665         // always delete tmpLog, and create new tmpLog.
666       }
667     } else {
668       // LCOV_EXCL_START 6: there must be '/' in string f_destination
669       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
670       l_tmpDest = f_destination;
671       // LCOV_EXCL_STOP
672     }
673
674     int l_of = open(l_tmpDest.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC,
675                     0640);
676     if (-1 == l_of) {  // LCOV_EXCL_BR_LINE 5: open's error case
677       // LCOV_EXCL_START 5: open's error case
678       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
679       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "dest open fail:%s,errno:%d,msg:%s",
680              l_tmpDest.c_str(), errno, strerror(errno));
681       l_eStatus = eFrameworkunifiedStatusFail;
682       // LCOV_EXCL_STOP
683     } else {
684       do {
685         l_nrd = read(l_if, l_buf, sizeof(l_buf));
686         if (l_nrd == -1) {  // LCOV_EXCL_BR_LINE 5: read's error case
687           // LCOV_EXCL_START 5: read's error case
688           AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
689           FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "read fail:%s,errno:%d,msg:%s",
690                  f_source.c_str(), errno, strerror(errno));
691           l_eStatus = eFrameworkunifiedStatusAccessError;
692           break;
693           // LCOV_EXCL_STOP
694         }
695         l_nwr = write(l_of, l_buf, l_nrd);
696         if (l_nwr == -1) {  // LCOV_EXCL_BR_LINE 5: write's error case
697           // LCOV_EXCL_START 5: write's error case
698           AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
699           if (ENOSPC == errno) {  // LCOV_EXCL_BR_LINE 4: no space error case
700             // LCOV_EXCL_START 4: no space error case
701             AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
702             FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
703                    "write fail(ENOSPC):%s,errno:%d,msg:%s", l_tmpDest.c_str(),
704                    errno, strerror(errno));
705             l_eStatus = eFrameworkunifiedStatusErrNoEAGAIN;
706             // LCOV_EXCL_STOP
707           } else {
708             FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "write fail:%s,errno:%d,msg%s",
709                    l_tmpDest.c_str(), errno, strerror(errno));
710             l_eStatus = eFrameworkunifiedStatusAccessError;
711           }
712           break;
713           // LCOV_EXCL_STOP
714         }
715       } while (l_nrd > 0);
716       fsync(l_of);
717       close(l_of);
718     }
719     close(l_if);
720
721     if (rename(l_tmpDest.c_str(), f_destination.c_str()) != 0) {  // LCOV_EXCL_BR_LINE 5: rename's error case
722       // LCOV_EXCL_START 5: rename's error case
723       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
724       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "rename %s to %s fail,errno:%d,msg:%s",
725              l_tmpDest.c_str(), f_destination.c_str(), errno, strerror(errno));
726       // LCOV_EXCL_STOP
727     }
728
729     if (std::string::npos != l_pos) {  // LCOV_EXCL_BR_LINE 6: there must be '/' in string f_destination
730       std::string l_destPath = f_destination.substr(0, l_pos);
731       SyncDir(l_destPath);
732     } else {
733       // LCOV_EXCL_START 6: there must be '/' in string f_destination
734       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
735       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "dest invalid:%s", f_destination.c_str());
736       // LCOV_EXCL_STOP
737     }
738   }
739   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
740   return (l_eStatus);
741 }
742
743 static EFrameworkunifiedStatus copyDirectory (std::string f_source, std::string f_destination)
744 {
745   DEB_LOGGERSERVICELOG(ZONE_FUNC, __FUNCTION__, "+");
746   EFrameworkunifiedStatus l_eStatus = eFrameworkunifiedStatusOK;
747   DIR * l_pDir = opendir(f_source.c_str());
748   if (l_pDir == NULL) {
749     DEB_LOGGERSERVICELOG(ZONE_ERR, __FUNCTION__, "Could not open directory: %s", f_source.c_str());
750   } else {
751     if (mkdir(f_destination.c_str(),0775) == -1) {
752       if (errno == EEXIST) {
753         DEB_LOGGERSERVICELOG(ZONE_FUNC, __FUNCTION__, "Directory: %s already exists.", f_destination.c_str());
754       } else {
755         DEB_LOGGERSERVICELOG(ZONE_ERR, __FUNCTION__, "Could not create directory: %s. Errno: %s", f_destination.c_str(),strerror(errno));
756         l_eStatus = eFrameworkunifiedStatusFail;
757       }
758     } else {
759       SyncDir(f_destination);
760       size_t l_pos = f_destination.find_last_of('/');
761       if (l_pos != std::string::npos) {
762         std::string l_destPath = f_destination.substr(0, l_pos);
763         SyncDir(l_destPath);
764       }
765     }
766
767     struct dirent l_pDirent;
768     struct dirent* next;
769     while (0 == readdir_r(l_pDir,&l_pDirent,&next) && next != NULL) {
770       if ( ( 0   != strcmp( l_pDirent.d_name, "."  ) ) &&
771       ( 0   != strcmp( l_pDirent.d_name, ".." ))  &&
772       ( 0   != strcmp( l_pDirent.d_name, "lost+found" ))  &&
773       ( '.' != l_pDirent.d_name[0] ) ) {
774         std::string l_fileSource = f_source;
775         std::string l_fileDestination = f_destination;
776         l_fileSource.append("/");
777         l_fileSource.append(l_pDirent.d_name);
778         l_fileDestination.append("/");
779         l_fileDestination.append(l_pDirent.d_name);
780         l_eStatus = copyUntyped(l_fileSource,l_fileDestination);
781       }
782     }
783     closedir (l_pDir);
784   }
785   DEB_LOGGERSERVICELOG(ZONE_FUNC, __FUNCTION__, "-");
786   return l_eStatus;
787 }
788
789 static EFrameworkunifiedStatus copyUntyped (std::string f_source, std::string f_destination)
790 {
791   DEB_LOGGERSERVICELOG(ZONE_FUNC, __FUNCTION__, "+");
792   EFrameworkunifiedStatus l_eStatus = eFrameworkunifiedStatusOK;
793   struct stat  l_stat;
794   SI_8         l_statRetVal;
795   if (0 != access(f_source.c_str(), F_OK)) {
796     DEB_LOGGERSERVICELOG(ZONE_ERR,__FUNCTION__," Error. The specified file path and name does not exist: %s", f_source.c_str());
797   } else if (0 != (l_statRetVal = lstat(f_source.c_str(), &l_stat))) {
798     DEB_LOGGERSERVICELOG(ZONE_ERR,__FUNCTION__," Error. stat() for file or directory returned error: %s -> %d", f_source.c_str(), l_statRetVal);
799   } else if (0 != S_ISDIR(l_stat.st_mode)) {
800     l_eStatus = copyDirectory(f_source, f_destination);
801   } else if (0 != S_ISLNK(l_stat.st_mode)) {
802     l_eStatus = copyDirectory(f_source, f_destination);
803   } else if (0 != S_ISREG(l_stat.st_mode)) {
804     l_eStatus = copyFile(f_source, f_destination);
805   } else {
806     DEB_LOGGERSERVICELOG(ZONE_ERR,__FUNCTION__," Error. specified file may be a symbolic link or other non 'regular' type. File: %s, mode: 0x%04X.",f_source.c_str(),l_stat.st_mode);
807   }
808   DEB_LOGGERSERVICELOG(ZONE_FUNC, __FUNCTION__, "-");
809   return l_eStatus;
810 }
811
812 static EFrameworkunifiedStatus copyFileToAccOffOnDir(std::vector<LogInfo>& list, SS_STORELOGS_OPE_TYPE type)
813 {
814   EFrameworkunifiedStatus l_eStatus = eFrameworkunifiedStatusOK;
815   EFrameworkunifiedStatus l_eFrameworkunifiedStatus = eFrameworkunifiedStatusOK;
816   std::string f_destination = LOGGERSERVICELOG_TMP_OUTPUT_PATH;
817   f_destination.append("/");
818   f_destination.append(ACCOFFON_DIR_NAME);
819   DIR * l_pDir = opendir(LOGGERSERVICELOG_TMP_OUTPUT_PATH);
820   if (l_pDir == NULL) {
821     DEB_LOGGERSERVICELOG(ZONE_ERR, __FUNCTION__, "Could not open directory: %s", LOGGERSERVICELOG_TMP_OUTPUT_PATH);
822     l_eStatus = eFrameworkunifiedStatusFail;
823     return l_eStatus;
824   } else {
825     closedir (l_pDir);
826     if (mkdir(f_destination.c_str(), 0775) == -1) {
827       DEB_LOGGERSERVICELOG(ZONE_ERR, __FUNCTION__, "Could not create directory: %s. Errno: %s", f_destination.c_str(),strerror(errno));
828       l_eStatus = eFrameworkunifiedStatusFail;
829       return l_eStatus;
830     }
831   } if (list.size() != 0) {
832     for (UI_32 j = 0; j < list.size(); j++) {
833       std::string dest_name = f_destination;
834       dest_name.append("/");
835       dest_name.append(list.at(j).dest_name);
836       l_eFrameworkunifiedStatus = copyUntyped(list.at(j).file_path, dest_name);
837       if (l_eFrameworkunifiedStatus != eFrameworkunifiedStatusOK) {
838         DEB_LOGGERSERVICELOG(ZONE_WARN, __FUNCTION__, " Error. File %s failed to archive.", list.at(j).file_path.c_str());
839         l_eStatus = l_eFrameworkunifiedStatus;
840       }
841     }
842     copyLoggerservicelogFile(f_destination);
843   }
844   return l_eStatus;
845 }
846
847 ELOGGERSERVICELOGTYPE QueryLoggerservicelogType(std::string f_logname) {
848 //  if (f_logname.find("_ILG_RESET.tar.gz") != std::string::npos
849   if (f_logname.find(SS_STORE_FILENAME_SYSILG_TERM) != std::string::npos) {
850     return eLoggerservicelogTypeSysAbnormal;
851   } else if (f_logname.find(SS_STORE_FILENAME__CWORD52__TERM) != std::string::npos) {
852     return eLoggerservicelogType_CWORD52_;
853   } else if (f_logname.find("_ILG_RESET.tar.gz") != std::string::npos
854
855       || f_logname.find("_ERR.tar.gz") != std::string::npos) {
856     return eLoggerservicelogTypeAbnormal;
857   } else if (f_logname.find("_GRP_RELAUNCH.tar.gz") != std::string::npos) {
858     return eLoggerservicelogTypeGrpRelaunch;
859   } else if (f_logname.find(".tar.gz") != std::string::npos) {
860     return eLoggerservicelogTypeNormal;
861   } else {
862     return eLoggerservicelogTypeOther;
863   }
864 }
865
866 void SyncDir(std::string f_dir_path) {
867   int fd = open(f_dir_path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
868 #define OPE_ERR_MSG "%s %s failed. errno:%d,msg:%s"
869   if (fd == -1) {
870     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, OPE_ERR_MSG, f_dir_path.c_str(), "open",
871            errno, strerror(errno));
872   } else {
873     if (fsync(fd) == -1) {  // LCOV_EXCL_BR_LINE 5: fsync's error case
874       // LCOV_EXCL_START 5: fsync's error case
875       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
876       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, OPE_ERR_MSG, f_dir_path.c_str(), "fsync",
877              errno, strerror(errno));
878       // LCOV_EXCL_STOP
879     }
880     if (close(fd) == -1) {  // LCOV_EXCL_BR_LINE 5: close's error case
881       // LCOV_EXCL_START 5: close's error case
882       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
883       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, OPE_ERR_MSG, f_dir_path.c_str(), "close",
884              errno, strerror(errno));
885       // LCOV_EXCL_STOP
886     }
887   }
888 #undef OPE_ERR_MSG
889 }
890
891 // LCOV_EXCL_START 4: no space error case
892 size_t deleteRequestLogs(std::string f_emmcpath, ELOGGERSERVICELOGTYPE f_reqtype,
893                          size_t f_reqsize, ELOGGERSERVICELOGTYPE f_deltype) {
894   AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
895   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "+");
896   DIR* l_dirp = NULL;
897   std::vector<std::string> vect;
898   std::vector<std::string>::iterator it;
899   UI_32 l_count = 0;
900   size_t l_totalsize = 0;
901
902   ELOGGERSERVICELOGTYPE filetype;
903
904
905   // create saved file list on eMMC
906   l_dirp = opendir(f_emmcpath.c_str());
907   if (l_dirp != NULL) {
908     struct dirent l_dirent;
909     struct dirent* next;
910     while (0 == readdir_r(l_dirp, &l_dirent, &next) && next != NULL) {
911       std::string l_filename = l_dirent.d_name;
912
913 //      if (QueryLoggerservicelogType(l_filename) == f_deltype) {
914 //        vect.push_back(l_filename);
915 //      }
916       if ((l_filename == ".") && (l_filename == "..")) {
917         continue;
918       }
919       filetype = QueryLoggerservicelogType(l_filename);
920       if (f_deltype == eLoggerservicelogTypeAbnormal) {
921         if ((filetype == eLoggerservicelogTypeAbnormal) || (filetype == eLoggerservicelogTypeSysAbnormal) ||
922             (filetype == eLoggerservicelogType_CWORD52_)) {
923           vect.push_back(l_filename);
924         }
925       } else if (filetype == f_deltype) {
926         vect.push_back(l_filename);
927       }
928
929     }
930     closedir(l_dirp);
931   } else {
932     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, " open failed eMMC path: %s",
933            f_emmcpath.c_str());
934     FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
935     return 0;
936   }
937
938   // get num of delete logs
939   std::sort(vect.begin(), vect.end());
940   for (it = vect.begin(); it != vect.end(); it++) {
941     l_count++;
942
943     std::string l_filename = *it;
944     struct stat st_buf;
945     std::string l_tmpstr = f_emmcpath;
946     l_tmpstr.append(l_filename.c_str());
947     if (stat(l_tmpstr.c_str(), &st_buf) != -1) {
948       l_totalsize += st_buf.st_size;
949     }
950
951     if (l_totalsize > f_reqsize) {
952       break;
953     }
954   }
955
956   // start delete logs
957   if ((l_totalsize > f_reqsize) || (f_reqtype == eLoggerservicelogTypeAbnormal)
958       || (f_reqtype == eLoggerservicelogTypeGrpRelaunch)) {
959     for (it = vect.begin(); it != vect.end() && l_count > 0; it++) {
960       l_count--;
961
962       std::string l_filename = *it;
963       std::string l_tmpstr = f_emmcpath;
964       l_tmpstr.append(l_filename.c_str());
965       if (unlink(l_tmpstr.c_str()) != 0) {
966         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, " unlink failed %s:%d,msg:%s",
967                l_tmpstr.c_str(), errno, strerror(errno));
968       }
969       FRAMEWORKUNIFIEDLOG(ZONE_INFO, __FUNCTION__, " del-file=%s total=%d", l_tmpstr.c_str(),
970              l_totalsize);
971     }
972
973     if (f_reqtype == eLoggerservicelogTypeAbnormal) {
974       removeSameNumFiles(it, f_emmcpath, vect);
975     }
976
977     SyncDir(f_emmcpath);
978   } else {
979     l_totalsize = 0;
980     FRAMEWORKUNIFIEDLOG(
981       ZONE_INFO,
982       __FUNCTION__,
983       " nothing to delete logs req-type=%d del-logtype=%d total=%d, log_count=%d",
984       f_reqtype, f_deltype, l_totalsize, l_count);
985   }
986
987   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
988   return l_totalsize;
989 }
990 // LCOV_EXCL_STOP
991
992 // LCOV_EXCL_START 4: no space error case
993 EFrameworkunifiedStatus forceDeleteOldLog(std::string f_archive_destination,
994                              size_t f_req_size) {
995   AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
996   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "+");
997   EFrameworkunifiedStatus l_eStatus = eFrameworkunifiedStatusFail;
998   std::string l_emmc_path;
999   size_t l_delsize = 0;
1000   ELOGGERSERVICELOGTYPE l_logtype = eLoggerservicelogTypeOther;
1001
1002   size_t l_pos = f_archive_destination.find_last_of('/');
1003   if (std::string::npos != l_pos) {
1004     l_emmc_path = f_archive_destination.substr(0, l_pos);
1005     l_emmc_path.append("/");
1006     l_logtype = QueryLoggerservicelogType(
1007                   f_archive_destination.substr(l_pos + 1,
1008                       f_archive_destination.size() - l_pos + 1));
1009
1010     if ((l_logtype == eLoggerservicelogTypeSysAbnormal) || (l_logtype == eLoggerservicelogType_CWORD52_)) {
1011       l_logtype = eLoggerservicelogTypeAbnormal;
1012     }
1013
1014   }
1015
1016   if (l_logtype == eLoggerservicelogTypeOther) {
1017     // not found
1018     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, " Invalid Parameter. dest=%s",
1019            f_archive_destination.c_str());
1020     FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
1021     return eFrameworkunifiedStatusFail;
1022   }
1023
1024   // remove dirty-file if exist
1025   if (unlink(f_archive_destination.c_str()) != 0) {
1026     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, " unlink failed %s:%d.",
1027            f_archive_destination.c_str(), errno);
1028   }
1029
1030   // delete normal log
1031   l_delsize = deleteRequestLogs(l_emmc_path, l_logtype, f_req_size,
1032                                 eLoggerservicelogTypeNormal);
1033   if (l_delsize >= f_req_size) {
1034     FRAMEWORKUNIFIEDLOG(ZONE_INFO, __FUNCTION__,
1035            " delete normal logs success: req-size=%d, del-size=%d", f_req_size,
1036            l_delsize);
1037     l_eStatus = eFrameworkunifiedStatusOK;
1038   } else if (l_logtype == eLoggerservicelogTypeAbnormal) {
1039     // delete abnormal log if request type is abnormal
1040     FRAMEWORKUNIFIEDLOG(ZONE_INFO, __FUNCTION__,
1041            " continue delete abnormal logs: req-size=%d, del-size=%d",
1042            f_req_size, l_delsize);
1043     size_t l_tmpsize = f_req_size;
1044     l_tmpsize -= l_delsize;
1045     l_delsize = deleteRequestLogs(l_emmc_path, l_logtype, l_tmpsize,
1046                                   eLoggerservicelogTypeAbnormal);
1047     if (l_delsize >= l_tmpsize) {
1048       FRAMEWORKUNIFIEDLOG(ZONE_INFO, __FUNCTION__,
1049              " delete abnormal logs success: req-size=%d, del-size=%d",
1050              f_req_size, l_delsize);
1051       l_eStatus = eFrameworkunifiedStatusOK;
1052     } else {
1053       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
1054              " abnormal log delete not complete. req-size=%d, del-size=%d",
1055              f_req_size, l_delsize);
1056     }
1057   } else if (l_logtype == eLoggerservicelogTypeGrpRelaunch) {
1058     FRAMEWORKUNIFIEDLOG(ZONE_INFO, __FUNCTION__,
1059            " continue delete group relaunch logs: req-size=%d, del-size=%d",
1060            f_req_size, l_delsize);
1061     size_t l_tmpsize = f_req_size;
1062     l_tmpsize -= l_delsize;
1063     l_delsize = deleteRequestLogs(l_emmc_path, l_logtype, l_tmpsize,
1064                                   eLoggerservicelogTypeGrpRelaunch);
1065     if (l_delsize >= l_tmpsize) {
1066       FRAMEWORKUNIFIEDLOG(ZONE_INFO, __FUNCTION__,
1067              " delete group relaunch logs success: req-size=%d, del-size=%d",
1068              f_req_size, l_delsize);
1069       l_eStatus = eFrameworkunifiedStatusOK;
1070     } else {
1071       FRAMEWORKUNIFIEDLOG(
1072         ZONE_ERR, __FUNCTION__,
1073         " group relaunch log delete not complete. req-size=%d, del-size=%d",
1074         f_req_size, l_delsize);
1075     }
1076   } else {
1077     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
1078            " normal log del not complete. req-size=%d, del-size=%d", f_req_size,
1079            l_delsize);
1080   }
1081
1082   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
1083   return l_eStatus;
1084 }
1085 // LCOV_EXCL_STOP
1086
1087 ///////////////////////////////////////////////////////////////////////
1088 /// Function SS_LoggerStoreDebugLogs
1089 ///////////////////////////////////////////////////////////////////////
1090 EFrameworkunifiedStatus SS_LoggerStoreLogs(SS_STORELOGS_OPE_TYPE type) {
1091   if (type < SS_STORELOGS_MAX) {
1092     return storeLogs(type);
1093   } else {
1094     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Error. Bad enum number %d", type);
1095     return eFrameworkunifiedStatusFail;
1096   }
1097 }
1098
1099
1100 EFrameworkunifiedStatus SS_LoggerStoreLogs_deleteOldLogAbnrm(const std::string& log_path,
1101                                                 std::vector<std::string>& l_vector,
1102                                                 const std::string& f_archive_destination,
1103                                                 SI_32 max_num,
1104                                                 UI_32 abnrm_total) {
1105   EFrameworkunifiedStatus l_eFrameworkunifiedStatus;
1106   l_eFrameworkunifiedStatus = deleteOldLogAbnrm(log_path, l_vector, f_archive_destination, max_num, abnrm_total);
1107   return l_eFrameworkunifiedStatus;
1108 }
1109
1110
1111 ////////////////////////////////////////////////////////////////////////////////////////////////////
1112 /// IsDirectory
1113 /// Method to check if the entity is a directory.
1114 ////////////////////////////////////////////////////////////////////////////////////////////////////
1115 static BOOL IsDirectory(std::string &f_cPath) {  // NOLINT (runtime/references)
1116   BOOL l_bReturn = FALSE;
1117   struct stat st_buf;
1118
1119   if (-1 == stat(f_cPath.c_str(), &st_buf)) {  // LCOV_EXCL_BR_LINE 5: stat's error case  // NOLINT (runtime/references)  // NOLINT[whitespace/line_length]
1120     // LCOV_EXCL_START 5: stat's error case
1121     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1122     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
1123            "Error: stat failed for path/file %s, errno %d", f_cPath.c_str(),
1124            errno);
1125     FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
1126     // LCOV_EXCL_STOP
1127   } else if (S_ISDIR(st_buf.st_mode)) {
1128     l_bReturn = TRUE;  // return true if f_cPath is a directory
1129   }
1130   return l_bReturn;
1131 }
1132
1133 ////////////////////////////////////////////////////////////////////////////////////////////////////
1134 /// RemoveDirectory
1135 /// Method to remove a directory.
1136 ////////////////////////////////////////////////////////////////////////////////////////////////////
1137 static BOOL RemoveDirectory(std::string &f_cPath) {  // NOLINT (runtime/references)
1138   BOOL l_bReturn = FALSE;
1139
1140   if (RemoveSubDirectory(f_cPath)) {  // LCOV_EXCL_BR_LINE 6: RemoveSubDirectory always return true
1141     // delete the parent directory
1142     if (0 == rmdir(f_cPath.c_str())) {  // LCOV_EXCL_BR_LINE 5: rmdir's error case
1143       l_bReturn = TRUE;
1144     }
1145   }
1146   return l_bReturn;
1147 }
1148
1149 ////////////////////////////////////////////////////////////////////////////////////////////////////
1150 /// RemoveSubDirectory
1151 /// Method to remove a sub directory.
1152 ////////////////////////////////////////////////////////////////////////////////////////////////////
1153 static BOOL RemoveSubDirectory(std::string &f_cPath) {  // NOLINT (runtime/references)
1154   BOOL l_bReturn = TRUE;
1155
1156   if (!f_cPath.empty()) {  // LCOV_EXCL_BR_LINE 6: f_cPath can't be empty
1157     std::string l_cFilePath = "";
1158     struct dirent l_Dirent;
1159     struct dirent* next;
1160     DIR *l_pDir = NULL;
1161
1162     l_pDir = opendir(f_cPath.c_str());
1163     if (NULL != l_pDir) {  // LCOV_EXCL_BR_LINE 5: opendir's error case
1164       if ('/' != f_cPath[f_cPath.length() - 1]) {  // LCOV_EXCL_BR_LINE 6: there must be no '/'
1165         f_cPath.append("/");
1166       }
1167
1168       while (0 == readdir_r(l_pDir, &l_Dirent, &next) && next != NULL) {
1169         if (0 != std::strcmp(l_Dirent.d_name, ".")
1170             && 0 != std::strcmp(l_Dirent.d_name, "..")
1171             && 0 != std::strcmp(l_Dirent.d_name, "lost+found")) {
1172           l_cFilePath.assign(f_cPath);
1173           l_cFilePath.append(l_Dirent.d_name);  // concatenate the strings to get the complete f_cPath
1174           if (TRUE == IsDirectory(l_cFilePath)) {
1175             l_bReturn = RemoveDirectory(l_cFilePath);
1176           } else {
1177             // it's a file, we can use unlink
1178             if (unlink(l_cFilePath.c_str()) == -1) {  // LCOV_EXCL_BR_LINE 5: unlink's error case
1179               // LCOV_EXCL_START 5: unlink's error case
1180               AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1181               l_bReturn = FALSE;
1182               // LCOV_EXCL_STOP
1183             }
1184           }
1185         }
1186       }
1187       closedir(l_pDir);  // close the directory
1188       SyncDir(f_cPath);
1189     } else {
1190       // LCOV_EXCL_START 5: opendir's error case
1191       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1192       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "l_pDir is NULL");
1193       // LCOV_EXCL_STOP
1194     }
1195   } else {
1196     // LCOV_EXCL_START 6: f_cPath can't be empty
1197     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1198     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Pathname empty.");
1199     l_bReturn = FALSE;
1200     // LCOV_EXCL_STOP
1201   }
1202   return l_bReturn;
1203 }
1204
1205 static void CreateSaveFinFlag(SS_STORELOGS_OPE_TYPE type) {
1206   if (type == SS_STORELOGS_INTERFACEUNIFIEDLOG) {
1207     int fd;
1208     fd = open(SS_LOGGER_SAVE_INTERFACEUNIFIEDLOG_FLAG,
1209               O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0640);
1210     if (fd == -1) {
1211       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Error. Create %s. errno %d msg :%s",
1212              SS_LOGGER_SAVE_INTERFACEUNIFIEDLOG_FLAG, errno, strerror(errno));
1213     } else {
1214       fsync(fd);
1215       close(fd);
1216       std::string l_flagPath = SS_LOGGER_SAVE_INTERFACEUNIFIEDLOG_FLAG;
1217       size_t l_pos = l_flagPath.find_last_of('/');
1218       if (std::string::npos != l_pos) {  // LCOV_EXCL_BR_LINE 6: there must be '/' in l_flagPath
1219         std::string l_dirPath = l_flagPath.substr(0, l_pos);
1220         SyncDir(l_dirPath);
1221         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "create saveflag finish.");
1222         fprintf(stderr, "%s:Completed\n", __FUNCTION__);
1223       }
1224     }
1225   }
1226 }
1227
1228 static void deleteAccOffOnUntyped(std::string deletePath)
1229 {
1230   struct stat  l_stat;
1231   SI_8  l_statRetVal;
1232   if (0 != access(deletePath.c_str(), F_OK)) {
1233     DEB_LOGGERSERVICELOG(ZONE_WARN, __FUNCTION__, "access error (%s)", deletePath.c_str());
1234   } else if (0 != (l_statRetVal = lstat(deletePath.c_str(), &l_stat))) {
1235     DEB_LOGGERSERVICELOG(ZONE_WARN, __FUNCTION__, "get stat error (%s)", deletePath.c_str());
1236   } else if (0 != S_ISDIR(l_stat.st_mode)) {
1237     deleteAccOffOnDir(deletePath);
1238   } else if (0 != S_ISREG(l_stat.st_mode)) {
1239     unlink(deletePath.c_str());
1240   }
1241 }
1242
1243 static void deleteAccOffOnDir(std::string deletePath)
1244 {
1245   DIR * l_pDir = opendir(deletePath.c_str());
1246   if (l_pDir != NULL) {
1247     struct dirent l_pDirent;
1248     struct dirent* next;
1249     while (0 == readdir_r(l_pDir,&l_pDirent,&next) && next != NULL) {
1250       if ( ( 0   != strcmp( l_pDirent.d_name, "."  ) ) &&
1251       ( 0   != strcmp( l_pDirent.d_name, ".." ))  &&
1252       ( 0   != strcmp( l_pDirent.d_name, "lost+found" ))  &&
1253       ( '.' != l_pDirent.d_name[0] ) ) {
1254         std::string l_deletePath = deletePath;
1255         l_deletePath.append("/");
1256         l_deletePath.append(l_pDirent.d_name);
1257         deleteAccOffOnUntyped(l_deletePath);
1258       }
1259     }
1260     closedir (l_pDir);
1261   }
1262   RemoveDirectory(deletePath);
1263 }
1264
1265 static EFrameworkunifiedStatus storeLogs(SS_STORELOGS_OPE_TYPE type) {
1266   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "+");
1267   EFrameworkunifiedStatus l_eFrameworkunifiedStatus = eFrameworkunifiedStatusOK;
1268
1269   std::string file_name;
1270   std::vector<LogInfo> list;
1271   std::vector<LoggerservicelogInfo> loggerservicelogList;
1272   TAR* tar_info = NULL;
1273   uint32_t time_info;
1274   uint8_t status;
1275   CfgInfo cfginfo;
1276
1277   UI_32 l_counter = INVALID_FILENUMBER;
1278
1279
1280   // load ss_logger configuration file.
1281   getConfigInfo(cfginfo);
1282
1283
1284   if (type == SS_STORELOGS_SYS_ILLEGAL) {
1285     if (getFileNumberFromTempArchive(l_counter) != eFrameworkunifiedStatusOK) {
1286       // ------------------------------------ //
1287       // no made ILG_RESET.tar.gz             //
1288       // when is abnormal logging count over. //
1289       // ------------------------------------ //
1290       return eFrameworkunifiedStatusOK;
1291     }
1292   }
1293
1294
1295 //  Clock_getSystemTimeY2K38(&time_info, &status);
1296
1297 //  file_name = getFileName(cfginfo.output_path, time_info, type);
1298 //
1299 //  // prepare log files for collectting
1300 //  for (UI_32 i = 0; i < _countof(GetLogFuncTbl); i++) {
1301 //    GetLogFuncTbl[i](type, list);
1302 //  }
1303   file_name = getFileName(cfginfo.output_path, time_info, type, l_counter);
1304
1305   if (type != SS_STORELOGS_SYS_ILLEGAL) {
1306     // prepare log files for collectting
1307     for (UI_32 i = 0; i < _countof(GetLogFuncTbl); i++) {
1308       GetLogFuncTbl[i](type, list);
1309     }
1310   }
1311
1312   if (type == SS_STORELOGS_ACCOFFON) {
1313     copyFileToAccOffOnDir(list, type);
1314     DEB_LOGGERSERVICELOG(ZONE_FUNC, __FUNCTION__, "- : FrameworkunifiedStatus = %d", l_eFrameworkunifiedStatus);
1315     return l_eFrameworkunifiedStatus;
1316   } else if (type != SS_STORELOGS_ACCOFFON_PRESS) {
1317     // loggerservicelogList used with clear buffer
1318     getLoggerservicelogFile(type, list, loggerservicelogList);
1319   }
1320
1321   // ---------------------------------------------------------------- //
1322   // Warning!!! Logs by using FRAMEWORKUNIFIEDLOG macro, are not saved from here!! //
1323   // You can saved logs by FRAMEWORKUNIFIEDLOG after finished to clear buffer.     //
1324   // ---------------------------------------------------------------- //
1325
1326   if (list.size() != 0) {
1327     // delete old archive before create new one.
1328     deleteOldEmmcLog(cfginfo, file_name, type);
1329
1330     l_eFrameworkunifiedStatus = openArchive(&tar_info, file_name);
1331     if (l_eFrameworkunifiedStatus == eFrameworkunifiedStatusOK) {
1332       if (type == SS_STORELOGS_ACCOFFON_PRESS) {
1333         std::string collectPath;
1334         collectPath = LOGGERSERVICELOG_TMP_OUTPUT_PATH;
1335         collectPath.append("/");
1336         collectPath.append(ACCOFFON_DIR_NAME);
1337         if (0 != access(collectPath.c_str(), F_OK)) {
1338           DEB_LOGGERSERVICELOG(ZONE_ERR,__FUNCTION__," Error. The specified file path and name does not exist: %s", collectPath.c_str());
1339           l_eFrameworkunifiedStatus = eFrameworkunifiedStatusFail;
1340           return l_eFrameworkunifiedStatus;
1341         } else {
1342           l_eFrameworkunifiedStatus = addAllFileToArchive(tar_info,collectPath);
1343         }
1344       } else {
1345         for (UI_32 j = 0; j < list.size(); j++) {
1346           l_eFrameworkunifiedStatus = addToArchive(tar_info, list.at(j).file_path, list.at(j).dest_name);
1347           if(l_eFrameworkunifiedStatus != eFrameworkunifiedStatusOK) {
1348             FRAMEWORKUNIFIEDLOG(ZONE_WARN, __FUNCTION__, " Error. File %s failed to archive.", list.at(j).file_path.c_str());
1349           }
1350         }
1351       }
1352
1353 //      l_eFrameworkunifiedStatus = closeArchive(tar_info);
1354       l_eFrameworkunifiedStatus = closeArchive(tar_info, type);
1355
1356       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "finish archiving logs(%d)", type);
1357
1358       // when finish archiving, clear frameworkunifiedlog buffer.
1359       if (type == SS_STORELOGS_ACCOFFON_PRESS) {
1360         deleteTmpAccOffOn((std::string)ACCOFFON_DIR_NAME);
1361         DEB_LOGGERSERVICELOG(ZONE_FUNC, __FUNCTION__, "- : FrameworkunifiedStatus = %d", l_eFrameworkunifiedStatus);
1362         return (l_eFrameworkunifiedStatus);
1363       } else {
1364         ClearLoggerservicelogBuffer(loggerservicelogList);
1365       }
1366
1367       // create flag of archiving completed
1368       CreateSaveFinFlag(type);
1369
1370       // -------------------------------------------- //
1371       // You can save logs by FRAMEWORKUNIFIEDLOG macro from here. //
1372       // -------------------------------------------- //
1373     }
1374
1375     // remove temporary or unnecessary files.
1376     for (UI_32 k = 0; k < list.size(); k++) {
1377       if (list.at(k).tmp_file_delete == TRUE) {
1378         struct stat l_stat;
1379         if (0 != stat(list.at(k).file_path.c_str(), &l_stat)) {
1380           FRAMEWORKUNIFIEDLOG(ZONE_WARN, __FUNCTION__, "Error. stat(%s) errno. %d",
1381                  list.at(k).file_path.c_str(), errno);
1382         } else if (S_ISDIR(l_stat.st_mode)) {
1383           RemoveDirectory(list.at(k).file_path);
1384         } else {
1385           if (0 != unlink(list.at(k).file_path.c_str())) {  // LCOV_EXCL_BR_LINE 5: unlink's error case
1386             // LCOV_EXCL_START 5: unlink's error case
1387             AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1388             FRAMEWORKUNIFIEDLOG(ZONE_WARN, __FUNCTION__, " Error. unlink(%s) errno. %d",
1389                    list.at(k).file_path.c_str(), errno);
1390             // LCOV_EXCL_STOP
1391           }
1392         }
1393       }
1394     }
1395   }
1396   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "- : FrameworkunifiedStatus = %d", l_eFrameworkunifiedStatus);
1397   return (l_eFrameworkunifiedStatus);
1398 }
1399
1400 static void getCommunicationlogFile(SS_STORELOGS_OPE_TYPE type,
1401                                     std::vector<LogInfo>& list) {  // NOLINT (runtime/references)
1402
1403   LogInfo log_info;
1404
1405   log_info.file_path = FRAMEWORKUNIFIEDLOG_RAMDISC_PATH;
1406   log_info.file_path.append("/");
1407   log_info.file_path.append(COMMUNICATION_DIR_NAME);
1408   log_info.dest_name = COMMUNICATION_DIR_NAME;
1409   log_info.tmp_file_delete = FALSE;
1410   list.push_back(log_info);
1411 }
1412
1413 static void getExternallogFile(SS_STORELOGS_OPE_TYPE type,
1414                              std::vector<LogInfo>& list) {  // NOLINT (runtime/references)
1415   EFrameworkunifiedStatus l_eStatus = eFrameworkunifiedStatusOK;
1416   ExternalLogList ext_log;
1417   memset(&ext_log, 0, sizeof(&ext_log));
1418
1419   CNSConfigReader *l_pReaderCfg = new CNSConfigReader();
1420
1421   if (NULL == l_pReaderCfg) {  // LCOV_EXCL_BR_LINE 5: new's error case
1422     // LCOV_EXCL_START 5: new's error case
1423     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1424     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, " Error. Unable to allocate CNSConfigReader object.");
1425     // LCOV_EXCL_STOP
1426   } else {
1427     if (eFrameworkunifiedStatusOK != (l_eStatus = l_pReaderCfg->Parse(LOGGERSERVICELOG_CONFIG_PATH))) {
1428       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, " Error. l_pReaderCfg->Parse(%s) returned: 0x%X", LOGGERSERVICELOG_CONFIG_PATH);
1429     } else if (eFrameworkunifiedStatusOK !=
1430         (l_eStatus = l_pReaderCfg->GetInt("LOGGING.ExternalLogNum", ext_log.num))) {
1431       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, " Error. l_pReaderCfg->GetInt(LOGGING.ExternalLogNum)");
1432     } else if (eFrameworkunifiedStatusOK !=
1433         (l_eStatus = l_pReaderCfg->GetInt("LOGGING.ExternalLogMax", ext_log.max))) {
1434       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, " Error. l_pReaderCfg->GetInt(LOGGING.EmmcOutputMax)");
1435     } else {
1436       if (ext_log.num > 0) {
1437         std::string str = "EXTERNAL_";
1438         UI_32 num = 0;
1439
1440         if (ext_log.num <= ext_log.max) {
1441           num = ext_log.num;
1442         } else {
1443           num = ext_log.max;
1444         }
1445
1446         ext_log.p_info = new ExternalLogInfo[num];
1447
1448         // Load external log info
1449         for (UI_32 i = 0; i < num; i++) {
1450           std::string query = str + std::to_string(i+1);
1451           if (eFrameworkunifiedStatusOK !=
1452               (l_eStatus = l_pReaderCfg->GetString((query+".OutputPath"), ext_log.p_info[i].dirname))) {
1453             FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, " Error. l_pReaderCfg->GetString(EXTERNAL.OutputPath)");
1454           } else if (eFrameworkunifiedStatusOK !=
1455               (l_eStatus = l_pReaderCfg->GetString((query+".ExtLogPath"), ext_log.p_info[i].path))) {
1456             FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, " Error. l_pReaderCfg->GetString(EXTERNAL.ExtLogPath)");
1457           } else if (eFrameworkunifiedStatusOK !=
1458               (l_eStatus = l_pReaderCfg->GetBool((query+".Remove"), ext_log.p_info[i].remove))) {
1459             FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, " Error. l_pReaderCfg->GetBool(EXTERNAL.Remove)");
1460           } else {
1461             LogInfo log_info;
1462             log_info.file_path = ext_log.p_info[i].path;
1463             log_info.dest_name = ext_log.p_info[i].dirname;
1464             log_info.tmp_file_delete = ext_log.p_info[i].remove;
1465
1466             list.push_back(log_info);
1467           }
1468         }
1469
1470         delete[] ext_log.p_info;
1471
1472       } else {
1473         // None external log
1474       }
1475     }
1476     delete l_pReaderCfg;
1477   }
1478 }
1479
1480
1481
1482
1483 static void getLoggerservicelogFile(SS_STORELOGS_OPE_TYPE type,
1484                           std::vector<LogInfo>& list,  // NOLINT (runtime/references)
1485                           std::vector<LoggerservicelogInfo>& loggerservicelogList) {  // NOLINT (runtime/references)
1486   EFrameworkunifiedStatus l_eStatus = eFrameworkunifiedStatusOK;
1487   UI_32 l_DumpSize = 0;
1488   std::string src_file_path;
1489   std::string dst_file_path;
1490   PCSTR file_name;
1491   UI_32 file_num;
1492   LogInfo log_info;
1493   LoggerservicelogInfo loggerservicelog_info;
1494
1495   file_num = NSLogGetFrameworkunifiedlogFileTotalNum();
1496   for (UI_32 cont = 0; cont < file_num; cont++) {
1497     file_name = NSLogGetFrameworkunifiedlogFileName(cont);
1498     if (file_name == NULL) {
1499       break;
1500     }
1501     src_file_path = FRAMEWORKUNIFIEDLOG_RAMDISC_PATH;
1502     src_file_path.append("/");
1503     src_file_path.append(file_name);
1504     dst_file_path = LOGGERSERVICELOG_TMP_OUTPUT_PATH;
1505     dst_file_path.append("/");
1506     dst_file_path.append(file_name);
1507
1508     int index;
1509     index = NSLogGetFrameworkunifiedlogIndex(src_file_path.c_str());
1510     CNSRingBuffer* l_pLoggerservicelog = new (std::nothrow) CNSRingBuffer(
1511       src_file_path, 0, index + LOCK_NSLOG_ACCES_IF_1);
1512     if (l_pLoggerservicelog == NULL) {  // LCOV_EXCL_BR_LINE 5: new's error case
1513       // LCOV_EXCL_START 5: new's error case
1514       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1515       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
1516              "Error: FRAMEWORKUNIFIEDLOG RingBuffer handle is NULL %s",
1517              src_file_path.c_str());
1518       continue;
1519       // LCOV_EXCL_STOP
1520     } else if (eFrameworkunifiedStatusOK != (l_eStatus = l_pLoggerservicelog->Open())) {
1521       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
1522              "Error: FRAMEWORKUNIFIEDLOG RingBuffer Open failed %s %d",
1523              src_file_path.c_str(), l_eStatus);
1524     } else {
1525       if (eFrameworkunifiedStatusOK
1526           != (l_eStatus = l_pLoggerservicelog->DumpToFile(dst_file_path.c_str(),
1527                           &l_DumpSize))) {
1528         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
1529                "Error: FRAMEWORKUNIFIEDLOG RingBuffer DumpToFile failed %s %d",
1530                src_file_path.c_str(), l_eStatus);
1531       } else {
1532         log_info.file_path = dst_file_path;
1533         log_info.dest_name = file_name;
1534         log_info.tmp_file_delete = TRUE;
1535         list.push_back(log_info);
1536         // save frameworkunifiedlog-info for using clear frameworkunifiedlog buffer
1537         loggerservicelog_info.path = src_file_path;
1538         loggerservicelog_info.index = index;
1539         loggerservicelogList.push_back(loggerservicelog_info);
1540       }
1541       (void) l_pLoggerservicelog->Close();
1542     }
1543     delete l_pLoggerservicelog;
1544   }
1545 }
1546
1547 static void copyLoggerservicelogFile(std::string distPath)
1548 {
1549   EFrameworkunifiedStatus l_eStatus = eFrameworkunifiedStatusOK;
1550   UI_32 l_DumpSize = 0;
1551   std::string src_file_path;
1552   std::string dst_file_path;
1553   PCSTR file_name;
1554   UI_32 file_num;
1555
1556   file_num = NSLogGetFrameworkunifiedlogFileTotalNum();
1557
1558   for (UI_32 cont = 0; cont < file_num; cont++) {
1559     file_name = NSLogGetFrameworkunifiedlogFileName(cont);
1560
1561     if (file_name == NULL) {
1562       break;
1563     }
1564
1565     src_file_path = FRAMEWORKUNIFIEDLOG_RAMDISC_PATH;
1566     src_file_path.append("/");
1567     src_file_path.append(file_name);
1568
1569     dst_file_path = distPath;
1570     dst_file_path.append("/");
1571     dst_file_path.append(file_name);
1572
1573     int index;
1574     index = NSLogGetFrameworkunifiedlogIndex(src_file_path.c_str());
1575     CNSRingBuffer* l_pLoggerservicelog = new (std::nothrow)CNSRingBuffer(src_file_path,0,index+LOCK_NSLOG_ACCES_IF_1);
1576     if (l_pLoggerservicelog == NULL) {
1577       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Error: FRAMEWORKUNIFIEDLOG RingBuffer handle is NULL %s", src_file_path.c_str());
1578       continue;
1579     } else if (eFrameworkunifiedStatusOK != (l_eStatus = l_pLoggerservicelog->Open())) {
1580       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,"Error: FRAMEWORKUNIFIEDLOG RingBuffer Open failed %s %d", src_file_path.c_str(), l_eStatus);
1581     } else {
1582       if (eFrameworkunifiedStatusOK != (l_eStatus = l_pLoggerservicelog->DumpToFile(dst_file_path.c_str(), &l_DumpSize))) {
1583         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,"Error: FRAMEWORKUNIFIEDLOG RingBuffer DumpToFile failed %s %d", src_file_path.c_str(), l_eStatus);
1584       }
1585       (void)l_pLoggerservicelog->Close();
1586     }
1587     delete l_pLoggerservicelog;
1588   }
1589 }
1590
1591 static void deleteTmpAccOffOn(std::string accOffOnDir)
1592 {
1593   std::string l_tmpAccOffOnPath = LOGGERSERVICELOG_TMP_OUTPUT_PATH;
1594   l_tmpAccOffOnPath.append("/");
1595   l_tmpAccOffOnPath.append(accOffOnDir.c_str());
1596   DIR * l_pDir = opendir(l_tmpAccOffOnPath.c_str());
1597   if (l_pDir != NULL) {
1598     struct dirent l_pDirent;
1599     struct dirent* next;
1600     while (0 == readdir_r(l_pDir,&l_pDirent,&next) && next != NULL) {
1601       if ( ( 0   != strcmp( l_pDirent.d_name, "."  ) ) &&
1602       ( 0   != strcmp( l_pDirent.d_name, ".." ))  &&
1603       ( 0   != strcmp( l_pDirent.d_name, "lost+found" ))  &&
1604       ( '.' != l_pDirent.d_name[0] ) ) {
1605         std::string l_deletePath = l_tmpAccOffOnPath;
1606         l_deletePath.append("/");
1607         l_deletePath.append(l_pDirent.d_name);
1608         deleteAccOffOnUntyped(l_deletePath);
1609       }
1610     }
1611     closedir (l_pDir);
1612   }
1613   RemoveDirectory(l_tmpAccOffOnPath);
1614 }
1615
1616 static void ClearLoggerservicelogBuffer(std::vector<LoggerservicelogInfo> &loggerservicelogList) {  // NOLINT (runtime/references)
1617   EFrameworkunifiedStatus l_eStatus = eFrameworkunifiedStatusOK;
1618   std::vector<LoggerservicelogInfo>::iterator ite = loggerservicelogList.begin();
1619
1620   if (ite == loggerservicelogList.end()) {
1621     // target not found...
1622     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "nothing to clear");
1623   } else {
1624     for (ite = loggerservicelogList.begin(); ite != loggerservicelogList.end(); ite++) {
1625       CNSRingBuffer* l_pLoggerservicelog = new (std::nothrow) CNSRingBuffer(
1626         ite->path.c_str(), 0, ite->index + LOCK_NSLOG_ACCES_IF_1);
1627       if (l_pLoggerservicelog == NULL) {  // LCOV_EXCL_BR_LINE 5: new's error case
1628         // LCOV_EXCL_START 5: new's error case
1629         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1630         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
1631                "Error: FRAMEWORKUNIFIEDLOG RingBuffer handle is NULL %s", ite->path.c_str());
1632         continue;
1633         // LCOV_EXCL_STOP
1634       } else if (eFrameworkunifiedStatusOK != (l_eStatus = l_pLoggerservicelog->Open())) {
1635         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
1636                "Error: FRAMEWORKUNIFIEDLOG RingBuffer Open failed %s %d", ite->path.c_str(),
1637                l_eStatus);
1638       } else {
1639         if (eFrameworkunifiedStatusOK != (l_eStatus = l_pLoggerservicelog->ClearBuf())) {
1640           FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
1641                  "Error: FRAMEWORKUNIFIEDLOG RingBuffer ClearBuf failed %s %d",
1642                  ite->path.c_str(), l_eStatus);
1643         }
1644         (void) l_pLoggerservicelog->Close();
1645       }
1646       delete l_pLoggerservicelog;
1647     }
1648   }
1649   FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Completed");
1650   fprintf(stderr, "%s:Completed\n", __FUNCTION__);
1651 }
1652
1653 static void createKernelLog(SS_STORELOGS_KERNEL_LOG_TYPE type) {
1654   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "+");
1655   int len;
1656   int fd;
1657   char* buf;
1658   ssize_t wr_len;
1659
1660   len = klogctl(SYSLOG_ACTION_SIZE_BUFFER, NULL, 0);
1661   if (len < 0) {  // LCOV_EXCL_BR_LINE 5: klogctl's error case
1662     // LCOV_EXCL_START 5: klogctl's error case
1663     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1664     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
1665            "Error. Failed to get syslog buffer size: %d, %s", errno,
1666            strerror(errno));
1667     // LCOV_EXCL_STOP
1668   } else {
1669     buf = reinterpret_cast<char*>(malloc(len));
1670     if (buf != NULL) {  // LCOV_EXCL_BR_LINE 5: malloc's error case
1671       len = klogctl(SYSLOG_ACTION_READ_ALL, buf, len);
1672       if ((len < 0) || (len == 0)) {  // LCOV_EXCL_BR_LINE 5: klogctl's error case
1673         // LCOV_EXCL_START 5: klogctl's error case
1674         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1675         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
1676                "Error. Failed to read syslog buffer: %d, %s", errno,
1677                strerror(errno));
1678         // LCOV_EXCL_STOP
1679       } else {
1680         std::string file_put_path = "";
1681
1682         switch (type) {
1683         case SS_STORELOGS_KERNEL_LOG:
1684           file_put_path = LOGGERSERVICELOG_TMP_OUTPUT_PATH;
1685           file_put_path.append("/");
1686           file_put_path.append(KERNEL_LOG_FN);
1687           fd = open(file_put_path.c_str(),
1688                     O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
1689           break;
1690         case SS_STORELOGS_KERNEL_BOOT_LOG:
1691           file_put_path = FRAMEWORKUNIFIEDLOG_RAMDISC_PATH;
1692           file_put_path.append("/");
1693           file_put_path.append(KERNEL_BOOT_LOG_FN);
1694           fd = open(file_put_path.c_str(),
1695                     O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
1696           break;
1697         default:
1698           fd = -1;
1699           break;
1700         }
1701
1702         if (fd == -1) {
1703           FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
1704                  "Error. Failed to open file: %s: %d, %s",
1705                  file_put_path.c_str(), errno, strerror(errno));
1706         } else {
1707           wr_len = write(fd, buf, len);
1708           if (wr_len == -1) {  // LCOV_EXCL_BR_LINE 5: write's error case
1709             // LCOV_EXCL_START 5: write's error case
1710             AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1711             FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
1712                    " Error. File write failed. errno: %d, %s", errno,
1713                    strerror(errno));
1714             // LCOV_EXCL_STOP
1715           }
1716           fsync(fd);
1717           close(fd);
1718         }
1719       }
1720       free(buf);
1721     } else {
1722       // LCOV_EXCL_START 5: malloc's error case
1723       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1724       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, "Memory allocation Failed %s",
1725              strerror(errno));
1726       // LCOV_EXCL_STOP
1727     }
1728   }
1729   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
1730 }
1731
1732 static void getKernellogFile(SS_STORELOGS_OPE_TYPE type,
1733                              std::vector<LogInfo>& list) {  // NOLINT (runtime/references)
1734   getLastKernelLog(list);
1735
1736   getKernelLog(list);
1737
1738   if (type != SS_STORELOGS_ACCOFFON) {
1739     getKernelBootLog(type, list);
1740   }
1741 }
1742
1743 static void getLastKernelLog(std::vector<LogInfo>& list) {  // NOLINT (runtime/references)
1744   LogInfo log_info;
1745
1746   log_info.file_path = PSTORE_DIR_PATH;
1747   log_info.dest_name = "kernellog";
1748   log_info.tmp_file_delete = FALSE;
1749   list.push_back(log_info);
1750 }
1751
1752 static void getKernelLog(std::vector<LogInfo>& list) {  // NOLINT (runtime/references)
1753   createKernelLog(SS_STORELOGS_KERNEL_LOG);
1754
1755   LogInfo log_info;
1756
1757   std::string klog_path = LOGGERSERVICELOG_TMP_OUTPUT_PATH;
1758   klog_path.append("/");
1759   klog_path.append(KERNEL_LOG_FN);
1760
1761   if (0 == access(klog_path.c_str(), F_OK)) {
1762     log_info.file_path = klog_path;
1763     log_info.dest_name = KERNEL_LOG_FN;
1764     log_info.tmp_file_delete = TRUE;
1765     list.push_back(log_info);
1766   } else {
1767     FRAMEWORKUNIFIEDLOG(ZONE_INFO, __FUNCTION__, "Info: %s not found.", klog_path.c_str());
1768   }
1769 }
1770
1771 static void getKernelBootLog(SS_STORELOGS_OPE_TYPE type,
1772                              std::vector<LogInfo>& list) {  // NOLINT (runtime/references)
1773   createKernelLog(SS_STORELOGS_KERNEL_BOOT_LOG);
1774
1775   LogInfo log_info;
1776
1777   std::string klog_path = FRAMEWORKUNIFIEDLOG_RAMDISC_PATH;
1778   klog_path.append("/");
1779   klog_path.append(KERNEL_BOOT_LOG_FN);
1780
1781   if (0 == access(klog_path.c_str(), F_OK)) {
1782     std::string klog_out_path = LOGGERSERVICELOG_TMP_OUTPUT_PATH;
1783     klog_out_path.append("/");
1784     klog_out_path.append(KERNEL_BOOT_LOG_FN);
1785
1786     if (eFrameworkunifiedStatusOK == copyFile(klog_path.c_str(), klog_out_path.c_str())) {  // LCOV_EXCL_BR_LINE 6: copyFile must return ok  // NOLINT[whitespace/line_length]
1787       log_info.file_path = klog_out_path;
1788       log_info.dest_name = KERNEL_BOOT_LOG_FN;
1789       log_info.tmp_file_delete = TRUE;
1790       list.push_back(log_info);
1791     } else {
1792       // LCOV_EXCL_START 6: copyFile must return ok
1793       AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1794       FRAMEWORKUNIFIEDLOG(ZONE_INFO, __FUNCTION__, "Info: copyFile src:%s dest:%s failed.",
1795              klog_path.c_str(), klog_out_path.c_str());
1796       // LCOV_EXCL_STOP
1797     }
1798   } else {
1799     FRAMEWORKUNIFIEDLOG(ZONE_INFO, __FUNCTION__, "Info: %s not found.", klog_path.c_str());
1800   }
1801 }
1802
1803
1804 //static std::string getFileName(std::string &path, uint32_t f_time,  // NOLINT (runtime/references)
1805 //                               SS_STORELOGS_OPE_TYPE type) {
1806 static std::string getFileName(std::string &path, uint32_t f_time,
1807                                SS_STORELOGS_OPE_TYPE type, UI_32 l_counter) {
1808
1809   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "+");
1810   std::stringstream l_nameStream;
1811
1812 //  UI_32 l_counter = 0;
1813   std::string l_time_str = "00000000_000000";
1814   std::string l_ret;
1815   char buffer[20];
1816   struct tm l_time_tmp;
1817
1818
1819 //  getEmmcCounter(path, l_counter);
1820   if (l_counter == INVALID_FILENUMBER) {
1821     l_counter = 0;
1822     getEmmcCounter(path, l_counter);
1823   }
1824
1825
1826 //  CLOCK_RETURN clock_ret = Clock_getLocalTimeY2K38(&f_time, &l_time_tmp);
1827 //  if (clock_ret == CLOCK_OK) {
1828 //    if (0 != strftime(buffer, sizeof(buffer), "%Y%m%d_%H%M%S", &l_time_tmp)) {
1829 //      l_time_str = buffer;
1830 //    }
1831 //  }
1832
1833 //  l_nameStream << std::setw(5) << std::setfill('0') << std::right << std::dec
1834 //               << l_counter << '_';
1835   l_nameStream << std::setw(FILENUMBER_DIGIT_NUM) << std::setfill('0') << std::right << std::dec
1836                << l_counter << '_';
1837
1838
1839   switch (type) {
1840   case SS_STORELOGS_ILLEGAL:
1841     l_nameStream << std::setw(15) << l_time_str << "_ILG_RESET.tar.gz";
1842     break;
1843   case SS_STORELOGS_INTERFACEUNIFIEDLOG:
1844     l_nameStream << std::setw(15) << l_time_str << "_ACCOFF.tar.gz";
1845     break;
1846   case SS_STORELOGS_ACCOFFON:
1847   case SS_STORELOGS_ACCOFFON_PRESS:
1848     l_nameStream << std::setw(15) << l_time_str << "_ACCOFFON.tar.gz";
1849     break;
1850
1851   case SS_STORELOGS_SYS_ILLEGAL:
1852     l_nameStream << std::setw(15) << l_time_str << SS_STORE_FILENAME_SYSILG_TERM;
1853     break;
1854
1855   default:
1856     //Set the file name as usual for cases other than the anomaly log specification.
1857     l_nameStream << std::setw(15) << l_time_str << ".tar.gz";
1858     break;
1859   }
1860
1861   l_ret = path;
1862   l_ret.append("/");
1863   l_ret.append(l_nameStream.str());
1864
1865   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
1866   return (l_ret);
1867 }
1868
1869 static void getEmmcCounter(std::string &path, UI_32& f_counter) {  // NOLINT (runtime/references)
1870   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "+");
1871   std::string l_checkFileName;
1872   std::vector<UI_32> l_vector;
1873   DIR *l_dirp;
1874   struct dirent *l_direntp;
1875   size_t l_pos;
1876   UI_32 l_count;
1877   UI_32 l_maxCount = 0;
1878
1879   l_dirp = opendir(path.c_str());
1880   if (l_dirp != NULL) {
1881     for (;;) {
1882       l_direntp = readdir(l_dirp);
1883       if (l_direntp == NULL) {
1884         break;
1885       }
1886       l_checkFileName = l_direntp->d_name;
1887       l_pos = l_checkFileName.find(".tar.gz");
1888       if (std::string::npos != l_pos) {
1889         l_pos = l_checkFileName.find("_");
1890         if (std::string::npos != l_pos) {
1891           std::string l_numberString = l_checkFileName.substr(0, l_pos);
1892           l_count = static_cast<UI_32>(strtoul(l_numberString.c_str(), NULL, 10));
1893           l_vector.push_back(l_count);
1894           l_maxCount = std::max(l_count, l_maxCount);
1895         }
1896       }
1897     }
1898     closedir(l_dirp);
1899   }
1900   l_maxCount++;
1901
1902 //  if (l_maxCount >= 100000u) {
1903 //    l_maxCount = 1;
1904   if (l_maxCount >= FILENUMBER_UPPER_LIMIT_OVER) {
1905     l_maxCount = FILENUMBER_LOWER_LIMIT;
1906
1907     for (;;) {
1908       std::vector<UI_32>::iterator find_itr = std::find(l_vector.begin(),
1909                                               l_vector.end(),
1910                                               l_maxCount);
1911       if (find_itr == l_vector.end()) {
1912         break;
1913       }
1914       l_maxCount++;
1915     }
1916   }
1917   f_counter = l_maxCount;
1918   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
1919 }
1920
1921 static void getConfigInfo(CfgInfo& f_cfginfo) {  // NOLINT (runtime/references)
1922   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "+");
1923   EFrameworkunifiedStatus l_eStatus;
1924
1925   f_cfginfo.output_path = "";
1926   f_cfginfo.output_max = 0;
1927
1928   CNSConfigReader *l_pReaderCfg = new CNSConfigReader();
1929
1930   if (NULL == l_pReaderCfg) {  // LCOV_EXCL_BR_LINE 5: new's error case
1931     // LCOV_EXCL_START 5: new's error case
1932     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1933     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
1934            " Error. Unable to allocate CNSConfigReader object.");
1935     // LCOV_EXCL_STOP
1936   } else {
1937     if (eFrameworkunifiedStatusOK != (l_eStatus = l_pReaderCfg->Parse(LOGGERSERVICELOG_CONFIG_PATH))) {
1938       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
1939              " Error. l_pReaderCfg->Parse(%s) returned: 0x%X",
1940              LOGGERSERVICELOG_CONFIG_PATH, l_eStatus);
1941     } else if (eFrameworkunifiedStatusOK
1942                != (l_eStatus = l_pReaderCfg->GetString("LOGGING.EmmcOutputPath",
1943                                f_cfginfo.output_path))) {
1944       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
1945              " Error. l_pReaderCfg->GetString(LOGGING.EmmcOutputPath)");
1946     } else if (eFrameworkunifiedStatusOK
1947                != (l_eStatus = l_pReaderCfg->GetInt("LOGGING.EmmcOutputMax",
1948                                f_cfginfo.output_max))) {
1949       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
1950              " Error. l_pReaderCfg->GetInt(LOGGING.EmmcOutputMax)");
1951     } else if (eFrameworkunifiedStatusOK
1952                != (l_eStatus = l_pReaderCfg->GetInt("LOGGING.EmmcOutputErrMax",
1953                                f_cfginfo.output_errmax))) {
1954       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__,
1955              " Error. l_pReaderCfg->GetInt(LOGGING.EmmcOutputErrMax)");
1956     }
1957     delete l_pReaderCfg;
1958   }
1959   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
1960 }
1961
1962 static EFrameworkunifiedStatus deleteOldLog(std::string log_path,
1963                                std::vector<std::string>& l_vector,  // NOLINT (runtime/references)
1964                                std::string& f_archive_destination,  // NOLINT (runtime/references)
1965                                UI_32 max_num) {
1966   EFrameworkunifiedStatus l_eStatus = eFrameworkunifiedStatusOK;
1967
1968   size_t l_pos = f_archive_destination.find_last_of('/');
1969
1970   if (std::string::npos != l_pos) {  // LCOV_EXCL_BR_LINE 6: '/' must exist in f_archive_destination
1971     std::sort(l_vector.begin(), l_vector.end());
1972     std::vector<std::string>::iterator itr = l_vector.begin();
1973     for (UI_32 i = static_cast<UI_32>(l_vector.size()); (max_num - 1) < i; i--, itr++) {
1974       if (itr == l_vector.end()) {  // LCOV_EXCL_BR_LINE 6: itr can't be l_vector.end()
1975         // LCOV_EXCL_START 6: itr can't be l_vector.end()
1976         AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1977         break;
1978         // LCOV_EXCL_STOP
1979       }
1980       std::string l_FilePath = log_path;
1981       std::string l_FileName = *itr;
1982       l_FilePath.append("/");
1983       l_FilePath.append(l_FileName.c_str());
1984       if (0 != unlink(l_FilePath.c_str())) {
1985         l_eStatus = eFrameworkunifiedStatusAccessError;
1986         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, " Error. delete old log file %s:%d.",
1987                l_FilePath.c_str(), errno);
1988       }
1989     }
1990     SyncDir(log_path);
1991   } else {
1992     // LCOV_EXCL_START 6: '/' must exist in f_archive_destination
1993     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
1994     l_eStatus = eFrameworkunifiedStatusFail;
1995     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, " Error. delete target not found. %s",
1996            f_archive_destination.c_str());
1997     // LCOV_EXCL_STOP
1998   }
1999   return l_eStatus;
2000 }
2001
2002
2003 static EFrameworkunifiedStatus getFileNumber(const std::string &filename,UI_32 &number) {
2004   char buf[16];
2005   size_t pos;
2006   size_t offset;
2007   size_t length;
2008   UI_32 temp_value;
2009
2010   offset = filename.find_last_of(PATHNAME_SEPARATOR) + 1;
2011   pos = filename.find_first_of('_', offset);
2012   length = pos-offset;
2013   if (std::string::npos == pos) {
2014     return eFrameworkunifiedStatusInvldParam;
2015   } else if (sizeof(buf) <= length) {
2016     return eFrameworkunifiedStatusInvldParam;
2017   }
2018
2019   char *endptr;
2020   int  error_number;
2021
2022   memcpy(buf, filename.c_str() + offset, length);
2023   buf[length]  = '\x0';
2024
2025   errno = EOK;
2026   temp_value = strtol(buf, &endptr, 10);
2027   error_number = errno;
2028   if ((error_number != EOK) || (*endptr != '\x0')) {
2029     return eFrameworkunifiedStatusInvldParam;
2030   }
2031   number = temp_value;
2032   return eFrameworkunifiedStatusOK;
2033 }
2034
2035 static bool compareFileNumber(UI_32 filename1_number, const std::string &filename2) {
2036   EFrameworkunifiedStatus l_eStatus;
2037   bool       result;
2038   UI_32      filename2_number;
2039
2040   l_eStatus = getFileNumber(filename2, filename2_number);
2041   if (l_eStatus != eFrameworkunifiedStatusOK) {
2042     return false;
2043   }
2044   result = (filename1_number == filename2_number);
2045   return result;
2046 }
2047
2048 static EFrameworkunifiedStatus removeFiles(const std::string &log_path, std::vector<std::string> &l_vector,
2049                               size_t begin_pos, size_t end_pos) {
2050   std::string l_FilePath;
2051   size_t      i;
2052   int         result;
2053   EFrameworkunifiedStatus  l_eStatus     = eFrameworkunifiedStatusOK;
2054   EFrameworkunifiedStatus  l_ePartStatus = eFrameworkunifiedStatusOK;
2055   l_FilePath.reserve(SSLOGGER_PATHNAME);
2056   for (i = begin_pos; i < end_pos; i++) {
2057     l_FilePath = log_path + PATHNAME_SEPARATOR_STR + l_vector[i];
2058     result     = unlink(l_FilePath.c_str());
2059     if (0 != result) {
2060       FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, " Error. unlink() filename = %s ,errno = %d.", l_FilePath.c_str(), errno);
2061       l_ePartStatus  = eFrameworkunifiedStatusAccessError;
2062       if (l_ePartStatus != eFrameworkunifiedStatusOK) {
2063         l_eStatus  = l_ePartStatus;
2064       }
2065     }
2066   }
2067   return l_eStatus;
2068 }
2069
2070 static EFrameworkunifiedStatus removeSameNumFiles(std::vector<std::string>::iterator &itr, const std::string &log_path,
2071                                      std::vector<std::string> &l_vector) {
2072   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "+");
2073   if (l_vector.begin() == itr) {  // LCOV_EXCL_BR_LINE 4: itr is l_vector.begin() only when no space error case
2074     // LCOV_EXCL_START 4: itr is l_vector.begin() only when no space error case
2075     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
2076     FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
2077     return eFrameworkunifiedStatusOK;
2078     // LCOV_EXCL_STOP
2079   }
2080   std::string &removed_filename  = *(itr - 1);
2081   UI_32        removed_filenumber;
2082   if (getFileNumber(removed_filename, removed_filenumber) != eFrameworkunifiedStatusOK) {  // LCOV_EXCL_BR_LINE 6: double check, must return ok  // NOLINT[whitespace/line_length]
2083     // LCOV_EXCL_START 6: double check, must return ok
2084     AGL_ASSERT_NOT_TESTED();  // LCOV_EXCL_LINE 200: test assert
2085     FRAMEWORKUNIFIEDLOG(ZONE_WARN, __FUNCTION__, " Warning. Type mismatch filename. = %s", removed_filename.c_str());
2086     return eFrameworkunifiedStatusOK;
2087     // LCOV_EXCL_STOP
2088   }
2089
2090   std::string l_FilePath;
2091   EFrameworkunifiedStatus  l_ePartStatus  = eFrameworkunifiedStatusOK;
2092   EFrameworkunifiedStatus  l_eStatus    = eFrameworkunifiedStatusOK;
2093   int         result;
2094   for (;itr < l_vector.end(); itr++) {
2095     const std::string &exist_filename = (*itr);
2096     if (compareFileNumber(removed_filenumber, exist_filename) == true) {
2097       l_FilePath = log_path + PATHNAME_SEPARATOR_STR + exist_filename;
2098       FRAMEWORKUNIFIEDLOG(ZONE_INFO, __FUNCTION__, " Remove file = %s.", l_FilePath.c_str());
2099       result = unlink(l_FilePath.c_str());
2100       if (0 != result) {
2101         FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, " Error. unlink() filename = %s , errno = %d.", l_FilePath.c_str(), errno);
2102         l_ePartStatus = eFrameworkunifiedStatusAccessError;
2103         if (l_ePartStatus != eFrameworkunifiedStatusOK) {
2104           l_eStatus  = l_ePartStatus;
2105         }
2106       }
2107     } else {
2108       break;
2109     }
2110   }
2111   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
2112   return l_eStatus;
2113 }
2114
2115 static EFrameworkunifiedStatus deleteOldLogAbnrm(const std::string& log_path, std::vector<std::string>& l_vector,
2116                                     const std::string& f_archive_destination, SI_32 max_num, UI_32 abnrm_total) {
2117   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "+");
2118   size_t l_pos = f_archive_destination.find_last_of(PATHNAME_SEPARATOR);
2119   if (std::string::npos == l_pos) {
2120     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, " Error. delete target not found. %s", f_archive_destination.c_str());
2121     return eFrameworkunifiedStatusFail;
2122   }
2123   if (l_vector.size() == 0) {
2124     FRAMEWORKUNIFIEDLOG(ZONE_ERR, __FUNCTION__, " Error. empty array.");
2125     return eFrameworkunifiedStatusFail;
2126   }
2127   //FRAMEWORKUNIFIEDLOG(ZONE_INFO, __FUNCTION__, " max_num = %d , vect_abnrm.size() = %d", max_num, vect_abnrm.size());
2128
2129   size_t       i;
2130   EFrameworkunifiedStatus   l_ePartStatus = eFrameworkunifiedStatusOK;
2131   EFrameworkunifiedStatus   l_eStatus     = eFrameworkunifiedStatusOK;
2132   size_t       end_pos       = l_vector.size();
2133   SI_32        abnrm_count   = 0;
2134   UI_32        exist_filenumber;
2135   ELOGGERSERVICELOGTYPE  filetype;
2136
2137   max_num = abnrm_total - max_num + 1;
2138   std::sort(l_vector.begin(), l_vector.end());
2139   for (i = 0; i < end_pos; i++) {
2140     const std::string &exist_filename = l_vector[i];
2141     if (getFileNumber(exist_filename, exist_filenumber) != eFrameworkunifiedStatusOK) {
2142       continue;
2143     }
2144     filetype = QueryLoggerservicelogType(exist_filename);
2145     if (filetype == eLoggerservicelogTypeAbnormal) {
2146       abnrm_count++;
2147       if (max_num <= abnrm_count) {
2148         end_pos  = i + 1;
2149         break;
2150       }
2151     }
2152   }
2153   l_ePartStatus = removeFiles(log_path, l_vector, 0, end_pos);
2154   if (l_ePartStatus != eFrameworkunifiedStatusOK) {
2155     l_eStatus  = l_ePartStatus;
2156   }
2157   if (end_pos < l_vector.size()) {
2158     std::vector<std::string>::iterator itr = l_vector.begin() + end_pos;
2159     l_ePartStatus = removeSameNumFiles(itr, log_path, l_vector);
2160     if (l_ePartStatus != eFrameworkunifiedStatusOK) {
2161       l_eStatus  = l_ePartStatus;
2162     }
2163   }
2164   SyncDir(log_path);
2165   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
2166   return l_eStatus;
2167 }
2168
2169
2170 static EFrameworkunifiedStatus deleteOldEmmcLog(CfgInfo& f_cfginfo,  // NOLINT (runtime/references)
2171                                    std::string& f_archive_destination,  // NOLINT (runtime/references)
2172                                    SS_STORELOGS_OPE_TYPE type) {
2173   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "+");
2174   DIR *l_dirp = NULL;
2175   struct dirent *l_direntp = NULL;
2176   std::vector<std::string> vect_abnrm;
2177   std::vector<std::string> vect_nrm;
2178   std::vector<std::string> vect_rlnc;
2179   std::string l_emmc_path = f_cfginfo.output_path;
2180   EFrameworkunifiedStatus l_eStatus = eFrameworkunifiedStatusOK;
2181
2182   UI_32         abnrm_count = 0;
2183
2184   if (SS_STORELOGS_SYS_ILLEGAL == type) {
2185     FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
2186     return eFrameworkunifiedStatusOK;
2187   }
2188
2189
2190   l_dirp = opendir(l_emmc_path.c_str());
2191   if (l_dirp != NULL) {
2192     while ((l_direntp = readdir(l_dirp)) != NULL) {
2193       std::string l_findFileName = l_direntp->d_name;
2194
2195 //      if ((std::string::npos != l_findFileName.find("_ILG_RESET.tar.gz"))
2196 //          || (std::string::npos != l_findFileName.find("_ERR.tar.gz"))) {
2197       if ((l_findFileName == ".") || (l_findFileName == "..")) {
2198         continue;
2199       } else if (std::string::npos != l_findFileName.find(SS_STORE_FILENAME_SYSILG_TERM)) {
2200         vect_abnrm.push_back(l_findFileName);
2201       } else if (std::string::npos != l_findFileName.find(SS_STORE_FILENAME__CWORD52__TERM)) {
2202         vect_abnrm.push_back(l_findFileName);
2203       } else if((std::string::npos != l_findFileName.find("_ILG_RESET.tar.gz")) ||
2204                 (std::string::npos != l_findFileName.find("_ERR.tar.gz"))) {
2205
2206         vect_abnrm.push_back(l_findFileName);
2207
2208         abnrm_count++;
2209
2210       } else if (std::string::npos
2211                  != l_findFileName.find("_GRP_RELAUNCH.tar.gz")) {
2212         vect_rlnc.push_back(l_findFileName);
2213       } else if (std::string::npos != l_findFileName.find(".tar.gz")) {
2214         vect_nrm.push_back(l_findFileName);
2215       }
2216     }
2217     closedir(l_dirp);
2218   }
2219
2220   if (SS_STORELOGS_ILLEGAL == type) {
2221     if ((UI_32) f_cfginfo.output_errmax <= vect_abnrm.size()) {
2222       l_eStatus = deleteOldLog(l_emmc_path, vect_abnrm, f_archive_destination,
2223                                (UI_32) f_cfginfo.output_errmax);
2224     }
2225   } else {
2226     if ((UI_32) f_cfginfo.output_max <= vect_nrm.size()) {
2227       l_eStatus = deleteOldLog(l_emmc_path, vect_nrm, f_archive_destination,
2228                                (UI_32) f_cfginfo.output_max);
2229     }
2230   }
2231   FRAMEWORKUNIFIEDLOG(ZONE_FUNC, __FUNCTION__, "-");
2232   return l_eStatus;
2233 }