-
Notifications
You must be signed in to change notification settings - Fork 2
/
iot_testbed_client.py
executable file
·1224 lines (967 loc) · 40.9 KB
/
iot_testbed_client.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
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
#!/usr/bin/env python3
import json
import copy
import re
from datetime import datetime, timedelta, date, time
from pathlib import Path
import warnings
import itertools
from requests import Session
from requests.compat import urljoin
import shutil
import unittest
default_config = {
"server": "https://research.iottestbed.disi.unitn.it",
"cacert": Path(__file__).resolve().parent.joinpath(
"testbediot-disi-unitn-it-chain.pem")
}
class ApiError(ValueError):
def __init__(self, contextMessage, code, message):
super().__init__(self, f"{contextMessage}: {code} {message}")
self.contextMessage = contextMessage
self.code = code
self.message = message
def __str__(self):
return f"{self.contextMessage}: " \
f"{','.join(itertools.chain.from_iterable(self.message.values()))}"
class Job:
"""
Class to represent a single job on testbed, the purpose of this class is
help set and modify in the correct way each parameter
"""
def __init__(self, source=None, cwd=Path()):
self.duration = None
self.start_time = None
self.binaries = []
if source is None:
return
if not isinstance(source, dict):
raise ValueError("source must be a dictionary")
source = copy.deepcopy(source)
self._cwd = cwd
# correction from legacy format
# first ts_init
if 'start_time' not in source and 'ts_init' in source:
warnings.warn("Deprecated use of ts_init, change it in start_time",
FutureWarning)
self.start_time = source.pop('ts_init')
if 'binaries' not in source and 'image' in source:
warnings.warn("Deprecated use of image, use binaries",
FutureWarning)
tmp = source.pop('image')
else:
tmp = source.pop('binaries')
if not isinstance(tmp, list):
tmp = [tmp, ]
for b in tmp:
if isinstance(b, dict):
if 'bin_file' not in b and 'file' in b:
warnings.warn(
"Deprecated use of file in binaries, use bin_file",
FutureWarning
)
b['bin_file'] = b.pop('file')
if 'targets' not in b and 'target' in b:
warnings.warn("Deprecated use of target, use targets",
FutureWarning)
b['targets'] = b.pop('target')
self.binaries.append(Job.Binary(**b))
else:
raise ValueError(
"binaries field should be a dictionary or list of "
"dicitionaries"
)
if 'orchestrator' in source:
if not isinstance(source['orchestrator'], dict):
raise ValueError("orchestrator element should be a dictionary")
elif 'python_script' in source:
warnings.warn(
"Deprecated use of python_script, change it in orchestrator",
FutureWarning
)
source['orchestrator'] = {'type': 'python',
'file': source.pop('python_script'),
'run': 'run_test'
}
if 'extra_files' in source:
efiles = source.pop('extra_files')
if isinstance(efiles, list):
for e in efiles:
if not isinstance(e, str):
raise ValueError(
f"Wrong format in extra_files, error on {e}"
)
self.add_extra_file(e)
elif isinstance(efiles, str):
self.add_extra_file(efiles)
else:
raise ValueError(
"Wrong format of extra_files, should be a list of string "
"or a string"
)
self.__dict__ = {**self.__dict__, **source}
class Binary:
"""
Binary class will contain all data about a binary used to all or some
node in the testbed
"""
def __init__(self, hardware, bin_file, targets, programAddress=None,
**kargs):
self.hardware = hardware
self.bin_file = bin_file
self.targets = targets
self.programAddress = programAddress
self.__dict__ = {**self.__dict__, **kargs}
def validate(self, cwd, filenames):
errors = []
warnings = []
if not isinstance(self.hardware, str):
errors.append(
"Hardware should be a string with platfoem name for this "
"binary file"
)
if isinstance(self.bin_file, str):
self.bin_file = Path(self.bin_file)
if not isinstance(self.bin_file, Path):
errors.append("file must be a string or a Path object")
if not cwd.joinpath(self.bin_file).is_file():
errors.append(f"File {self.bin_file} not found")
if self.bin_file.name in filenames:
warnings.append(f"file {self.bin_file} will be renamed")
if not isinstance(self.targets, list):
self.targets = [self.targets, ]
for t in self.targets:
if not isinstance(t, (int, str)):
errors.append(
"targets must be a str, a int or a list of them"
)
return errors, warnings
def toJSON(self):
tmp = copy.deepcopy(self)
if isinstance(tmp.bin_file, Path):
tmp.bin_file = str(tmp.bin_file)
return json.dumps(tmp.__dict__)
def _add_file(self, file_ref):
if isinstance(file_ref, Path):
return file_ref
elif isinstance(file_ref, str):
return Path(file_ref)
else:
raise TypeError("file_ref should be Path or str object")
def add_extra_file(self, file):
if not hasattr(self, 'extra_files'):
self.extra_files = [self._add_file(file), ]
else:
self.extra_files.append(self._add_file(file))
def validate(self):
errors = []
warnings = []
filenames = ['testFile.json', ]
if not isinstance(self.binaries, list):
self.binaries = [self.binaries, ]
for b in self.binaries:
e, w = b.validate(self._cwd, filenames)
errors += e
warnings += w
if hasattr(self, 'orchestrator'):
if not isinstance(self.orchestrator, dict):
errors.append("orchestrator should be a dictionary")
else:
if 'file' not in self.orchestrator:
errors.append("Orchestartor should have a file filed")
elif not isinstance(self.orchestrator['file'], (str, Path)):
errors.append(
"File field of orchestrator should be a string or a "
"Path object"
)
else:
if isinstance(self.orchestrator['file'], str):
self.orchestrator['file'] = Path(
self.orchestrator['file']
)
if not self._cwd.joinpath(
self.orchestrator['file']).is_file():
errors.append(
f"orchestrator file {self.orchestrator['file']} "
"not found"
)
elif self.orchestrator['file'].name in filenames:
# will not renamed, it is an error
errors.append("duplicated filename for orchestrator "
f"file: {self.orchestrator['file'].name}"
)
else:
filenames.append(self.orchestrator['file'].name)
if hasattr(self, 'extra_files'):
if not isinstance(self.extra_files, list):
self.extra_files = [self.extra_files, ]
tmp = self.extra_files.copy()
self.extra_files = []
for e in tmp:
if not isinstance(e, (str, Path)):
errors.append(
"extra_files must be a str, a Path or a list of them")
else:
if isinstance(e, str):
e = Path(e)
if not self._cwd.joinpath(e).is_file():
errors.append(f"extra file {e} not found")
elif e.name in filenames:
# extra_files will not be ranamed, it is an error
errors.append(f"duplicate filename {e} ")
else:
self.extra_files.append(e)
filenames.append(e.name)
return errors, warnings
def toJSON(self, indent=4):
tmp = copy.deepcopy(self)
delattr(tmp, '_cwd')
if isinstance(tmp.start_time, datetime):
tmp.start_time = tmp.start_time.strftime("%Y-%m-%d %H:%M")
btmp = tmp.binaries
tmp.binaries = []
for b in btmp:
tmp.binaries.append(json.loads(b.toJSON()))
if hasattr(tmp, 'orchestrator'):
if isinstance(tmp.orchestrator, dict):
if ('file' in tmp.orchestrator and
not isinstance(tmp.orchestrator['file'], str)):
tmp.orchestrator['file'] = str(tmp.orchestrator['file'])
else:
raise TypeError(
"Dont't know how to handle an orchestrator element that "
"is not a dictionary"
)
if hasattr(tmp, 'extra_files') and isinstance(tmp.extra_files, list):
etmp = tmp.extra_files
tmp.extra_files = []
for e in etmp:
if isinstance(e, Path):
tmp.extra_files.append(str(e))
elif isinstance(e, str):
tmp.extra_files.append(e)
else:
raise TypeError(
"Don't know hot to handle extra_file element is not "
"a Path or str"
)
return json.dumps(tmp.__dict__, indent=indent)
def attachedFiles(self):
""" return a list of file used by this job """
def _cwd_path(f):
return self._cwd.joinpath(f)
# binaries files
for b in self.binaries:
yield _cwd_path(b.bin_file)
# orchestartor
if hasattr(self, 'orchestrator'):
yield _cwd_path(self.orchestrator['file'])
# extra file
if hasattr(self, 'extra_files'):
if isinstance(self.extra_files, list):
for f in self.extra_files:
yield _cwd_path(f)
else:
yield Path(self.extra_files)
class TestJobs(unittest.TestCase):
"""
Class to autoimaitc test Job class
"""
def setUp(self):
self.DURATION_TEST = 5
self.START_TIME_TEST = "String"
self.HARDWARE_TEST = "platform"
self.BIN_FILE_TEST = "/tmp/falseBinary"
self.TARGETS_TEST = "all"
self.d = {"duration": self.DURATION_TEST,
"start_time": self.START_TIME_TEST,
"binaries": {
"hardware": self.HARDWARE_TEST,
"bin_file": self.BIN_FILE_TEST,
"targets": self.TARGETS_TEST
}
}
self.falseBinary = Path(self.BIN_FILE_TEST)
with self.falseBinary.open("w+") as fh:
fh.write("Hello world!!")
self._fileToCancel = []
def tearDown(self):
self.falseBinary.unlink()
for f in self._fileToCancel:
f.unlink()
def _falseFile(self, filepath):
with filepath.open('w+') as fh:
fh.write(f"Hello world from {filepath}")
self._fileToCancel.append(Path(filepath))
def test_create_from_dict(self):
j = Job(self.d)
self.assertEqual(j.duration, self.DURATION_TEST)
self.assertEqual(j.start_time, self.START_TIME_TEST)
self.assertIsInstance(j.binaries, list)
self.assertEqual(len(j.binaries), 1)
self.assertIsInstance(j.binaries[0], Job.Binary)
self.assertEqual(j.binaries[0].hardware, self.HARDWARE_TEST)
self.assertEqual(j.binaries[0].bin_file, self.BIN_FILE_TEST)
self.assertEqual(j.binaries[0].targets, self.TARGETS_TEST)
def _test_validate_json(self, job, expected_error, expected_warnings):
errors, warnings = job.validate()
self.assertEqual(errors, expected_error)
self.assertEqual(warnings, expected_warnings)
# Binares field is handled in a list, returned string should see it
if not isinstance(self.d['binaries'], list):
self.d['binaries'] = [self.d['binaries'], ]
# Targets in binaries object are always list,
for b in self.d['binaries']:
if not isinstance(b['targets'], list):
b['targets'] = [b['targets'], ]
self.assertLessEqual(job.toJSON(), json.dumps(self.d))
def test_json(self):
j = Job(self.d)
# Binares field is handled in a list, returned string should see it
self.d['binaries'] = [self.d['binaries'], ]
self.assertLessEqual(j.toJSON(0), json.dumps(self.d))
def test_not_existing_bin_file(self):
NOT_EXISTING_PATH = "/not/existing/path"
self.d['binaries']['bin_file'] = NOT_EXISTING_PATH
j = Job(self.d)
self._test_validate_json(j, [f"File {NOT_EXISTING_PATH} not found"],
[])
def test_start_time_values(self):
# start_time can be a datetime value
self.d['start_time'] = datetime.now()
j = Job(self.d)
self.d['start_time'] = self.d['start_time'].strftime("%Y-%m-%d %H:%M")
self._test_validate_json(j, [], [])
def test_legacy_ts_init(self):
self.d['ts_init'] = self.d.pop('start_time')
with self.assertWarnsRegex(FutureWarning, r"Deprecated use of .*"):
j = Job(self.d)
errors, warnings = j.validate()
self.assertEqual(errors, [])
self.assertEqual(warnings, [])
# Binares field is handled in a list, returned string should see it
self.d['binaries'] = [self.d['binaries'], ]
# Targets in binaries object are always list,
for b in self.d['binaries']:
if not isinstance(b['targets'], list):
b['targets'] = [b['targets'], ]
# TODO improve assert
self.assertNotEqual(j.toJSON(), json.dumps(self.d))
def test_legacy_image(self):
self.d['image'] = self.d.pop('binaries')
with self.assertWarnsRegex(FutureWarning, r"Deprecated use of .*"):
j = Job(self.d)
errors, warnings = j.validate()
self.assertEqual(errors, [])
self.assertEqual(warnings, [])
# Binares field is handled in a list, returned string should see it
self.d['image'] = [self.d['image'], ]
# Targets in image object are always list,
for b in self.d['image']:
if not isinstance(b['targets'], list):
b['targets'] = [b['targets'], ]
# TODO improve assert
self.assertNotEqual(j.toJSON(), json.dumps(self.d))
def test_legacy_python_script(self):
falsePythonScript = '/tmp/pFile.py'
self._falseFile(Path(falsePythonScript))
self.d['python_script'] = falsePythonScript
with self.assertWarnsRegex(FutureWarning, r"Deprecated use of .*"):
j = Job(self.d)
errors, warnings = j.validate()
self.assertEqual(errors, [])
self.assertEqual(warnings, [])
def test_orchestrator(self):
orchestratorFile = '/tmp/orchestrator.py'
self._falseFile(Path(orchestratorFile))
self.d['orchestrator'] = {'file': orchestratorFile}
j = Job(self.d)
self._test_validate_json(j, [], [])
# IoTTestbed class-------------------------------------------------------------
class IoTTestbed:
"""
Class that represent the testbed Frontend, it handles connection and
operation
"""
def __init__(self, token, server, cacert=None, **kargs):
if (not server.startswith("http://") and
not server.startswith("https://")):
raise ValueError("Server should start with http:// or https://")
self.server = server
self.token = token
self.cacert = cacert if cacert is not None else True
self._session = None
def is_open(self):
return self._session is not None
def open(self):
if self.is_open():
# TODO: change error type
raise Exception("Already connected")
self._session = Session()
self._session.headers = {
'Authorization': f'Token {self.token}',
'Accept': 'application/json'
}
if self.server.startswith("https"):
if isinstance(self.cacert, Path):
self._session.verify = str(self.cacert)
else:
self._session.verify = self.cacert
def __enter__(self):
if not self.is_open():
self.open()
return self
def close(self):
self._session.close()
self._session = None
def __exit__(self, type, value, traceback):
self.close()
def calendar(self, begin=datetime.now(),
end=datetime.now() + timedelta(days=7)):
if not self.is_open():
# TODO chaneg Excpetion type
raise Exception("Not open")
response = self._session.get(
urljoin(self.server, '/calendar_data'),
params={'begin__gte': begin, 'begin__lt': end}
)
if not response.ok:
raise Exception(
f"Something goes wrong: {response.status_code} "
f"{response.json()}"
)
return response.json()
def schedule(self, job):
if not isinstance(job, Job):
raise ValueError("job must be a Job object")
errors, warnings = job.validate()
if len(errors) > 0:
raise Exception(f"Not valid job: errors {errors}")
if not self.is_open():
# TODO chaneg Exception type
raise Exception("Not open")
files = []
for f in job.attachedFiles():
print(f"attached: {f}")
files.append(
('files', (f.name, f.open('rb'),
'application/octet-stream'))
)
r = self._session.post(urljoin(self.server, '/job/'),
data={'config': job.toJSON()},
files=files)
for label, f in files:
f[1].close()
return r.status_code == 200, r.json()
def cancel(self, jobId):
if not isinstance(jobId, int):
raise ValueError("jobId must be an int")
if not self.is_open():
# TODO change Exception type
raise Exception("Not open")
r = self._session.delete(
urljoin(self.server, f"/job/{jobId}"))
return r.ok, r.json()
def _get_filename(self, tmp):
if not tmp:
return None
fname = re.findall(r'filename="(.+)"', tmp)
if len(fname) == 0:
return None
return fname[0]
def download(self, jobId, destDir, delete=True, unzip=False):
if not isinstance(jobId, int):
raise TypeError("testId should be an integer")
if isinstance(destDir, str):
destDir = Path(destDir)
elif not isinstance(destDir, Path):
raise TypeError("destDir should be a str or Path object")
if not destDir.is_dir():
raise FileNotFoundError(
f"{destDir} doesn't exist or is not a directory")
if not self.is_open():
raise Exception("Not open")
r = self._session.get(
urljoin(self.server, f"/completed/{jobId}"))
if not r.ok:
raise Exception("Error downloading completed job file: "
f"{r.status_code} {r.content}")
filename = self._get_filename(r.headers.get('content-disposition'))
if not filename:
filename = f"job_{jobId}.tar.gz"
cLen = r.headers.get('content-length')
if cLen is None:
raise Exception('Received data does not contain expected content-length')
cLen = int(cLen)
if cLen != len(r.content):
raise Exception("Received data is of different length than expected "
f"(received: {len(r.content)} expected: {cLen})")
fpath = destDir.joinpath(filename)
count = fpath.write_bytes(r.content)
if delete:
r = self._session.delete(
urljoin(self.server, f"/completed/{jobId}"))
if not r.ok:
raise Exception("Error deleteing downloaded file on server "
f"{r.status_code} {r.content}")
if unzip:
try:
shutil.unpack_archive(fpath, destDir, format='gztar')
except Exception as e:
print(
"Warning: failed to extract the downloaded log "
f"{filename} to {destDir}"
)
print(e)
return str(fpath), count
def list_completed(self):
if not self.is_open():
raise Exception("Not open")
r = self._session.get(urljoin(self.server, "/completed/"))
if not r.ok:
raise Exception(
f"Error retrivieng completed list: {r.status_code} {r.content}"
)
return r.json()
def add_reservation(self, island, begin, end):
if not isinstance(begin, datetime):
raise ValueError("Begin argument is not valid")
if not isinstance(end, (datetime, timedelta)):
raise ValueError("End argument is not valid")
if isinstance(end, timedelta):
end = begin + end
if not self.is_open():
raise Exception("Not open")
r = self._session.post(
urljoin(self.server, "/reservations/"),
data={'island': island, 'begin': begin, 'end': end}
)
if not r.ok:
raise ApiError(
contextMessage="Error adding reservation",
code=r.status_code,
message=r.json()
)
return r.json()
def mod_reservation(self, reserv_id, island, begin, end):
if not isinstance(reserv_id, int):
raise ValueError("reserv_id should be an integer id")
if begin is not None and not isinstance(begin, (datetime, timedelta)):
raise ValueError("Begin argument is not valid")
if end is not None and not isinstance(end, (datetime, timedelta)):
raise ValueError("End argument is not valid")
if not self.is_open():
raise Exception("Not open")
old_response = self._session.get(
urljoin(self.server,
f"/reservations/{reserv_id}"
)
)
if not old_response.ok:
raise ApiError(
contextMessage="Error retrieving reservation to modify it",
code=old_response.status_code,
message=old_response.json()
)
print(f"{old_response.json()}")
old = old_response.json()
new = {'island': island if island is not None else old['island']}
if begin is None:
new['begin'] = old['begin']
elif isinstance(begin, timedelta):
new['begin'] = datetime.fromisoformat(old['begin']) + begin
else:
new['begin'] = begin
if end is None:
new['end'] = old['end']
elif isinstance(end, timedelta):
new['end'] = datetime.fromisoformat(old['end']) + end
else:
new['end'] = end
r = self._session.put(
urljoin(self.server, f"/reservations/{reserv_id}"),
data=new
)
if not r.ok:
raise ApiError(
contextMessage=f"Error modifying the reservation {reserv_id}",
code=r.status_code,
message=r.json()
)
return r.json()
def del_reservartion(self, reserv_id):
if not isinstance(reserv_id, int):
raise ValueError("reserv_id should be an integer id")
if not self.is_open():
raise Exception("Not open")
r = self._session.delete(
urljoin(self.server, f"/reservations/{reserv_id}")
)
if not r.ok:
raise ApiError(
contextMessage="Error deleting reservation",
code=r.status_code,
message=r.json()
)
return r.json()
def validate(jobFile):
print(f"File: {jobFile}")
if not isinstance(jobFile, (str, Path)):
raise TypeError("jobFile should be a str or Path object")
if isinstance(jobFile, str):
jobFile = Path(jobFile)
with jobFile.open('r') as fh:
job = Job(json.load(fh), jobFile.parent)
errs, warns = job.validate()
if len(errs) > 0:
print("Errors:")
for e in errs:
print(f"\t{e}")
if len(warns) > 0:
print("Warnings:")
for w in warns:
print(f"\t{w}")
if len(warns) == 0 and len(errs) == 0:
print("Job file valid")
elif len(errs) != 0:
print("Job file has error, rejected")
elif len(warns) != 0:
print("Job file has warings, accepted")
return job, errs, warns
def parse_datetime_argument(arg):
if not isinstance(arg, str):
raise ValueError("arg should be a string")
if arg == 'now':
return datetime.now() + timedelta(seconds=20)
m = re.match(r" ?(?P<number>[+-]\d+)(?P<unit>[mh])", arg)
if m:
if m.group('unit') == 'm':
return timedelta(minutes=int(m.group('number')))
elif m.group('unit') == 'h':
return timedelta(hours=int(m.group('number')))
try:
return datetime.fromisoformat(arg)
except Exception as err:
raise ValueError(f"Can't parse reservation argument '{arg}'") from err
class TestParseReservationArgument(unittest.TestCase):
def test_int(self):
with self.assertRaisesRegex(ValueError, "arg should be a string"):
parse_datetime_argument(1)
def test_str(self):
for value in ['+string', 'ciao']:
with self.assertRaises(ValueError):
parse_datetime_argument(value)
def test_now(self):
r = parse_datetime_argument('now')
self.assertTrue(isinstance(r, datetime))
self.assertLess(datetime.now() - r, timedelta(seconds=1))
def test_relative(self):
values = [
('-1h', timedelta(hours=-1)),
(' -1h', timedelta(hours=-1)),
('-1m', timedelta(minutes=-1)),
(' -1m', timedelta(minutes=-1)),
('+1m', timedelta(minutes=1)),
('+1h', timedelta(hours=1)),
]
for s, v in values:
with self.subTest(s=s):
r = parse_datetime_argument(s)
self.assertTrue(isinstance(r, timedelta))
self.assertEqual(r, v)
def test_absoulte(self):
values = ['2021-02-07 12:00', '2021-02-07T12:00']
ref = datetime(year=2021, month=2, day=7, hour=12, minute=0)
for v in values:
with self.subTest(v=v):
r = parse_datetime_argument(v)
self.assertTrue(isinstance(r, datetime))
self.assertEqual(r, ref)
if __name__ == '__main__':
import argparse
cli_parser = argparse.ArgumentParser(
description="Client script for testbed Iot"
)
subparser = cli_parser.add_subparsers(dest='command')
cli_parser.add_argument('--server', help="URL of testbed server")
cli_parser.add_argument('--token', '-t', help="Token used to authenticate")
cli_parser.add_argument('--cacert',
help="indicate which CA certificate use to verify "
"server certificate"
)
saveConfig = subparser.add_parser(
'saveConfig',
help="save configuration as default for user"
)
calendarParser = subparser.add_parser(
'calendar',
help='interrogate testbed to know when the testebd will used, by '
'default show next 7 days'
)
calendarParser.add_argument(
'--begin', '-b', nargs='?',
default=datetime.combine(date.today(), time()),
help="Request all the reservation that began after the specified "
"moment. Valid values are: a date in ISO format YYYY-mm-dd, "
"a quoted date and time in ISO format 'YYY-mm-dd HH:MM' or an "
"empty value for whenever. By default, when this option is "
"not used, is today at midnighth."
)
calendarParser.add_argument(
'--end', '-e', nargs='?',
default=datetime.combine(date.today(), time()) + timedelta(days=7),
help="Request all the reservation that ends before the specified "
"moment. Valid values are: a date in ISO format YYYY-mm-dd, a "
"quoted date and time in ISO format 'YYY-mm-dd HH:MM' or an empty "
"value for whenever. By default, when this option is not used, is "
"in 7 days at midnight."
)
# Validate subcommand -----------------------------------------------------
validateParser = subparser.add_parser(
'validate',
help='validate a jobFile only on client side, server will do a '
'better and deeper check before accept the job'
)
validateParser.add_argument('jobFile',
help='the json file that decribe the job',
nargs='+')
# Scheduler subcommand ----------------------------------------------------
scheduleParser = subparser.add_parser(
'schedule',
help='perform a validation as validate command and if '
'it is passed the test is submitted to Testbed'
)
startGroup = scheduleParser.add_mutually_exclusive_group()
startGroup.add_argument('--asap', action="store_true",
help="overwrite start_time fields with 'asap'")
startGroup.add_argument(
'--asap-after', metavar="AFTER",
help="overwrite start_time fields with 'asap AFTER', AFTER should be "
"in form (quoted) 'YYYY-mm-dd HH:MM' or in form (quoted or not) HH:MM"
)
startGroup.add_argument('--now', action='store_true',
help="overwrite start_time fields with 'now'")
scheduleParser.add_argument('--duration', type=int,
default=None,
help="overwrite the duration of the job (in seconds)")
scheduleParser.add_argument('jobFile',
help='the json file that decribe the job',
nargs='+')
# Cancel subcommand --------------------------------------------------
cancelParser = subparser.add_parser('cancel')
cancelParser.add_argument('jobId', help="ids of jobs to download",
type=int, nargs='+')
# Download subcommand --------------------------------------------------
downloadParser = subparser.add_parser('download',
help='downalod completed')
downloadParser.add_argument('jobId', help="ids of jobs to download",
type=int, nargs='*')
downloadParser.add_argument('--unzip', '-u',
help="unzip after downloading",
action='store_true')
downloadParser.add_argument(
'--dest-dir',
help="specify in which directory download files",
default='./'
)
downloadParser.add_argument(
'--no-delete', action='store_false',
help="avoid delete file on server after it is downloaded"
)
# list_completed subcommand -----------------------------------------------
list_completedParser = subparser.add_parser(
'completed',
help="retrieve list of user's completed job"
)
# reservation subcommand --------------------------------------------------
reservationParser = subparser.add_parser(
"reservation",
help="add, change or delete a reservation"
)
reservationCommand = reservationParser.add_subparsers(dest='reserv_cmd')