summaryrefslogtreecommitdiff
path: root/src/setup_system.c
blob: e41da0bf8733156ccf22ae849733075348d07915 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
/*
 * Copyright (c) 2016-2017 Samsung Electronics Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/inotify.h>
#include <sys/stat.h>
#include <dirent.h>

#include <fcntl.h>
#include <json.h>
#include <errno.h>

#include "sa_common.h"
#include "sa_types.h"
#include "input_file.h"
#include "setup_system.h"
#include "adaptor_setting.h"
#include "adaptor_util.h"

#include <sys/statvfs.h>
#include <mntent.h>				/* for getmntent(), et al. */

#define DEFAULT_FILE_SYSTEM_PATH	"/etc/mtab"	/* mounted file system */
#define STR_VALUE_LEN	10

#define ENVIRONMENT_PROXY_FILE "/opt/beluga/system/env/environment"
#define CONFIG_DOCKERD_DAEMON_FILE "/etc/docker/daemon.json"
#define CONFIG_DOCKERD_FOLDER "/etc/docker"

#define STR_HTTP_PROXY			"HTTP_PROXY"
#define STR_HTTPS_PROXY			"HTTPS_PROXY"
#define STR_OPERATOR			"="
#define STR_CARRIAGERETURN		"\r\n"

#define DOCKERD_RESTART_CMD		"systemctl restart beluga-launcher"
#define DOCKERD_STOP_CMD		"systemctl stop beluga-launcher"

#define SYSTEM_CERT_FILE "/opt/var/lib/ca-certificates/ca-bundle.pem"
#define USER_CERT_DIR_PATH "/opt/beluga/setup-adaptor/cert/"
#define EXCLUDE_WORD_IN_CERT "CERTIFICATE"

#define MAXLINE		1024
#define GET_BELUGA_VERSION_CMD		"source /opt/beluga/system/release/beluga-release && echo $VERSION"
#define GET_BASEOS_VERSION_CMD		"source /etc/os-release && echo $NAME-$VERSION"
#define GET_DOCKER_VERSION_CMD		"docker version --format '{{.Server.Version}}'"
#define DEVICE_REBOOT_CMD		"sleep 5 && reboot"

#define DOCKER_NETWORK_REMOVE_CMD			"/usr/bin/docker network rm $(docker network ls -q) && sleep 1"
#define DOCKER_SERVICES_REMOVE_CMD			"/usr/bin/docker service rm $(docker service ls -q) && sleep 1"
#define DOCKER_CONTAINERS_REMOVE_CMD		"/usr/bin/docker rm -f $(docker ps -a -q) && sleep 1"
#define DOCKER_IMAGES_REMOVE_CMD			"/usr/bin/docker rmi -f $(docker images -q) && sleep 1"
#define DOCKER_SYSTEM_PRUNE_CMD				"/usr/bin/docker system prune --all --force --volumes && sleep 1"

#define DOCKER_DIRECTORY_PATH			"/opt/beluga/var/lib/docker/"
#define USER_CONTAINER_VOLUME_PATH		"/opt/beluga/uc/"
#define FACTORY_INIT_FLAG_FILE			"/opt/beluga/system/env/factory_init.json"

static int __create_dockerd_opt(sa_dockerd_opt_s * opt, char **value)
{
	json_object *registryObj = NULL;
	json_object *arrayObj = NULL;
	json_object *jString = NULL;
	char *buf = NULL;
	int ulIndex = 0;
	int buf_len = 0;
	char *ret_buf = NULL;

	registryObj = json_object_new_object();
	arrayObj = json_object_new_array();

	if (opt->count > 0) {
		if (registryObj != NULL && arrayObj != NULL) {
			for (ulIndex = 0; ulIndex < opt->count; ulIndex++) {
				// string add in arrayObj
				/*Creating json strings */
				if (strlen(opt->insecureRegistries[ulIndex]) > 0) {
					jString = json_object_new_string(opt->insecureRegistries[ulIndex]);
					if (arrayObj != NULL)
						json_object_array_add(arrayObj, jString);
				}
			}
			json_object_object_add(registryObj, "insecure-registries", arrayObj);

			buf = json_object_to_json_string_ext(registryObj, JSON_C_TO_STRING_SPACED | JSON_C_TO_STRING_PRETTY);

			if (buf != NULL) {
				buf_len = strlen(buf) + 1;
				ret_buf = (char *)malloc(buf_len);
				if (ret_buf != NULL) {
					snprintf(ret_buf, buf_len, "%s", buf);
					//_D("create json:[%s]", ret_buf);
				}
				*value = ret_buf;
			}
		} else
			_D("empty object is not created");
	}

	if (registryObj != NULL)
		json_object_put(registryObj);

	return buf_len;
}

