aboutsummaryrefslogtreecommitdiffstats
path: root/kernel-shark/src/libkshark-configio.c
blob: d7b8a699936d0da9bb40facbb947c5b20c26f52d (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
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
// SPDX-License-Identifier: LGPL-2.1

/*
 * Copyright (C) 2018 VMware Inc, Yordan Karadzhov <y.karadz@gmail.com>
 */

 /**
  *  @file    libkshark-configio.c
  *  @brief   Json Configuration I/O.
  */

// C
/** Use GNU C Library. */
#define _GNU_SOURCE
#include <stdio.h>
#include <sys/stat.h>

// KernelShark
#include "libkshark.h"
#include "libkshark-model.h"

static struct json_object *kshark_json_config_alloc(const char *type)
{
	json_object *jobj, *jtype;

	jobj = json_object_new_object();
	jtype = json_object_new_string(type);

	if (!jobj || !jtype)
		goto fail;

	/* Set the type of this Json document. */
	json_object_object_add(jobj, "type", jtype);

	return jobj;

 fail:
	fprintf(stderr, "Failed to allocate memory for json_object.\n");
	json_object_put(jobj);
	json_object_put(jtype);

	return NULL;
}

/**
 * @brief Allocate kshark_config_doc and set its format.
 *
 * @param format: Input location for the Configuration format identifier.
 *		  Currently only Json and String formats are supported.
 *
 * @returns kshark_config_doc instance on success, otherwise NULL. Use
 *	    free() to free the object.
 */
struct kshark_config_doc *
kshark_config_alloc(enum kshark_config_formats format)
{
	struct kshark_config_doc *doc;

	switch (format) {
	case KS_CONFIG_AUTO:
	case KS_CONFIG_JSON:
	case KS_CONFIG_STRING:
		doc = malloc(sizeof(*doc));
		if (!doc)
			goto fail;

		doc->format = format;
		doc->conf_doc = NULL;
		return doc;
	default:
		fprintf(stderr, "Document format %d not supported\n",
		format);
	}

	return NULL;

 fail:
	fprintf(stderr, "Failed to allocate memory for kshark_config_doc.\n");
	return NULL;
}

/**
 * @brief Create an empty Configuration document and set its format and type.
 *
 * @param type: String describing the type of the document,
 *		e.g. "kshark.config.record" or "kshark.config.filter".
 * @param format: Input location for the Configuration format identifier.
 *		  Currently only Json format is supported.
 *
 * @returns kshark_config_doc instance on success, otherwise NULL. Use
 *	    kshark_free_config_doc() to free the object.
 */
struct kshark_config_doc *
kshark_config_new(const char *type, enum kshark_config_formats format)
{
	struct kshark_config_doc *doc = NULL;

	if (format == KS_CONFIG_AUTO)
		format = KS_CONFIG_JSON;

	switch (format) {
	case KS_CONFIG_JSON:
		doc = kshark_config_alloc(format);
		if (doc) {
			doc->conf_doc = kshark_json_config_alloc(type);
			if (!doc->conf_doc) {
				free(doc);
				doc = NULL;
			}
		}

		break;
	case KS_CONFIG_STRING:
		doc = kshark_config_alloc(format);
		break;
	default:
		fprintf(stderr, "Document format %d not supported\n",
			format);
		return NULL;
	}

	return doc;
}

/**
 * @brief Free the Configuration document.
 *
 * @param conf: Input location for the kshark_config_doc instance. It is safe
 *	        to pass a NULL value.
 */
void kshark_free_config_doc(struct kshark_config_doc *conf)
{
	if (!conf)
		return;

	switch (conf->format) {
	case KS_CONFIG_JSON:
		json_object_put(conf->conf_doc);
		break;
	case KS_CONFIG_STRING:
		free(conf->conf_doc);
		break;
	}

	free(conf);
}

/**
 * @brief Use an existing Json document to create a new KernelShark
 *	  Configuration document.
 *
 * @param jobj: Input location for the json_object instance.
 *
 * @returns shark_config_doc instance on success, otherwise NULL. Use
 *	    kshark_free_config_doc() to free the object.
 */
struct kshark_config_doc *kshark_json_to_conf(struct json_object *jobj)
{
	struct kshark_config_doc *conf = kshark_config_alloc(KS_CONFIG_JSON);

	if (conf)
		conf->conf_doc = jobj;

	return conf;
}

/**
 * @brief Use an existing string to create a new KernelShark Configuration
 * document.
 *
 * @param val: Input location for the string.
 *
 * @returns shark_config_doc instance on success, otherwise NULL. Use
 *	    kshark_free_config_doc() to free the object.
 */
struct kshark_config_doc *kshark_string_to_conf(const char* val)
{
	struct kshark_config_doc *conf;
	char *str;

	conf = kshark_config_alloc(KS_CONFIG_STRING);
	if (conf) {
		if (asprintf(&str, "%s", val) > 0) {
			conf->conf_doc = str;
		} else {
			fprintf(stderr,
				"Failed to allocate string conf. doc.\n");
			free(conf);
			conf = NULL;
		}
	}

	return conf;
}

/**
 * @brief Add a field to a KernelShark Configuration document.
 *
 * @param conf: Input location for the kshark_config_doc instance. Currently
 *		only Json format is supported.
 * @param key: The name of the field.
 * @param val: Input location for the kshark_config_doc to be added. Currently
 *	       only Json and String formats are supported. Pass KS_CONFIG_AUTO
 *	       if you want "val" to have the same fornat as "conf". Upon
 *	       calling this function, the ownership of "val" transfers to
 *	       "conf".
 *
 * @returns True on success, otherwise False.
 */
bool kshark_config_doc_add(struct kshark_config_doc *conf,
			   const char *key,
			   struct kshark_config_doc *val)
{
	struct json_object *jobj = NULL;

	if (!conf || !val)
		return false;

	if (val->format == KS_CONFIG_AUTO)
		val->format = conf->format;

	switch (conf->format) {
	case KS_CONFIG_JSON:
		switch (val->format) {
		case KS_CONFIG_JSON:
			json_object_object_add(conf->conf_doc, key,
					       val->conf_doc);
			break;

		case KS_CONFIG_STRING:
			jobj = json_object_new_string(val->conf_doc);
			if (!jobj)
				goto fail;

			json_object_object_add(conf->conf_doc, key, jobj);
			break;

		default:
			fprintf(stderr, "Value format %d not supported\n",
				val->format);
			return false;
		}

		free(val);
		break;
	default:
		fprintf(stderr, "Document format %d not supported\n",
			conf->format);
		return false;
	}

	return true;

 fail:
	fprintf(stderr, "Failed to allocate memory for json_object.\n");
	json_object_put(jobj);

	return false;
}

static bool get_jval(struct kshark_config_doc *conf,
		     const char *key, void **val)
{
	return json_object_object_get_ex(conf->conf_doc, key,
					 (json_object **) val);
}

/**
 * @brief Get the KernelShark Configuration document associate with a given
 *	  field name.
 *
 * @param conf: Input location for the kshark_config_doc instance. Currently
 *		only Json format is supported.
 * @param key: The name of the field.
 * @param val: Output location for the kshark_config_doc instance containing
 *	       the field. Currently only Json and String formats are supported.
 *
 * @returns True, if the key exists, otherwise False.
 */
bool kshark_config_doc_get(struct kshark_config_doc *conf,
			   const char *key,
			   struct kshark_config_doc *val)
{
	struct kshark_config_doc *tmp;

	if (!conf || !val)
		return false;

	if (val->format == KS_CONFIG_AUTO)
		val->format = conf->format;

	switch (conf->format) {
	case KS_CONFIG_JSON:
		switch (val->format) {
		case KS_CONFIG_JSON:
			json_object_put(val->conf_doc);
			if (!get_jval(conf, key, &val->conf_doc))
				goto fail;

			return true;
		case KS_CONFIG_STRING:
			tmp = kshark_config_alloc(KS_CONFIG_AUTO);
			if (!tmp)
				goto fail;

			if (!get_jval(conf, key, &tmp->conf_doc))
				goto fail;

			free(val->conf_doc);
			val->conf_doc =
				(char *) json_object_get_string(tmp->conf_doc);
			free(tmp);

			return true;
		default:
			fprintf(stderr, "Value format %d not supported\n",
				val->format);
			return false;
		}

		break;
	default:
		fprintf(stderr, "Document format %d not supported\n",
			conf->format);
		return false;
	}

	return true;

 fail:
	fprintf(stderr, "Failed to get config. document.\n");
	return false;
}

/**
 * @brief Create an empty Record Configuration document. The type description
 *	  is set to "kshark.config.record".
 *
 * @returns kshark_config_doc instance on success, otherwise NULL. Use
 *	    kshark_free_config_doc() to free the object.
 */
struct kshark_config_doc *
kshark_record_config_new(enum kshark_config_formats format)
{
	return kshark_config_new("kshark.config.record", format);
}

/**
 * @brief Create an empty Filter Configuration document. The type description
 *	  is set to "kshark.config.filter".
 *
 * @returns kshark_config_doc instance on success, otherwise NULL. Use
 *	    kshark_free_config_doc() to free the object.
 */
struct kshark_config_doc *
kshark_filter_config_new(enum kshark_config_formats format)
{
	return kshark_config_new("kshark.config.filter", format);
}

/**
 * @brief Create an empty Text Configuration document. The Text Configuration
 *	  documents do not use type descriptions.
 *
 * @returns kshark_config_doc instance on success, otherwise NULL. Use free()
 *	    to free the object.
 */
struct kshark_config_doc *kshark_string_config_alloc()
{
	return kshark_config_alloc(KS_CONFIG_STRING);
}

static void json_del_if_exist(struct json_object *jobj, const char *key)
{
	struct json_object *temp;
	if (json_object_object_get_ex(jobj, key, &temp))
	    json_object_object_del(jobj, key);
}

static bool kshark_json_type_check(struct json_object *jobj, const char *type)
{
	struct json_object *jtype;
	const char *type_str;

	if (!json_object_object_get_ex(jobj, "type", &jtype))
		return false;

	type_str = json_object_get_string(jtype);
	if (strcmp(type_str, type) != 0)
		return false;

	return true;
}

/**
 * @brief Check the type of a Configuration document and compare with an
 *	  expected value.
 *
 * @param conf: Input location for the kshark_config_doc instance.
 * @param type: Input location for the expected value of the Configuration
 *		document type, e.g. "kshark.config.record" or
 *		"kshark.config.filter".
 *
 * @returns True, if the document has the expected type, otherwise False.
 */
bool kshark_type_check(struct kshark_config_doc *conf, const char *type)
{
	switch (conf->format) {
	case KS_CONFIG_JSON:
		return kshark_json_type_check(conf->conf_doc, type);

	default:
		fprintf(stderr, "Document format %d not supported\n",
			conf->format);
		return false;
	}
}

static bool kshark_trace_file_to_json(const char *file,
				      struct json_object *jobj)
{
	struct json_object *jfile_name, *jtime;
	struct stat st;

	if (!file || !jobj)
		return false;

	if (stat(file, &st) != 0) {
		fprintf(stderr, "Unable to find file %s\n", file);
		return false;
	}

	jfile_name = json_object_new_string(file);
	jtime = json_object_new_int64(st.st_mtime);

	if (!jfile_name || !jtime)
		goto fail;

	json_object_object_add(jobj, "file", jfile_name);
	json_object_object_add(jobj, "time", jtime);

	return true;

 fail:
	fprintf(stderr, "Failed to allocate memory for json_object.\n");
	json_object_put(jobj);
	json_object_put(jfile_name);
	json_object_put(jtime);

	return false;
}

/**
 * @brief Record the name of a trace data file and its timestamp into a
 *	  Configuration document.
 *
 * @param file: The name of the file.
 * @param format: Input location for the Configuration format identifier.
 *		  Currently only Json format is supported.
 *
 * @returns True on success, otherwise False.
 */
struct kshark_config_doc *
kshark_export_trace_file(const char *file,
			 enum kshark_config_formats format)
{
	/*  Create a new Configuration document. */
	struct kshark_config_doc *conf =
		kshark_config_new("kshark.config.data", format);

	if (!conf)
		return NULL;

	switch (format) {
	case KS_CONFIG_JSON:
		kshark_trace_file_to_json(file, conf->conf_doc);
		return conf;

	default:
		fprintf(stderr, "Document format %d not supported\n",
			conf->format);
		return NULL;
	}
}

static bool kshark_trace_file_from_json(const char **file,
					struct json_object *jobj)
{
	struct json_object *jfile_name, *jtime;
	const char *file_str;
	struct stat st;
	int64_t time;

	if (!jobj)
		return false;

	if (!kshark_json_type_check(jobj, "kshark.config.data") ||
	    !json_object_object_get_ex(jobj, "file", &jfile_name) ||
	    !json_object_object_get_ex(jobj, "time", &jtime)) {
		fprintf(stderr,
			"Failed to retrieve data file from json_object.\n");
		return false;
	}

	file_str = json_object_get_string(jfile_name);
	time = json_object_get_int64(jtime);

	if (stat(file_str, &st) != 0) {
		fprintf(stderr, "Unable to find file %s\n", file_str);
		return false;
	}

	if (st.st_mtime != time) {
		fprintf(stderr,"Timestamp mismatch!\nFile %s", file_str);
		return false;
	}

	*file = file_str;

	return true;
}

/**
 * @brief Read the name of a trace data file and its timestamp from a
 *	  Configuration document and check if such a file exists.
 *	  If the file exists, open it.
 *
 * @param kshark_ctx: Input location for session context pointer.
 * @param conf: Input location for the kshark_config_doc instance. Currently
 *		only Json format is supported.
 *
 * @returns The name of the file on success, otherwise NULL. "conf" has
 *	    the ownership over the returned string.
 */
const char* kshark_import_trace_file(struct kshark_context *kshark_ctx,
				     struct kshark_config_doc *conf)
{
	const char *file = NULL;
	switch (conf->format) {
	case KS_CONFIG_JSON:
		if (kshark_trace_file_from_json(&file, conf->conf_doc))
			kshark_open(kshark_ctx, file);

		break;

	default:
		fprintf(stderr, "Document format %d not supported\n",
			conf->format);
		return NULL;
	}

	return file;
}

static bool kshark_model_to_json(struct kshark_trace_histo *histo,
				 struct json_object *jobj)
{
	struct json_object *jrange, *jmin, *jmax, *jn_bins;
	if (!histo || !jobj)
		return false;

	jrange = json_object_new_array();

	jmin = json_object_new_int64(histo->min);
	jmax = json_object_new_int64(histo->max);
	jn_bins = json_object_new_int(histo->n_bins);

	if (!jrange || !jmin || !jmax || !jn_bins)
		goto fail;

	json_object_array_put_idx(jrange, 0, jmin);
	json_object_array_put_idx(jrange, 1, jmax);

	json_object_object_add(jobj, "range", jrange);
	json_object_object_add(jobj, "bins", jn_bins);

	return true;

 fail:
	fprintf(stderr, "Failed to allocate memory for json_object.\n");
	json_object_put(jobj);
	json_object_put(jrange);
	json_object_put(jmin);
	json_object_put(jmax);
	json_object_put(jn_bins);

	return false;
}

/**
 * @brief Record the current configuration of the Vis. model into a
 *	  Configuration document.
 * Load the configuration of the Vis. model from a Configuration
 *	  document.
 *
 * @param histo: Input location for the Vis. model descriptor.
 * @param format: Input location for the kshark_config_doc instance. Currently
 *		  only Json format is supported.
 *
 * @returns True on success, otherwise False.
 */
struct kshark_config_doc *
kshark_export_model(struct kshark_trace_histo *histo,
		    enum kshark_config_formats format)
{
	/*  Create a new Configuration document. */
	struct kshark_config_doc *conf =
		kshark_config_new("kshark.config.model", format);

	if (!conf)
		return NULL;

	switch (format) {
	case KS_CONFIG_JSON:
		kshark_model_to_json(histo, conf->conf_doc);
		return conf;

	default:
		fprintf(stderr, "Document format %d not supported\n",
			format);
		return NULL;
	}
}

static bool kshark_model_from_json(struct kshark_trace_histo *histo,
				   struct json_object *jobj)
{
	struct json_object *jrange, *jmin, *jmax, *jn_bins;
	uint64_t min, max;
	int n_bins;

	if (!histo || !jobj)
		return false;

	if (!kshark_json_type_check(jobj, "kshark.config.model") ||
	    !json_object_object_get_ex(jobj, "range", &jrange) ||
	    !json_object_object_get_ex(jobj, "bins", &jn_bins) ||
	    json_object_get_type(jrange) != json_type_array ||
	    json_object_array_length(jrange) != 2)
		goto fail;

	jmin = json_object_array_get_idx(jrange, 0);
	jmax = json_object_array_get_idx(jrange, 1);
	if (!jmin || !jmax)
		goto fail;

	min = json_object_get_int64(jmin);
	max = json_object_get_int64(jmax);
	n_bins = json_object_get_int(jn_bins);
	ksmodel_set_bining(histo, n_bins, min, max);

	if (histo->data && histo->data_size)
		ksmodel_fill(histo, histo->data, histo->data_size);

	return true;

 fail:
	fprintf(stderr, "Failed to load event filter from json_object.\n");
	return false;
}

/**
 * @brief Load the configuration of the Vis. model from a Configuration
 *	  document.
 *
 * @param histo: Input location for the Vis. model descriptor.
 * @param conf: Input location for the kshark_config_doc instance. Currently
 *		only Json format is supported.
 *
 * @returns True, if the model has been loaded. If the model configuration
 *	    document contains no data or in a case of an error, the function
 *	    returns False.
 */
bool kshark_import_model(struct kshark_trace_histo *histo,
			 struct kshark_config_doc *conf)
{
	switch (conf->format) {
	case KS_CONFIG_JSON:
		return kshark_model_from_json(histo, conf->conf_doc);

	default:
		fprintf(stderr, "Document format %d not supported\n",
			conf->format);
		return false;
	}
}

static bool kshark_event_filter_to_json(struct tep_handle *pevent,
					struct tracecmd_filter_id *filter,
					const char *filter_name,
					struct json_object *jobj)
{
	json_object *jfilter_data, *jevent, *jsystem, *jname;
	struct tep_event *event;
	int i, evt, *ids, nr_events;
	char *temp;

	jevent = jsystem = jname = NULL;

	/*
	 * If this Json document already contains a description of the filter,
	 * delete this description.
	 */
	json_del_if_exist(jobj, filter_name);

	/* Get the array of Ids to be fitered. */
	ids = tracecmd_filter_ids(filter);
	if (!ids)
		return true;

	/* Create a Json array and fill the Id values into it. */
	jfilter_data = json_object_new_array();
	if (!jfilter_data)
		goto fail;

	nr_events = tep_get_events_count(pevent);
	for (i = 0; i < filter->count; ++i) {
		for (evt = 0; evt < nr_events; ++evt) {
			event = tep_get_event(pevent, evt);
			if (event->id == ids[i]) {
				jevent = json_object_new_object();

				temp = event->system;
				jsystem = json_object_new_string(temp);

				temp = event->name;
				jname = json_object_new_string(temp);

				if (!jevent || !jsystem || !jname)
					goto fail;

				json_object_object_add(jevent, "system",
							       jsystem);

				json_object_object_add(jevent, "name",
							       jname);

				json_object_array_add(jfilter_data, jevent);

				break;
			}
		}
	}

	free(ids);

	/* Add the array of Ids to the filter config document. */
	json_object_object_add(jobj, filter_name, jfilter_data);

	return true;

 fail:
	fprintf(stderr, "Failed to allocate memory for json_object.\n");
	json_object_put(jfilter_data);
	json_object_put(jevent);
	json_object_put(jsystem);
	json_object_put(jname);
	free(ids);

	return false;
}

/**
 * @brief Record the current configuration of an Event Id filter into a
 *	  Configuration document.
 *
 * @param pevent: Input location for the Page event.
 * @param filter: Input location for an Id filter.
 * @param filter_name: The name of the filter to show up in the Json document.
 * @param conf: Input location for the kshark_config_doc instance. Currently
 *		only Json format is supported.
 *
 * @returns True on success, otherwise False.
 */
bool kshark_export_event_filter(struct tep_handle *pevent,
				struct tracecmd_filter_id *filter,
				const char *filter_name,
				struct kshark_config_doc *conf)
{
	switch (conf->format) {
	case KS_CONFIG_JSON:
		return kshark_event_filter_to_json(pevent, filter,
						   filter_name,
						   conf->conf_doc);

	default:
		fprintf(stderr, "Document format %d not supported\n",
			conf->format);
		return false;
	}
}

static bool kshark_event_filter_from_json(struct tep_handle *pevent,
					  struct tracecmd_filter_id *filter,
					  const char *filter_name,
					  struct json_object *jobj)
{
	json_object *jfilter, *jevent, *jsystem, *jname;
	const char *system_str, *name_str;
	struct tep_event *event;
	int i, length;

	/*
	 * Use the name of the filter to find the array of events associated
	 * with this filter. Notice that the filter config document may
	 * contain no data for this particular filter.
	 */
	if (!json_object_object_get_ex(jobj, filter_name, &jfilter))
		return false;

	if (!kshark_json_type_check(jobj, "kshark.config.filter") ||
	    json_object_get_type(jfilter) != json_type_array)
		goto fail;

	/* Set the filter. */
	length = json_object_array_length(jfilter);
	for (i = 0; i < length; ++i) {
		jevent = json_object_array_get_idx(jfilter, i);

		if (!json_object_object_get_ex(jevent, "system", &jsystem) ||
		    !json_object_object_get_ex(jevent, "name", &jname))
			goto fail;

		system_str = json_object_get_string(jsystem);
		name_str = json_object_get_string(jname);

		event = tep_find_event_by_name(pevent, system_str, name_str);
		if (!event)
			goto fail;

		tracecmd_filter_id_add(filter, event->id);
	}

	return true;

 fail:
	fprintf(stderr, "Failed to load event filter from json_object.\n");
	return false;
}

/**
 * @brief Load from Configuration document the configuration of an Event Id filter.
 *
 * @param pevent: Input location for the Page event.
 * @param filter: Input location for an Id filter.
 * @param filter_name: The name of the filter as showing up in the Config.
 *	               document.
 * @param conf: Input location for the kshark_config_doc instance. Currently
 *		only Json format is supported.
 *
 * @returns True, if a filter has been loaded. If the filter configuration
 *	    document contains no data for this particular filter or in a case
 *	    of an error, the function returns False.
 */
bool kshark_import_event_filter(struct tep_handle *pevent,
				struct tracecmd_filter_id *filter,
				const char *filter_name,
				struct kshark_config_doc *conf)
{
	switch (conf->format) {
	case KS_CONFIG_JSON:
		return kshark_event_filter_from_json(pevent, filter,
						     filter_name,
						     conf->conf_doc);

	default:
		fprintf(stderr, "Document format %d not supported\n",
			conf->format);
		return false;
	}
}

static bool kshark_filter_array_to_json(struct tracecmd_filter_id *filter,
					const char *filter_name,
					struct json_object *jobj)
{
	json_object *jfilter_data, *jpid = NULL;
	int i, *ids;

	/*
	 * If this Json document already contains a description of the filter,
	 * delete this description.
	 */
	json_del_if_exist(jobj, filter_name);

	/* Get the array of Ids to be filtered. */
	ids = tracecmd_filter_ids(filter);
	if (!ids)
		return true;

	/* Create a Json array and fill the Id values into it. */
	jfilter_data = json_object_new_array();
	if (!jfilter_data)
		goto fail;

	for (i = 0; i < filter->count; ++i) {
		jpid = json_object_new_int(ids[i]);
		if (!jpid)
			goto fail;

		json_object_array_add(jfilter_data, jpid);
	}

	free(ids);

	/* Add the array of Ids to the filter config document. */
	json_object_object_add(jobj, filter_name, jfilter_data);

	return true;

 fail:
	fprintf(stderr, "Failed to allocate memory for json_object.\n");
	json_object_put(jfilter_data);
	json_object_put(jpid);
	free(ids);

	return false;
}

/**
 * @brief Record the current configuration of a simple Id filter into a
 *	  Configuration document.
 *
 * @param filter: Input location for an Id filter.
 * @param filter_name: The name of the filter to show up in the Json document.
 * @param conf: Input location for the kshark_config_doc instance. Currently
 *		only Json format is supported.
 *
 * @returns True on success, otherwise False.
 */
bool kshark_export_filter_array(struct tracecmd_filter_id *filter,
				const char *filter_name,
				struct kshark_config_doc *conf)
{
	switch (conf->format) {
	case KS_CONFIG_JSON:
		return kshark_filter_array_to_json(filter, filter_name,
						   conf->conf_doc);

	default:
		fprintf(stderr, "Document format %d not supported\n",
			conf->format);
		return false;
	}
}

static bool kshark_filter_array_from_json(struct tracecmd_filter_id *filter,
					  const char *filter_name,
					  struct json_object *jobj)
{
	json_object *jfilter, *jpid;
	int i, length;

	/*
	 * Use the name of the filter to find the array of events associated
	 * with this filter. Notice that the filter config document may
	 * contain no data for this particular filter.
	 */
	if (!json_object_object_get_ex(jobj, filter_name, &jfilter))
		return false;

	if (!kshark_json_type_check(jobj, "kshark.config.filter") ||
	    json_object_get_type(jfilter) != json_type_array)
		goto fail;

	/* Set the filter. */
	length = json_object_array_length(jfilter);
	for (i = 0; i < length; ++i) {
		jpid = json_object_array_get_idx(jfilter, i);
		if (!jpid)
			goto fail;

		tracecmd_filter_id_add(filter, json_object_get_int(jpid));
	}

	return true;

 fail:
	fprintf(stderr, "Failed to load task filter from json_object.\n");
	return false;
}

/**
 * @brief Load from Configuration document the configuration of a simple
 *	  Id filter.
 *
 * @param filter: Input location for an Id filter.
 * @param filter_name: The name of the filter as showing up in the Config.
 *	               document.
 * @param conf: Input location for the kshark_config_doc instance. Currently
 *		only Json format is supported.
 *
 * @returns True, if a filter has been loaded. If the filter configuration
 *	    document contains no data for this particular filter or in a case
 *	    of an error, the function returns False.
 */
bool kshark_import_filter_array(struct tracecmd_filter_id *filter,
				const char *filter_name,
				struct kshark_config_doc *conf)
{
	switch (conf->format) {
	case KS_CONFIG_JSON:
		return kshark_filter_array_from_json(filter, filter_name,
						     conf->conf_doc);

	default:
		fprintf(stderr, "Document format %d not supported\n",
			conf->format);
		return false;
	}
}

static bool kshark_adv_filters_to_json(struct kshark_context *kshark_ctx,
				       struct json_object *jobj)
{
	struct tep_event_filter *adv_filter = kshark_ctx->advanced_event_filter;
	json_object *jfilter_data, *jevent, *jsystem, *jname, *jfilter;
	struct tep_event **events;
	char *str;
	int i;

	jevent = jsystem = jname = jfilter = NULL;

	/*
	 * If this Json document already contains a description of the model,
	 * delete this description.
	 */
	json_del_if_exist(jobj, KS_ADV_EVENT_FILTER_NAME);

	if (!kshark_ctx->advanced_event_filter ||
	    !kshark_ctx->advanced_event_filter->filters)
		return true;

	/* Create a Json array and fill the Id values into it. */
	jfilter_data = json_object_new_array();
	if (!jfilter_data)
		goto fail;

	events = tep_list_events(kshark_ctx->pevent, TEP_EVENT_SORT_SYSTEM);
	if (!events)
		return false;

	for (i = 0; events[i]; i++) {
		str = tep_filter_make_string(adv_filter,
					     events[i]->id);
		if (!str)
			continue;

		jevent = json_object_new_object();
		jsystem = json_object_new_string(events[i]->system);
		jname = json_object_new_string(events[i]->name);
		jfilter = json_object_new_string(str);
		if (!jevent || !jsystem || !jname || !jfilter)
			goto fail;

		json_object_object_add(jevent, "system", jsystem);
		json_object_object_add(jevent, "name", jname);
		json_object_object_add(jevent, "condition", jfilter);

		json_object_array_add(jfilter_data, jevent);
	}

	/* Add the array of advanced filters to the filter config document. */
	json_object_object_add(jobj, KS_ADV_EVENT_FILTER_NAME, jfilter_data);

	return true;

 fail:
	fprintf(stderr, "Failed to allocate memory for json_object.\n");
	json_object_put(jfilter_data);
	json_object_put(jevent);
	json_object_put(jsystem);
	json_object_put(jname);
	json_object_put(jfilter);

	return false;
}

/**
 * @brief Record the current configuration of the advanced filter into a
 *	  Configuration document.
 *
 * @param kshark_ctx: Input location for session context pointer.
 * @param conf: Input location for the kshark_config_doc instance. Currently
 *		only Json format is supported. If NULL, a new Adv. Filter
 *		Configuration document will be created.
 *
 * @returns True on success, otherwise False.
 */
bool kshark_export_adv_filters(struct kshark_context *kshark_ctx,
			       struct kshark_config_doc **conf)
{
	if (!*conf)
		*conf = kshark_filter_config_new(KS_CONFIG_JSON);

	if (!*conf)
		return false;

	switch ((*conf)->format) {
	case KS_CONFIG_JSON:
		return kshark_adv_filters_to_json(kshark_ctx,
						  (*conf)->conf_doc);

	default:
		fprintf(stderr, "Document format %d not supported\n",
			(*conf)->format);
		return false;
	}
}

static bool kshark_adv_filters_from_json(struct kshark_context *kshark_ctx,
					 struct json_object *jobj)
{
	struct tep_event_filter *adv_filter = kshark_ctx->advanced_event_filter;
	json_object *jfilter, *jsystem, *jname, *jcond;
	int i, length, n, ret = 0;
	char *filter_str = NULL;

	/*
	 * Use the name of the filter to find the array of events associated
	 * with this filter. Notice that the filter config document may
	 * contain no data for this particular filter.
	 */
	if (!json_object_object_get_ex(jobj, KS_ADV_EVENT_FILTER_NAME,
				       &jfilter))
		return false;

	if (!kshark_json_type_check(jobj, "kshark.config.filter") ||
	    json_object_get_type(jfilter) != json_type_array)
		goto fail;

	/* Set the filter. */
	length = json_object_array_length(jfilter);
	for (i = 0; i < length; ++i) {
		jfilter = json_object_array_get_idx(jfilter, i);

		if (!json_object_object_get_ex(jfilter, "system", &jsystem) ||
		    !json_object_object_get_ex(jfilter, "name", &jname) ||
		    !json_object_object_get_ex(jfilter, "condition", &jcond))
			goto fail;

		n = asprintf(&filter_str, "%s/%s:%s",
			     json_object_get_string(jsystem),
			     json_object_get_string(jname),
			     json_object_get_string(jcond));

		if (n <= 0) {
			filter_str = NULL;
			goto fail;
		}

		ret = tep_filter_add_filter_str(adv_filter,
						filter_str);
		if (ret < 0)
			goto fail;
	}

	return true;

 fail:
	fprintf(stderr, "Failed to laod Advanced filters.\n");
	if (ret < 0) {
		char error_str[200];
		int error_status =
			tep_strerror(kshark_ctx->pevent, ret, error_str,
				     sizeof(error_str));

		if (error_status == 0)
			fprintf(stderr, "filter failed due to: %s\n",
					error_str);
	}

	free(filter_str);
	return false;
}

/**
 * @brief Load from Configuration document the configuration of the advanced
 *	  filter.
 *
 * @param kshark_ctx: Input location for session context pointer.
 * @param conf: Input location for the kshark_config_doc instance. Currently
 *		only Json format is supported.
 *
 * @returns True, if a filter has been loaded. If the filter configuration
 *	    document contains no data for the Adv. filter or in a case of
 *	    an error, the function returns False.
 */
bool kshark_import_adv_filters(struct kshark_context *kshark_ctx,
			       struct kshark_config_doc *conf)
{
	switch (conf->format) {
	case KS_CONFIG_JSON:
		return kshark_adv_filters_from_json(kshark_ctx,
						    conf->conf_doc);

	default:
		fprintf(stderr, "Document format %d not supported\n",
			conf->format);
		return false;
	}
}

static bool kshark_user_mask_to_json(struct kshark_context *kshark_ctx,
				     struct json_object *jobj)
{
	uint8_t mask = kshark_ctx->filter_mask;
	json_object *jmask;

	jmask = json_object_new_int((int) mask);
	if (!jmask)
		return false;

	/* Add the mask to the filter config document. */
	json_object_object_add(jobj, KS_USER_FILTER_MASK_NAME, jmask);
	return true;
}

/**
 * @brief Record the current value of the the user-specified filter mask into
 *	  a Configuration document.
 *
 * @param kshark_ctx: Input location for session context pointer.
 * @param conf: Input location for the kshark_config_doc instance. Currently
 *		only Json format is supported. If NULL, a new Adv. Filter
 *		Configuration document will be created.
 *
 * @returns True on success, otherwise False.
 */
bool kshark_export_user_mask(struct kshark_context *kshark_ctx,
			     struct kshark_config_doc **conf)
{
	if (!*conf)
		*conf = kshark_filter_config_new(KS_CONFIG_JSON);

	if (!*conf)
		return false;

	switch ((*conf)->format) {
	case KS_CONFIG_JSON:
		return kshark_user_mask_to_json(kshark_ctx,
						(*conf)->conf_doc);

	default:
		fprintf(stderr, "Document format %d not supported\n",
			(*conf)->format);
		return false;
	}
}

static bool kshark_user_mask_from_json(struct kshark_context *kshark_ctx,
				       struct json_object *jobj)
{
	json_object *jmask;
	uint8_t mask;

	if (!kshark_json_type_check(jobj, "kshark.config.filter"))
		return false;
	/*
	 * Use the name of the filter to find the value of the filter maks.
	 * Notice that the filter config document may contain no data for
	 * the mask.
	 */
	if (!json_object_object_get_ex(jobj, KS_USER_FILTER_MASK_NAME,
				       &jmask))
		return false;

	mask = json_object_get_int(jmask);
	kshark_ctx->filter_mask = mask;

	return true;
}

/**
 * @brief Load from Configuration document the value of the user-specified
 *	  filter mask.
 *
 * @param kshark_ctx: Input location for session context pointer.
 * @param conf: Input location for the kshark_config_doc instance. Currently
 *		only Json format is supported.
 *
 * @returns True, if a mask has been loaded. If the filter configuration
 *	    document contains no data for the mask or in a case of an error,
 *	    the function returns False.
 */
bool kshark_import_user_mask(struct kshark_context *kshark_ctx,
			     struct kshark_config_doc *conf)
{
	switch (conf->format) {
	case KS_CONFIG_JSON:
		return kshark_user_mask_from_json(kshark_ctx,
						  conf->conf_doc);

	default:
		fprintf(stderr, "Document format %d not supported\n",
			conf->format);
		return false;
	}
}

static bool filter_is_set(struct tracecmd_filter_id *filter)
{
	return filter && filter->count;
}

/**
 * @brief Record the current configuration of "show task" and "hide task"
 *	  filters into a Json document.
 *
 * @param kshark_ctx: Input location for session context pointer.
 * @param conf: Input location for the kshark_config_doc instance. Currently
 *		only Json format is supported. If NULL, a new Filter
 *		Configuration document will be created.
 *
 * @returns True, if a filter has been recorded. If both filters contain
 *	    no Id values or in a case of an error, the function returns False.
 */
bool kshark_export_all_event_filters(struct kshark_context *kshark_ctx,
				     struct kshark_config_doc **conf)
{
	bool ret = true;

	if (!*conf)
		*conf = kshark_filter_config_new(KS_CONFIG_JSON);

	if (!*conf)
		return false;

	/* Save a filter only if it contains Id values. */
	if (filter_is_set(kshark_ctx->show_event_filter))
		ret &= kshark_export_event_filter(kshark_ctx->pevent,
						  kshark_ctx->show_event_filter,
						  KS_SHOW_EVENT_FILTER_NAME,
						  *conf);

	if (filter_is_set(kshark_ctx->hide_event_filter))
		ret &= kshark_export_event_filter(kshark_ctx->pevent,
						  kshark_ctx->hide_event_filter,
						  KS_HIDE_EVENT_FILTER_NAME,
						  *conf);

	return ret;
}

/**
 * @brief Record the current configuration of "show task" and "hide task"
 *	  filters into a Configuration document.
 *
 * @param kshark_ctx: Input location for session context pointer.
 * @param conf: Input location for the kshark_config_doc instance. Currently
 *		only Json format is supported. If NULL, a new Filter
 *		Configuration document will be created.
 *
 * @returns True, if a filter has been recorded. If both filters contain
 *	    no Id values or in a case of an error, the function returns False.
 */
bool kshark_export_all_task_filters(struct kshark_context *kshark_ctx,
				    struct kshark_config_doc **conf)
{
	bool ret = true;

	if (!*conf)
		*conf = kshark_filter_config_new(KS_CONFIG_JSON);

	if (!*conf)
		return false;

	/* Save a filter only if it contains Id values. */
	if (filter_is_set(kshark_ctx->show_task_filter))
		ret &= kshark_export_filter_array(kshark_ctx->show_task_filter,
						  KS_SHOW_TASK_FILTER_NAME,
						  *conf);

	if (filter_is_set(kshark_ctx->hide_task_filter))
		ret &= kshark_export_filter_array(kshark_ctx->hide_task_filter,
						  KS_HIDE_TASK_FILTER_NAME,
						  *conf);

	return ret;
}


/**
 * @brief Record the current configuration of "show cpu" and "hide cpu"
 *	  filters into a Configuration document.
 *
 * @param kshark_ctx: Input location for session context pointer.
 * @param conf: Input location for the kshark_config_doc instance. Currently
 *		only Json format is supported. If NULL, a new Filter
 *		Configuration document will be created.
 *
 * @returns True, if a filter has been recorded. If both filters contain
 *	    no Id values or in a case of an error, the function returns False.
 */
bool kshark_export_all_cpu_filters(struct kshark_context *kshark_ctx,
				   struct kshark_config_doc **conf)
{
	bool ret = true;

	if (!*conf)
		*conf = kshark_filter_config_new(KS_CONFIG_JSON);

	if (!*conf)
		return false;

	/* Save a filter only if it contains Id values. */
	if (filter_is_set(kshark_ctx->show_task_filter))
		ret &= kshark_export_filter_array(kshark_ctx->show_cpu_filter,
						  KS_SHOW_CPU_FILTER_NAME,
						  *conf);

	if (filter_is_set(kshark_ctx->hide_task_filter))
		ret &= kshark_export_filter_array(kshark_ctx->hide_cpu_filter,
						  KS_HIDE_CPU_FILTER_NAME,
						  *conf);

	return ret;
}

/**
 * @brief Load from a Configuration document the configuration of "show event"
 *	  and "hide event" filters.
 *
 * @param kshark_ctx: Input location for session context pointer.
 * @param conf: Input location for the kshark_config_doc instance. Currently
 *		only Json format is supported.
 *
 * @returns True, if a filter has been loaded. If the filter configuration
 *	    document contains no data for any event filter or in a case
 *	    of an error, the function returns False.
 */
bool kshark_import_all_event_filters(struct kshark_context *kshark_ctx,
				     struct kshark_config_doc *conf)
{
	bool ret = false;

	ret |= kshark_import_event_filter(kshark_ctx->pevent,
					  kshark_ctx->hide_event_filter,
					  KS_HIDE_EVENT_FILTER_NAME,
					  conf);

	ret |= kshark_import_event_filter(kshark_ctx->pevent,
					  kshark_ctx->show_event_filter,
					  KS_SHOW_EVENT_FILTER_NAME,
					  conf);

	return ret;
}

/**
 * @brief Load from Configuration document the configuration of "show task"
 *	  and "hide task" filters.
 *
 * @param kshark_ctx: Input location for session context pointer.
 * @param conf: Input location for the kshark_config_doc instance. Currently
 *		only Json format is supported.
 *
 * @returns True, if a filter has been loaded. If the filter configuration
 *	    document contains no data for any task filter or in a case of an
 *	    error, the function returns False.
 */
bool kshark_import_all_task_filters(struct kshark_context *kshark_ctx,
				    struct kshark_config_doc *conf)
{
	bool ret = false;

	ret |= kshark_import_filter_array(kshark_ctx->hide_task_filter,
					  KS_HIDE_TASK_FILTER_NAME,
					  conf);

	ret |= kshark_import_filter_array(kshark_ctx->show_task_filter,
					  KS_SHOW_TASK_FILTER_NAME,
					  conf);

	return ret;
}

/**
 * @brief Load from Configuration document the configuration of "show cpu"
 *	  and "hide cpu" filters.
 *
 * @param kshark_ctx: Input location for session context pointer.
 * @param conf: Input location for the kshark_config_doc instance. Currently
 *		only Json format is supported.
 *
 * @returns True, if a filter has been loaded. If the filter configuration
 *	    document contains no data for any cpu filter or in a case of an
 *	    error, the function returns False.
 */
bool kshark_import_all_cpu_filters(struct kshark_context *kshark_ctx,
				    struct kshark_config_doc *conf)
{
	bool ret = false;

	ret |= kshark_import_filter_array(kshark_ctx->hide_cpu_filter,
					  KS_HIDE_CPU_FILTER_NAME,
					  conf);

	ret |= kshark_import_filter_array(kshark_ctx->show_cpu_filter,
					  KS_SHOW_CPU_FILTER_NAME,
					  conf);

	return ret;
}

/**
 * @brief Create a Filter Configuration document containing the current
 *	  configuration of all filters.
 *
 * @param kshark_ctx: Input location for session context pointer.
 * @param format: Input location for the kshark_config_doc instance. Currently
 *		  only Json format is supported.
 *
 * @returns kshark_config_doc instance on success, otherwise NULL. Use
 *	    kshark_free_config_doc() to free the object.
 */
struct kshark_config_doc *
kshark_export_all_filters(struct kshark_context *kshark_ctx,
			  enum kshark_config_formats format)
{
	/*  Create a new Configuration document. */
	struct kshark_config_doc *conf =
		kshark_filter_config_new(format);

	/* Save a filter only if it contains Id values. */
	if (!conf ||
	    !kshark_export_all_event_filters(kshark_ctx, &conf) ||
	    !kshark_export_all_task_filters(kshark_ctx, &conf) ||
	    !kshark_export_all_cpu_filters(kshark_ctx, &conf) ||
	    !kshark_export_user_mask(kshark_ctx, &conf) ||
	    !kshark_export_adv_filters(kshark_ctx, &conf)) {
		kshark_free_config_doc(conf);
		return NULL;
	}

	return conf;
}

/**
 * @brief Load from a Configuration document the configuration of all filters.
 *
 * @param kshark_ctx: Input location for session context pointer.
 * @param conf: Input location for the kshark_config_doc instance. Currently
 *		only Json format is supported.
 *
 * @returns True, if a filter has been loaded. If the filter configuration
 *	    document contains no data for any filter or in a case of an error,
 *	    the function returns False.
 */
bool kshark_import_all_filters(struct kshark_context *kshark_ctx,
			       struct kshark_config_doc *conf)
{
	bool ret;
	ret = kshark_import_all_task_filters(kshark_ctx, conf);
	ret |= kshark_import_all_cpu_filters(kshark_ctx, conf);
	ret |= kshark_import_all_event_filters(kshark_ctx, conf);
	ret |= kshark_import_user_mask(kshark_ctx, conf);
	ret |= kshark_import_adv_filters(kshark_ctx, conf);

	return ret;
}

static bool kshark_save_json_file(const char *file_name,
				  struct json_object *jobj)
{
	int flags;

	/* Save the file in a human-readable form. */
	flags = JSON_C_TO_STRING_SPACED | JSON_C_TO_STRING_PRETTY;
	if (json_object_to_file_ext(file_name, jobj, flags) == 0)
		return true;

	return false;
}

/**
 * @brief Save a Configuration document into a file.
 *
 * @param file_name: The name of the file.
 * @param conf: Input location for the kshark_config_doc instance. Currently
 *		only Json format is supported.
 *
 * @returns True on success, otherwise False.
 */
bool kshark_save_config_file(const char *file_name,
			     struct kshark_config_doc *conf)
{
	switch (conf->format) {
	case KS_CONFIG_JSON:
		return kshark_save_json_file(file_name, conf->conf_doc);

	default:
		fprintf(stderr, "Document format %d not supported\n",
			conf->format);
		return false;
	}
}

static struct json_object *kshark_open_json_file(const char *file_name,
						 const char *type)
{
	struct json_object *jobj, *var;
	const char *type_var;

	jobj = json_object_from_file(file_name);

	if (!jobj)
		return NULL;

	/* Get the type of the document. */
	if (!json_object_object_get_ex(jobj, "type", &var))
		goto fail;

	type_var = json_object_get_string(var);

	if (strcmp(type, type_var) != 0)
		goto fail;

	return jobj;

 fail:
	/* The document has a wrong type. */
	fprintf(stderr, "Failed to open Json file %s\n.", file_name);
	fprintf(stderr, "The document has a wrong type.\n");

	json_object_put(jobj);
	return NULL;
}

static const char *get_ext(const char *filename)
{
	const char *dot = strrchr(filename, '.');

	if(!dot)
		return "unknown";

	return dot + 1;
}

/**
 * @brief Open for read a Configuration file and check if it has the
 *	  expected type.
 *
 * @param file_name: The name of the file. Currently only Json files are
 *		     supported.
 * @param type: String describing the expected type of the document,
 *		e.g. "kshark.config.record" or "kshark.config.filter".
 *
 * @returns kshark_config_doc instance on success, or NULL on failure. Use
 *	    kshark_free_config_doc() to free the object.
 */
struct kshark_config_doc *kshark_open_config_file(const char *file_name,
						  const char *type)
{
	struct kshark_config_doc *conf = NULL;

	if (strcmp(get_ext(file_name), "json") == 0) {
		struct json_object *jobj =
			kshark_open_json_file(file_name, type);

		if (jobj) {
			conf = malloc(sizeof(*conf));
			conf->conf_doc = jobj;
			conf->format = KS_CONFIG_JSON;
		}
	}

	return conf;
}