This repository has been archived by the owner on Apr 27, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cli.py
executable file
·579 lines (403 loc) · 15.5 KB
/
cli.py
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
#!/usr/bin/python3
"""
Front-end CLI for the leakage database
"""
import ast
import sys
import os
import gzip
import argparse
import datetime
import logging as log
import configparser
import numpy as np
import ldb
ENTITY_CORES = "cores"
ENTITY_DEVICES = "devices"
ENTITY_BOARDS = "boards"
ENTITY_TARGETS = "targets"
ENTITY_EXPERIMENTS = "experiments"
ENTITY_TTRACESETS = "ttrace-sets"
ENTITY_TRACESETBLOBS= "traceset-blobs"
ENTITY_VARIABLEVALUE= "variable-values"
ENTITY_STAT_TRACES = "statistic-traces"
ENTITY_CORR_TRACES = "corrolation-traces"
#
# Possible entity types we can list in the database.
list_command_options = [
ENTITY_CORES ,
ENTITY_DEVICES ,
ENTITY_BOARDS ,
ENTITY_TARGETS ,
ENTITY_EXPERIMENTS ,
ENTITY_TTRACESETS ,
ENTITY_TRACESETBLOBS,
ENTITY_VARIABLEVALUE,
ENTITY_STAT_TRACES ,
ENTITY_CORR_TRACES
]
def connectToBackend(path, backend):
"""
Returns an appropriate instance of a database backend based on
the supplied path and backend parameters.
"""
if(backend == "sqlite"):
return ldb.backend.SQLiteBackend("sqlite:///"+path)
else:
raise Exception("Unknown backend '%s'" % backend)
def commandInit(args):
"""
Called when "init" is specified on the command line.
"""
backend = None
if(args.backend == "sqlite"):
backend = ldb.backend.SQLiteBackend
else:
raise Exception("Invalid backend string: '%s'" % args.backend)
file_exists = os.path.isfile(args.dbpath)
if(file_exists and not args.soft and not args.force):
log.error("The file '%s' already exists!" % args.dbpath)
return 1
elif(file_exists and args.soft and not args.force):
log.info("The file '%s' already exists." % args.dbpath)
return 0
if(file_exists and args.force):
log.warning("Removing pre-existing file '%s'" % args.dbpath)
os.remove(args.dbpath)
backend.createNew(args.dbpath)
log.info("Created new %s backed database at %s" % (
args.backend, args.dbpath))
return 0
def commandInsertTargets(args):
"""
Inserts a target device based on a description cfg of the type
used by the browser tool.
"""
if(args.from_cfg):
backend = connectToBackend(args.dbpath, args.backend)
backend.pushAutoCommit(False)
for cfg_path in args.from_cfg:
cfg = configparser.ConfigParser()
cfg.read(cfg_path)
core = ldb.records.Core.fromCFGDict(cfg)
board = ldb.records.Board.fromCFGDict(cfg)
device = ldb.records.Device.fromCFGDict(cfg)
if(backend.getCoreByName(core.name) == None):
backend.insertCore(core)
else:
core = backend.getCoreByName(core.name)
log.warn("Skipping core '%s', already exists." % core.name)
if(backend.getBoardByName(board.name) == None):
backend.insertBoard(board)
else:
board = backend.getBoardByName(board.name)
log.warn("Skipping board '%s', already exists." % board.name)
if(backend.getDeviceByName(device.name) == None):
backend.insertDevice(device)
else:
device = backend.getDeviceByName(device.name)
log.warn("Skipping device '%s', already exists." % device.name)
target = ldb.records.Target.fromCFGDict(
cfg, device.id, board.id, core.id
)
if(backend.getTargetByName(target.name) == None):
backend.insertTarget(target)
else:
log.warn("Skipping target '%s', already exists." % target.name)
backend.commit()
backend.popAutoCommit()
else:
log.warn("No target information to insert!")
return 0
def commandListEntries(args):
"""
A simple way to print out entries in the database.
"""
assert(args.entity in list_command_options)
backend = connectToBackend(args.dbpath, args.backend)
items = []
if (args.entity == ENTITY_CORES):
items = backend.getAllCores()
elif(args.entity == ENTITY_DEVICES):
items = backend.getAllDevices()
elif(args.entity == ENTITY_BOARDS):
items = backend.getAllBoards()
elif(args.entity == ENTITY_TARGETS):
items = backend.getAllTargets()
elif(args.entity == ENTITY_EXPERIMENTS):
items = backend.getAllExperiments()
elif(args.entity == ENTITY_TTRACESETS):
items = backend.getAllTTraceSets()
elif(args.entity == ENTITY_TRACESETBLOBS):
items = backend.getAllTraceSetBlobs()
elif(args.entity == ENTITY_VARIABLEVALUE):
items = backend.getAllVariableValues()
elif(args.entity == ENTITY_STAT_TRACES):
items = backend.getAllStatisticTraces()
elif(args.entity == ENTITY_CORR_TRACES):
items = backend.getAllCorrolationTraces()
else:
assert(False),"Should be unreachable!"
for item in items:
print(item)
return 0
def showTTraceSet(backend, ttraceSet):
"""
Print information on the TTrace set.
"""
experiment = backend.getExperimentById(ttraceSet.experimentId)
target = backend.getTargetById(ttraceSet.targetId)
fixed = ttraceSet.fixedTraceSet
random = ttraceSet.randomTraceSet
parameters = ast.literal_eval(ttraceSet.parameters)
print("TTraceSet captured at %s" % ttraceSet.timestamp)
print("Experiment: %s" % experiment.name)
print("Target : %s" % target.name)
print("Parameters:")
for p in parameters:
print("- %-7s : %s" % (p, parameters[p]))
print("Fixed Traces: %5d traces, %5d long" % fixed.shape)
for var in fixed.variableValues:
print("- %-5s id=%d, %d values" % (var.varname, var.id,var.num_values))
print("Random Traces: %5d traces, %5d long" % random.shape)
for var in random.variableValues:
print("- %-5s id=%d, %d values" % (var.varname, var.id,var.num_values))
return 0
def commandShow(args):
"""
Show all information on a specific object in the database.
"""
backend = connectToBackend(args.dbpath, args.backend)
if(args.entity == ENTITY_TTRACESETS):
ttraceSet = backend.getTTraceSetsById(args.id)
if(ttraceSet == None):
log.error("No TTraceSet exists with id '%d'" % args.id)
return 1
else:
return showTTraceSet(backend, ttraceSet)
else:
log.error("Functionality not implemented: 'show %s'" % args.entity)
return 1
return 0
def commandRemove(args):
"""
Implements removal operations for entities in the database.
"""
backend = connectToBackend(args.dbpath, args.backend)
if(args.entity == ENTITY_TTRACESETS):
backend.pushAutoCommit(False)
if(args.all):
for ts in backend.getAllTTraceSets():
backend.removeTTraceSet(ts.id)
else:
for tsid in args.id:
ttraceSet = backend.getTTraceSetsById(tsid)
if(ttraceSet == None):
log.error("No TTraceSet exists with id '%d'" % tsid)
return 1
backend.removeTTraceSet(ttraceSet.id)
backend.popAutoCommit()
backend.commit()
elif(args.entity == ENTITY_CORR_TRACES):
backend.pushAutoCommit(False)
if(args.all):
for ct in backend.getAllCorrolationTraces():
backend.removeCorrolationTrace(ct.id)
else:
for ctid in args.id:
corrtrace = backend.getCorrolationTraceById(ctid)
if(corrtrace== None):
log.error("No Corrolation Trace exists with id '%d'" % ctid)
return 1
backend.removeCorrolationTrace(corrtrace.id)
backend.popAutoCommit()
backend.commit()
elif(args.entity == ENTITY_EXPERIMENTS):
backend.pushAutoCommit(False)
if(args.all):
for ct in backend.getAllExperiments():
backend.removeExperiment(ct.id)
else:
for ctid in args.id:
experiment = backend.getExperimentById(ctid)
if(experiment == None):
log.error("No Experiment exists with id '%d'" % ctid)
return 1
backend.removeExperiment(experiment.id)
backend.popAutoCommit()
backend.commit()
elif(args.entity == ENTITY_TARGETS):
backend.pushAutoCommit(False)
if(args.all):
for tgt in backend.getAllTargets():
backend.removeTarget(tgt.id)
if(args.id):
for tid in args.id:
target = backend.getTargetById(tid)
if(target == None):
log.error("No target exists with id '%d'" % tid)
return 1
backend.removeTarget(target.id)
log.info("Removed target %3d %20s" % (
target.id, target.name
))
if(args.name):
for tname in args.name:
target = backend.getTargetByName(tname)
if(target == None):
log.error("No target exists with name '%s'" % tname)
return 1
backend.removeTarget(target.id)
backend.popAutoCommit()
backend.commit()
else:
log.error("Functionality not implemented: 'remove %s'" % args.entity)
return 1
return 0
def commandPlot(args):
"""
Uses Matplotlib to show a simple average trace plot for the supplied
trace blob.
"""
backend = connectToBackend(args.dbpath, args.backend)
blob = backend.getTraceSetBlobById(args.blob_id)
if(blob == None):
log.error("Unknown blob id '%d'" % args.blob_id)
traces = blob.getTracesAsNdArray()
import matplotlib.pyplot as plt
plt.figure()
plt.plot(traces)
plt.show()
return 0
def commandInsertExperiment(args):
"""
For inserting experiments into the database.
If the supplied name/catagory combination already exists, then
print the id of the existing entry. Otherwise print the id of
the new entry.
"""
backend = connectToBackend(args.dbpath, args.backend)
existing = backend.getExperimentByCatagoryAndName(
args.catagory,
args.name
)
if(existing == None):
newExperiment = ldb.records.Experiment(
name = args.name,
catagory = args.catagory,
description = args.description
)
backend.insertExperiment(newExperiment)
backend.commit()
print(newExperiment.id)
else:
print(existing.id)
return 0
def buildArgParser():
"""
Return the ArgumentParser object used to parse command line arguments
to the CLI app.
"""
parser = argparse.ArgumentParser()
parser.add_argument("dbpath", type=str,
help="File-path of the database")
parser.add_argument("--backend", choices=["sqlite"],
default="sqlite", help="Database Backend To Use")
parser.add_argument("--verbose","-v",action="store_true",
help="Turn on verbose logging.")
parser.add_argument("--log", type=str,
help = "Filepath to log too."
)
subparsers = parser.add_subparsers(
title="Sub-commands",
dest="command"
)
subparsers.required = True
#
# Arguments for listing entries in the database
parser_add_target = subparsers.add_parser("list",
help="list entries in the database")
parser_add_target.set_defaults(func=commandListEntries)
parser_add_target.add_argument("entity", type=str,
choices=list_command_options,
help="What sort of entity type in the database to list.")
#
# Arguments for inserting a new target, board, device and core from
# A config used by the browser tool
parser_add_target = subparsers.add_parser("insert-targets",
help="Insert a new target into the database")
parser_add_target.set_defaults(func=commandInsertTargets)
parser_add_target.add_argument("--from-cfg", type=str, nargs="+",
help="Insert Target, Device, Board and Core information from the supplied cfg file.")
#
# Arguments for adding a new experiment to the database
parser_add_experiment = subparsers.add_parser("insert-experiment",
help = "Add a new experiment to the database. If the experiment already exists, it is not updated.")
parser_add_experiment.set_defaults(func=commandInsertExperiment)
parser_add_experiment.add_argument("--catagory","-c", type=str,
default = "miscellaneous",
help="Catagory to which the experiment belongs.")
parser_add_experiment.add_argument("--description","-d", type=str,
default="",
help="A short description of the experiment")
parser_add_experiment.add_argument("name", type=str,
help="The name of the experiment")
#
# Arguments for initialising a new database
parser_init = subparsers.add_parser("init",
help="Create a new database file")
parser_init.set_defaults(func=commandInit)
parser_init.add_argument("--soft", action="store_true",
help="Don't raise an error if the destination file already exists.")
parser_init.add_argument("--force", action="store_true",
help="Remove the existing database file if it already exists.")
#
# Arguments for showing information on things
parser_show = subparsers.add_parser("show",
help="Show information on an object in the database")
parser_show.set_defaults(func=commandShow)
parser_show.add_argument("entity", type=str,
choices=list_command_options,
help="What sort of entity type in the database to show.")
parser_show.add_argument("id", type=int,
help="Unique ID of the entity to show")
#
# Arguments for manually deleteing things
parser_rm= subparsers.add_parser("remove",
help="Remove an entity (and possible sub-entities) from the database.")
parser_rm.set_defaults(func=commandRemove)
parser_rm.add_argument("entity", type=str,
choices=list_command_options,
help="What sort of entity type in the database to remove.")
parser_rm_grp = parser_rm.add_mutually_exclusive_group(required = True)
parser_rm_grp.add_argument("--id", type=int, nargs="+",
help="Unique ID of the entity to remove")
parser_rm_grp.add_argument("--name", type=str, nargs="+",
help="Unique Name of the entity to remove. Only used for targets")
parser_rm_grp.add_argument("--all", action="store_true",
help="Remove all entities of this type.")
#
# Arguments for plotting
parser_plot = subparsers.add_parser("plot",
help="Tools for creating simple plots from trace blobs")
parser_plot.set_defaults(func = commandPlot)
parser_plot_grp = parser_plot.add_mutually_exclusive_group(required=True)
parser_plot_grp.add_argument("--blob-id", type=int,
help="The ID of the traceset_blob to plot.")
return parser
def main():
"""
CLI main function
"""
parser = buildArgParser()
args = parser.parse_args()
log_level = log.WARN
log_file = args.log
if(args.verbose):
log_level = log.INFO
log.basicConfig(filename = log_file, level=log_level)
result = args.func(args)
return result
if(__name__=="__main__"):
rcode = main()
sys.exit(rcode)