static sa_error_e sa_inputfile_set_proxy_env(sa_proxy_s * proxy)
{
	int fd = 0;
	int len = 0;
	sa_error_e ret = SA_ERROR_NONE;
	char additionalBuff[256] = { 0, };
	char writeBuff[512] = { 0, };

	if (proxy == NULL) {
		_E("input parameter is null");
		return SA_ERROR_INVALID_PARAMETER;
	}
	// make string for httpProxy
	if (strlen(proxy->httpProxy) > 0) {
		if (strlen(proxy->httpProxy) < (sizeof(proxy->httpProxy) - 1)) {
			_D("copy http proxy buffer");
			snprintf(writeBuff, strlen(STR_HTTP_PROXY) + strlen(STR_OPERATOR) + strlen(proxy->httpProxy) + 1, "%s%s%s", STR_HTTP_PROXY, STR_OPERATOR, proxy->httpProxy);
		} else {
			ret = SA_ERROR_NOT_AVAILABLE;
			_E("Not available to set due to buffer overflow");
		}
	} else {
		_D("there is no httpProxy input");
		snprintf(writeBuff, strlen(STR_HTTP_PROXY) + strlen(STR_OPERATOR) + 1, "%s%s", STR_HTTP_PROXY, STR_OPERATOR);
	}

	// make string for httpsProxy
	if (ret == SA_ERROR_NONE) {
		if (strlen(proxy->httpsProxy) > 0) {
			if (strlen(proxy->httpsProxy) < (sizeof(proxy->httpsProxy) - 1)) {
				_D("copy https proxy buffer");
				snprintf(additionalBuff, strlen(STR_CARRIAGERETURN) + strlen(STR_HTTPS_PROXY) + strlen(STR_OPERATOR) + strlen(proxy->httpsProxy) + 1, "%s%s%s%s", STR_CARRIAGERETURN, STR_HTTPS_PROXY, STR_OPERATOR, proxy->httpsProxy);
			} else {
				ret = SA_ERROR_NOT_AVAILABLE;
				_E("Not available to set due to buffer overflow");
			}
		} else {
			_D("there is no httpsProxy input");
			snprintf(additionalBuff, strlen(STR_CARRIAGERETURN) + strlen(STR_HTTPS_PROXY) + strlen(STR_OPERATOR) + 1, "%s%s%s", STR_CARRIAGERETURN, STR_HTTPS_PROXY, STR_OPERATOR);
		}
		// strcat httpProxy and httpsProxy
		strncat(writeBuff, additionalBuff, sizeof(writeBuff) - strlen(writeBuff) - 1);
	}
	//write data into file
	if (ret == SA_ERROR_NONE) {
		_D("write proxy buffer[%s][%d] to file{%s}", writeBuff, strlen(writeBuff), ENVIRONMENT_PROXY_FILE);
		fd = open(ENVIRONMENT_PROXY_FILE, O_WRONLY | O_CREAT | O_TRUNC, 0644);
		if (fd > 0) {
			write(fd, writeBuff, strlen(writeBuff));
		} else {
			ret = SA_ERROR_NOT_AVAILABLE;
			_E("Cannot open file");
		}
		close(fd);
	}

	return ret;
}

static sa_error_e sa_inputfile_remove_proxy_env(void)
{
	sa_error_e ret = SA_ERROR_NONE;

	if (sa_inputfile_is_file_exist(ENVIRONMENT_PROXY_FILE) == SA_FILE_STATE_EXIST) {
		if (remove(ENVIRONMENT_PROXY_FILE) != 0) {
			_D("Error!!! remove [%s] file", ENVIRONMENT_PROXY_FILE);
			ret = SA_ERROR_UNKNOWN;
		}
	}
	return ret;
}

static int __remove_factory_init_flag(void)
{
	sa_error_e ret = SA_ERROR_NONE;

	if (sa_inputfile_is_file_exist(FACTORY_INIT_FLAG_FILE) == SA_FILE_STATE_EXIST) {
		if (remove(FACTORY_INIT_FLAG_FILE) != 0) {
			_D("Error!!! remove [%s] file", FACTORY_INIT_FLAG_FILE);
			ret = SA_ERROR_UNKNOWN;
		}
	}
	return ret;
}

static sa_error_e sa_inputfile_set_dockerd_opt(sa_dockerd_opt_s * opt)
{
	int fd = 0;
	int buf_len = 0;
	sa_error_e ret = SA_ERROR_NONE;
	struct stat sb = { 0, };
	char *buf = NULL;

	if (opt == NULL) {
		_E("input parameter is null");
		return SA_ERROR_INVALID_PARAMETER;
	}
	// make string to write in daemon.json
	buf_len = __create_dockerd_opt(opt, &buf);
	if ((buf_len > 0) && (buf != NULL)) {
		// check folder
		if (stat(CONFIG_DOCKERD_FOLDER, &sb) == -1) {
			_D("/etc/docker Folder Create");
			if (mkdir(CONFIG_DOCKERD_FOLDER, 0644) != 0)
				_E("unable to mkdir; %s", CONFIG_DOCKERD_FOLDER);
		}
		//write data into file
		fd = creat(CONFIG_DOCKERD_DAEMON_FILE, 0644);
		if (fd > 0) {
			write(fd, buf, strlen(buf));
		} else {
			ret = SA_ERROR_NOT_AVAILABLE;
			_E("Cannot create file");
		}
		close(fd);

		if (buf != NULL)
			free(buf);
	}

	return ret;
}

static sa_error_e sa_inputfile_remove_dockerd_opt(void)
{
	sa_error_e ret = SA_ERROR_NONE;

	if (sa_inputfile_is_file_exist(CONFIG_DOCKERD_DAEMON_FILE) == SA_FILE_STATE_EXIST) {
		if (remove(CONFIG_DOCKERD_DAEMON_FILE) != 0) {
			_D("Error!!! remove [%s] file", CONFIG_DOCKERD_DAEMON_FILE);
			ret = SA_ERROR_UNKNOWN;
		}
	}
	return ret;
}

/**
 * @fn        static int restart_dockerd(void)
 * @brief     This function to restart docker daemon
 * @return    int    return of function
 */
static int restart_dockerd(void)
{
	int ret = 0;

	_D("docker daemon restart ~~~~~~~~~~~~~~~~~~~");
	// restart dockzen-launcher.service to apply the modified setting value.
	ret = send_message_to_launcher(SA_RESTART_DOCKERD);

	return ret;
}

static int stop_dockerd(void)
{
	int ret = 0;

	_D("docker daemon stop ~~~~~~~~~~~~~~~~~~~");
	ret = send_message_to_launcher(SA_STOP_DOCKERD);

	return ret;
}

int __apply_ca_cert_file(char *fileName)
{
	int c;
	FILE *destCert, *sourCert;

	if (access(fileName, F_OK) != 0) {
		_D("there is no user certificate file, skip applying user cert");
		return -1;
	}
	if (access(SYSTEM_CERT_FILE, F_OK) != 0) {
		_D("there is no system certificate, need to be installed ca-certificates package");
		return -1;
	}

	if ((sourCert = fopen(fileName, "r")) == NULL) {
		_D("file [%s] open error", fileName);
		return -2;
	}
	if ((destCert = fopen(SYSTEM_CERT_FILE, "a")) == NULL) {
		_D("file [%s] open error", SYSTEM_CERT_FILE);
		fclose(sourCert);
		return -2;
	}

	putc('\n', destCert);
	while ((c = getc(sourCert)) != EOF)
		putc(c, destCert);
	fclose(destCert);
	fclose(sourCert);
	return 0;
}

int __get_file_extension(char *file_name, char **fileExt)
{
	int len = 0;
	char *ptr = NULL;
	char *ret_buf = NULL;

	if (!strchr(file_name, '.') || strlen(file_name) < 3)
		return -1;

	ptr = strchr(file_name, '.');
	if (ptr != NULL) {
		len = strlen(ptr);
		ret_buf = (char *)malloc(len + 1);
		if (ret_buf != NULL) {
			strncpy(ret_buf, ptr + 1, len);
			ret_buf[len] = '\0';
			*fileExt = ret_buf;
		} else {
			_E("malloc fail !!");
		}
	}
	return 0;
}

int __search_str_pattern(char *destFileName, char *sourFileName)
{
	char grepCmd[256] = { 0, };

	snprintf(grepCmd, sizeof(grepCmd), "grep --file=%s %s | grep --invert-match %s --count", sourFileName, destFileName, EXCLUDE_WORD_IN_CERT);
	return system(grepCmd);
}

void setup_user_certificates(void)
{
	DIR *dir_info;
	struct dirent *dir_entry;
	char file_name[128];
	char *fileExt = NULL;

	dir_info = opendir(USER_CERT_DIR_PATH);
	if (dir_info != NULL) {
		while (dir_entry = readdir(dir_info)) {
			if (__get_file_extension(dir_entry->d_name, &fileExt) == 0) {
				if (fileExt != NULL) {
					if (strncmp(fileExt, "crt", 3) == 0) {
						snprintf(file_name, sizeof(file_name), "%s%s", USER_CERT_DIR_PATH, dir_entry->d_name);
						if (__search_str_pattern(SYSTEM_CERT_FILE, file_name) != 0) {	// un-matched file, need to be applied
							if (__apply_ca_cert_file(file_name) != 0)
								_D("File[%s]: apply error!!!", dir_entry->d_name);
							else
								_D("File[%s]: applied successfully ca-certificate!!!", dir_entry->d_name);
						} else {
							_D("FILE[%s]: already applied!!!", dir_entry->d_name);
						}
					}
					free(fileExt);
					fileExt = NULL;
				}
			} else
				_D("File[%s]: Not valid certificate file", dir_entry->d_name);
		}
		closedir(dir_info);
	}
}

sa_error_e sa_setup_system(sa_system_s * system, int flagInitialized)
{
	sa_error_e ret = SA_ERROR_NONE;
	int flagRestart = 0;

	if (system == NULL) {
		_E("__set_system is null");
		return SA_ERROR_INVALID_PARAMETER;
	}

	if (system->proxy != NULL) {
		ret = sa_inputfile_set_proxy_env(system->proxy);
		if (ret == SA_ERROR_NONE)
			flagRestart = 1;
	} else
		_D("skip proxy setting~~~");

	if (system->dockerdOpt != NULL) {
		ret = sa_inputfile_set_dockerd_opt(system->dockerdOpt);
		if (ret == SA_ERROR_NONE)
			flagRestart = 1;
	} else
		_D("skip dockerd option setting~~~");

	if (flagRestart && flagInitialized)
		restart_dockerd();
	return ret;
}

//////////////////////////////////////////////////////
// for device api functions
//////////////////////////////////////////////////////

void *__device_reboot_cmd_loop(void *pv)
{
	int ret = 0;

	ret = CLI_command(DEVICE_REBOOT_CMD, 0, NULL);

	return (void *)NULL;
}

int sa_device_reboot()
{
	int ret = 0;
	pthread_t thread;

	_D("docker daemon restart ~~~~~~~~~~~~~~~~~~~");
	if (pthread_create(&thread, NULL, &__device_reboot_cmd_loop, (void *)NULL)
		< 0) {
		_D("thread create error");
		ret = -1;
	}

	return ret;
}

char *sa_create_device_reboot_json_string(int value)
{
	json_object *jsonObj = NULL;
	char *buf = NULL;
	char *ret_buf = NULL;
	int buf_len = 0;

	jsonObj = json_object_new_object();
	if (jsonObj != NULL) {
		json_object_object_add(jsonObj, "result", json_object_new_int(value));

		buf = json_object_to_json_string_ext(jsonObj, JSON_C_TO_STRING_SPACED | JSON_C_TO_STRING_PRETTY);
		if (buf != NULL) {
			buf_len = strlen(buf) + 1;
			ret_buf = (char *)malloc(buf_len);
			if (ret_buf != NULL) {
				snprintf(ret_buf, buf_len, "%s", buf);
				//_D("create json:[%s]", ret_buf);
			}
		}
	} else
		_D("json object is not created");

	if (jsonObj != NULL)
		json_object_put(jsonObj);

	return ret_buf;
}

/* __do_statvfs ---print info */
/*
void __print_statvfs(struct statvfs vfs)
{
	_D("\tf_bsize: %ld\n",  (long) vfs.f_bsize);
	_D("\tf_frsize: %ld\n", (long) vfs.f_frsize);
	_D("\tf_blocks: %lu\n", (unsigned long) vfs.f_blocks);
	_D("\tf_bfree: %lu\n",  (unsigned long) vfs.f_bfree);
	_D("\tf_bavail: %lu\n", (unsigned long) vfs.f_bavail);
	_D("\tf_files: %lu\n",  (unsigned long) vfs.f_files);
	_D("\tf_ffree: %lu\n",  (unsigned long) vfs.f_ffree);
	_D("\tf_favail: %lu\n", (unsigned long) vfs.f_favail);
	_D("\tf_fsid: %#lx\n",  (unsigned long) vfs.f_fsid);
	_D("\tf_flag: ");
	if (vfs.f_flag == 0)
		_D("(none)\n");
	else {
		if ((vfs.f_flag & ST_RDONLY) != 0)
			_D("ST_RDONLY\n");
		if ((vfs.f_flag & ST_NOSUID) != 0)
			_D("ST_NOSUID\n");
	}
	_D("\tf_namemax: %#ld\n", (long)vfs.f_namemax);
}
*/

int sa_get_disk_info(disk_info_s * disk_info_h)
{
	FILE *fp;
	struct mntent *fs;
	struct statvfs vfs;
	int index = 0;
	int ret = 0;
	int buf_len = 0;
	const unsigned int MB = (1024 * 1024);

	if (disk_info_h == NULL) {
		_D("disk_info is NULL !!");
		ret = -1;
	}

	fp = setmntent(DEFAULT_FILE_SYSTEM_PATH, "r");	/* read only */
	if (fp == NULL) {
		_D("%s: could not open", DEFAULT_FILE_SYSTEM_PATH);
		ret = -1;
	}

	if (ret != -1) {
		// read struct mntent structures from file
		while ((fs = getmntent(fp)) != NULL) {
			if (fs->mnt_fsname[0] == '/') {	/* for nonreal filesystems */
				_D("%s, mounted on %s:", fs->mnt_dir, fs->mnt_fsname);
				if (statvfs(fs->mnt_dir, &vfs) != 0) {
					_D("%s: statvfs failed", fs->mnt_dir);
					ret = -1;
					break;
				} else {
					//__print_statvfs(vfs);
					buf_len = strlen(fs->mnt_dir) + 1;
					disk_info_h->disk[index].path = (char *)malloc(buf_len);
					if (disk_info_h->disk[index].path != NULL)
						snprintf(disk_info_h->disk[index].path, buf_len, "%s", fs->mnt_dir);

					unsigned long long f_total = (unsigned long long)vfs.f_blocks * (unsigned long long)vfs.f_frsize;
					unsigned long long f_free = (unsigned long long)vfs.f_bfree * (unsigned long long)vfs.f_frsize;
					unsigned long long f_used = f_total - f_free;
					disk_info_h->disk[index].total = (int)(f_total / (unsigned long long)MB);
					disk_info_h->disk[index].free = (int)(f_free / (unsigned long long)MB);
					disk_info_h->disk[index].used = (int)(f_used / (unsigned long long)MB);
					disk_info_h->disk[index].usedpercent = (int)((float)disk_info_h->disk[index].used / (float)disk_info_h->disk[index].total * 100 * 100);
					/*
					   _D("disk[%d], path = %s", index, disk_info_h->disk[index].path);
					   _D("disk[%d], total = %d", index, disk_info_h->disk[index].total);
					   _D("disk[%d], free = %d", index, disk_info_h->disk[index].free);
					   _D("disk[%d], used = %d", index, disk_info_h->disk[index].used);
					   _D("disk[%d], usedpercent = %.2f%%", index, (float)disk_info_h->disk[index].usedpercent/100);
					 */
					index++;
				}
			}
		}
		_D("disk_info_h->count :%d", index);
		disk_info_h->count = index;
		endmntent(fp);
	}

	return ret;
}

char *sa_create_disk_info_json_string(disk_info_s * disk_info_h)
{
	json_object *diskInfoObj = NULL;
	json_object *diskArrayObj = NULL;
	json_object *diskObj = NULL;
	char *buf = NULL;
	char *ret_buf = NULL;
	int index;
	int buf_len = 0;

	//_D("__create_disk_info_json_string()~~ ");
	if (disk_info_h != NULL) {
		if (disk_info_h->count > 0) {
			diskInfoObj = json_object_new_object();
			diskArrayObj = json_object_new_array();
			if (diskInfoObj != NULL && diskArrayObj != NULL) {
				json_object_object_add(diskInfoObj, "count", json_object_new_int(disk_info_h->count));
				for (index = 0; index < disk_info_h->count; index++) {
					diskObj = json_object_new_object();

					json_object_object_add(diskObj, "path", json_object_new_string(disk_info_h->disk[index].path));
					json_object_object_add(diskObj, "total", json_object_new_int(disk_info_h->disk[index].total));
					json_object_object_add(diskObj, "free", json_object_new_int(disk_info_h->disk[index].free));
					json_object_object_add(diskObj, "used", json_object_new_int(disk_info_h->disk[index].used));
					json_object_object_add(diskObj, "usedpercent", json_object_new_int(disk_info_h->disk[index].usedpercent));
					json_object_array_add(diskArrayObj, diskObj);
				}
				json_object_object_add(diskInfoObj, "disk", diskArrayObj);

				buf = json_object_to_json_string_ext(diskInfoObj, JSON_C_TO_STRING_SPACED | JSON_C_TO_STRING_PRETTY);
				if (buf != NULL) {
					buf_len = strlen(buf) + 1;
					ret_buf = (char *)malloc(buf_len);
					if (ret_buf != NULL)
						snprintf(ret_buf, buf_len, "%s", buf);
				}
			} else
				_D("empty object is not created");
		} else
			_D("no disk information");
	} else
		_D("disk_info_h is NULL !!");

	if (diskInfoObj != NULL)
		json_object_put(diskInfoObj);

	return ret_buf;
}

int sa_get_os_info(os_info_s * os_info_h)
{
	int ret = 0;
	char *ret_buf = NULL;
	int buf_len = 0;

	if (os_info_h == NULL) {
		_D("os_info is NULL !!");
		ret = -1;
	} else {
		// get platform version
		ret = CLI_command(GET_BELUGA_VERSION_CMD, 1, &ret_buf);
		if (ret_buf != NULL) {
			buf_len = strlen(ret_buf) + 1;
			os_info_h->platformVer = (char *)malloc(buf_len);
			if (os_info_h->platformVer != NULL)
				snprintf(os_info_h->platformVer, buf_len, "%s", ret_buf);

			_D("platformVer[%s]", os_info_h->platformVer);
			free(ret_buf);
			ret_buf = NULL;
		}
		// get base OS version
		ret = CLI_command(GET_BASEOS_VERSION_CMD, 1, &ret_buf);
		if (ret_buf != NULL) {
			buf_len = strlen(ret_buf) + 1;
			os_info_h->baseOSVer = (char *)malloc(buf_len);
			if (os_info_h->baseOSVer != NULL)
				snprintf(os_info_h->baseOSVer, buf_len, "%s", ret_buf);

			_D("baseOSVer[%s]", os_info_h->baseOSVer);
			free(ret_buf);
			ret_buf = NULL;
		}
		// get docker version
		ret = CLI_command(GET_DOCKER_VERSION_CMD, 1, &ret_buf);
		if (ret_buf != NULL) {
			buf_len = strlen(ret_buf) + 1;
			os_info_h->dockerVer = (char *)malloc(buf_len);
			if (os_info_h->dockerVer != NULL)
				snprintf(os_info_h->dockerVer, buf_len, "%s", ret_buf);

			_D("dockerVer[%s]", os_info_h->dockerVer);
			free(ret_buf);
			ret_buf = NULL;
		}
	}

	return ret;
}

char *sa_create_os_info_json_string(os_info_s * os_info_h)
{
	json_object *osInfoObj = NULL;
	char *buf = NULL;
	char *ret_buf = NULL;
	int buf_len = 0;

	//_D("__create_disk_info_json_string()~~ ");
	if (os_info_h != NULL) {
		osInfoObj = json_object_new_object();
		if (osInfoObj != NULL) {
			json_object_object_add(osInfoObj, "platformVer", json_object_new_string(os_info_h->platformVer));
			json_object_object_add(osInfoObj, "baseOSVer", json_object_new_string(os_info_h->baseOSVer));
			json_object_object_add(osInfoObj, "dockerVer", json_object_new_string(os_info_h->dockerVer));

			buf = json_object_to_json_string_ext(osInfoObj, JSON_C_TO_STRING_SPACED | JSON_C_TO_STRING_PRETTY);
			if (buf != NULL) {
				buf_len = strlen(buf) + 1;
				ret_buf = (char *)malloc(buf_len);
				if (ret_buf != NULL)
					snprintf(ret_buf, buf_len, "%s", buf);
			}
		} else
			_D("json object is not created");
	} else
		_D("os_info_h is NULL !!");

	if (osInfoObj != NULL)
		json_object_put(osInfoObj);

	return ret_buf;
}

static int __remove_directory(const char *path, int is_error_stop)
{
	DIR *dir_ptr = NULL;
	struct dirent *file = NULL;
	struct stat buf;
	char filename[1024];

	if ((dir_ptr = opendir(path)) == NULL) {
		// if path is not directory, unlink it
		return unlink(path);
	}
	// read from directory path
	while ((file = readdir(dir_ptr)) != NULL) {
		// skip for "." and ".." directories
		if (strcmp(file->d_name, ".") == 0 || strcmp(file->d_name, "..") == 0)
			continue;

		snprintf(filename, sizeof(filename), "%s/%s", path, file->d_name);

		// get file status
		if (lstat(filename, &buf) == -1)
			continue;

		if (S_ISDIR(buf.st_mode)) {
			// case of directory, run __remove_directory recursively
			if (__remove_directory(filename, is_error_stop) == -1 && is_error_stop) {
				closedir(dir_ptr);
				return -1;
			}
		} else if (S_ISREG(buf.st_mode) || S_ISLNK(buf.st_mode)) {
			// case of file or symbolic link
			if (unlink(filename) == -1 && is_error_stop) {
				closedir(dir_ptr);
				return -1;
			}
		}
	}
	closedir(dir_ptr);
	return rmdir(path);
}

/**
 * @fn        static int __create_directory(char *path, mode_t mode)
 * @brief     This function to create a directory
 * @param     *source   [in] string of directory full path
 * @param     mode_t    [in] mode
 * @return    int       result of function
 */
static int __create_directory(char *path, mode_t mode)
{
	int len = 0;
	char *tmp = path;
	char tmp_path[128] = { 0, };

	if (path == NULL)
		return -1;

	while ((tmp = strchr(tmp, '/')) != NULL) {
		len = tmp - path;
		tmp++;
		if (len == 0)
			continue;

		strncpy(tmp_path, path, len);
		tmp_path[len] = 0x00;

		if (access(tmp_path, 0) != 0) {
			if (mkdir(tmp_path, mode) == -1) {
				_E("mkdir error: %s", tmp_path);
				return -1;
			} else
				_D("created: %s", tmp_path);
		} else
			_W("already exist: %s", tmp_path);
	}

	return 0;
}

void *__factory_restore_procedure(void *pv)
{
	/* Factory Restore procedure */
	_D("Factory Restore procedure start.......");
	/* 0. Wait until caller response completed */
	sleep(5);
	/* 1. Remove docker services */
	_D("1. Remove docker services");
	if (system(DOCKER_SERVICES_REMOVE_CMD) != 0)
		_D("Error!! [%s] system call", DOCKER_SERVICES_REMOVE_CMD);

	/* 2. Remove docker containers */
	_D("2. Remove docker containers");
	if (system(DOCKER_CONTAINERS_REMOVE_CMD) != 0)
		_D("Error!! [%s] system call", DOCKER_CONTAINERS_REMOVE_CMD);

	/* 3. Remove docker images */
	_D("3. Remove docker images");
	if (system(DOCKER_IMAGES_REMOVE_CMD) != 0)
		_D("Error!! [%s] system call", DOCKER_IMAGES_REMOVE_CMD);

	/* 4. Prune docker system */
	_D("4. Prune docker system");
	if (system(DOCKER_SYSTEM_PRUNE_CMD) != 0)
		_D("Error!! [%s] system call", DOCKER_SYSTEM_PRUNE_CMD);

	/* 5. Delete docker directory */
	_D("5. Delete docker directory");
	if (stop_dockerd() != 0)
		_D("Error!! stop_dockerd");

	if (__remove_directory(DOCKER_DIRECTORY_PATH, 0) != 0)
		_D("Error!! [%s] __remove_directory", DOCKER_DIRECTORY_PATH);

	/* 6. Delete configuration files */
	_D("6. Delete configuration files");
	// setup configuration files
	if (sa_remove_config_file() != 0)
		_D("Error!! sa_remove_config_file");

	// proxy setting file
	if (sa_inputfile_remove_proxy_env() != 0)
		_D("Error!! sa_inputfile_remove_proxy_env");

	// docker daemon file
	if (sa_inputfile_remove_dockerd_opt() != 0)
		_D("Error!! sa_inputfile_remove_dockerd_opt");

	/* 7. Delete user container's volume */
	_D("7. Delete user container's volume");
	if (__remove_directory(USER_CONTAINER_VOLUME_PATH, 0) != 0)
		_D("Error!! [%s] __remove_directory", USER_CONTAINER_VOLUME_PATH);

	// create empty directory for bind-mount
	if (__create_directory(USER_CONTAINER_VOLUME_PATH, 0777) != 0)
		_D("Error!! [%s] __create_directory", USER_CONTAINER_VOLUME_PATH);

	/* 8. Initialize factory_init flag */
	_D("8. Initialize factory_init flag");
	if (__remove_factory_init_flag() != 0)
		_D("Error!! __remove_factory_init_flag");

	/* 9. Reboot machine */
	_D("9. Reboot machine");
	__device_reboot_cmd_loop((void *)NULL);

	return (void *)NULL;
}

int sa_factory_restore()
{
	int ret = 0;
	pthread_t thread;

	_D("factory restore start ~~~~~~~~~~~~~~~~~~~ ");
	if (pthread_create(&thread, NULL, &__factory_restore_procedure, (void *)NULL) < 0) {
		_D("thread create error");
		ret = -1;
	}
	return ret;
}

char *sa_create_factory_restore_json_string(int value)
{
	json_object *jsonObj = NULL;
	char *buf = NULL;
	char *ret_buf = NULL;
	int buf_len = 0;

	jsonObj = json_object_new_object();
	if (jsonObj != NULL) {
		json_object_object_add(jsonObj, "result", json_object_new_int(value));

		buf = json_object_to_json_string_ext(jsonObj, JSON_C_TO_STRING_SPACED | JSON_C_TO_STRING_PRETTY);
		if (buf != NULL) {
			buf_len = strlen(buf) + 1;
			ret_buf = (char *)malloc(buf_len);
			if (ret_buf != NULL)
				snprintf(ret_buf, buf_len, "%s", buf);
		}
	} else
		_D("json object is not created");

	if (jsonObj != NULL)
		json_object_put(jsonObj);

	return ret_buf;
}