-
Notifications
You must be signed in to change notification settings - Fork 161
/
client.py
executable file
·1607 lines (1447 loc) · 64.2 KB
/
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
"""The remote.client module contains the functionality to connect to a
coordinator, acquire a place and interact with the connected resources"""
import argparse
import asyncio
import os
import subprocess
import traceback
import logging
import sys
from textwrap import indent
from socket import gethostname
from getpass import getuser
from collections import defaultdict, OrderedDict
from datetime import datetime
from pprint import pformat
import txaio
from autobahn.asyncio.wamp import ApplicationSession
from .common import *
from ..environment import Environment
from ..exceptions import NoDriverFoundError, NoResourceFoundError, InvalidConfigError
from ..resource.remote import RemotePlaceManager, RemotePlace
from ..util.dict import diff_dict, flat_dict, filter_dict
from ..util.yaml import dump
from .. import Target, target_factory
from ..util.proxy import proxymanager
from ..util.helper import processwrapper
txaio.use_asyncio()
txaio.config.loop = asyncio.get_event_loop()
class Error(Exception):
pass
class UserError(Error):
pass
class ServerError(Error):
pass
class ClientSession(ApplicationSession):
"""The ClientSession encapsulates all the actions a Client can Invoke on
the coordinator."""
def onConnect(self):
"""Actions which are executed if a connection is successfully opened."""
self.loop = self.config.extra['loop']
self.connected = self.config.extra['connected']
self.args = self.config.extra.get('args')
self.env = self.config.extra.get('env', None)
self.role = self.config.extra.get('role', None)
self.prog = self.config.extra.get('prog', os.path.basename(sys.argv[0]))
self.monitor = self.config.extra.get('monitor', False)
enable_tcp_nodelay(self)
self.join(
self.config.realm, authmethods=["ticket"],
authid="client/{}/{}".format(gethostname(), getuser())
)
def onChallenge(self, challenge):
return "dummy-ticket"
async def onJoin(self, details):
# FIXME race condition?
resources = await self.call(
'org.labgrid.coordinator.get_resources'
)
self.resources = {}
for exporter, groups in resources.items():
for group_name, group in sorted(groups.items()):
for resource_name, resource in sorted(group.items()):
await self.on_resource_changed(
exporter, group_name, resource_name, resource
)
places = await self.call('org.labgrid.coordinator.get_places')
self.places = {}
for placename, config in places.items():
await self.on_place_changed(placename, config)
await self.subscribe(
self.on_resource_changed,
'org.labgrid.coordinator.resource_changed'
)
await self.subscribe(
self.on_place_changed, 'org.labgrid.coordinator.place_changed'
)
await self.connected(self)
async def on_resource_changed(self, exporter, group_name, resource_name, resource):
group = self.resources.setdefault(exporter,
{}).setdefault(group_name, {})
# Do not replace the ResourceEntry object, as other components may keep
# a reference to it and want to see changes.
if resource_name not in group:
old = None
group[resource_name] = ResourceEntry(resource)
else:
old = group[resource_name].data
group[resource_name].data = resource
if self.monitor:
if resource and not old:
print("Resource {}/{}/{} created: {}".format(
exporter, group_name, resource_name, resource
))
elif resource and old:
print("Resource {}/{}/{} changed:".format(
exporter, group_name, resource_name,
))
for k, v_old, v_new in diff_dict(flat_dict(old), flat_dict(resource)):
print(" {}: {} -> {}".format(k, v_old, v_new))
else:
print("Resource {}/{}/{} deleted".format(
exporter, group_name, resource_name))
async def on_place_changed(self, name, config):
if not config:
del self.places[name]
if self.monitor:
print("Place {} deleted".format(name))
return
config = config.copy()
config['name'] = name
config['matches'] = [ResourceMatch(**match) \
for match in config['matches']]
config = filter_dict(config, Place, warn=True)
if name not in self.places:
place = Place(**config)
self.places[name] = place
if self.monitor:
print("Place {} created: {}".format(name, place))
else:
place = self.places[name]
old = flat_dict(place.asdict())
place.update(config)
new = flat_dict(place.asdict())
if self.monitor:
print("Place {} changed:".format(name))
for k, v_old, v_new in diff_dict(old, new):
print(" {}: {} -> {}".format(k, v_old, v_new))
async def do_monitor(self):
self.monitor = True
while True:
await asyncio.sleep(3600.0)
async def complete(self):
if self.args.type == 'resources':
for exporter, groups in sorted(self.resources.items()):
for group_name, group in sorted(groups.items()):
for _, resource in sorted(group.items()):
print("{}/{}/{}".format(exporter, group_name, resource.cls))
elif self.args.type == 'places':
for name in sorted(self.places.keys()):
print(name)
def _get_places_by_resource(self, resource_path):
"""Yield Place objects that match the given resource path"""
for place in self.places.values():
match = place.getmatch(resource_path)
if match:
yield place
async def print_resources(self):
"""Print out the resources"""
match = ResourceMatch.fromstr(self.args.match) if self.args.match else None
# filter self.resources according to the arguments
nested = lambda: defaultdict(nested)
filtered = nested()
for exporter, groups in sorted(self.resources.items()):
if self.args.exporter and exporter != self.args.exporter:
continue
for group_name, group in sorted(groups.items()):
for resource_name, resource in sorted(group.items()):
if not (resource.avail or self.args.verbose >= 2):
continue
if self.args.acquired and resource.acquired is None:
continue
if match and not match.ismatch((exporter, group_name,
resource.cls, resource_name)):
continue
filtered[exporter][group_name][resource_name] = resource
# print the filtered resources
if self.args.verbose and not self.args.sort_by_matched_place_change:
for exporter, groups in sorted(filtered.items()):
print("Exporter '{}':".format(exporter))
for group_name, group in sorted(groups.items()):
print(" Group '{group}' ({exporter}/{group}/*):".format(
group=group_name, exporter=exporter))
for resource_name, resource in sorted(group.items()):
print(" Resource '{res}' ({exporter}/{group}/{res_cls}[/{res}]):"
.format(res=resource_name, exporter=exporter, group=group_name,
res_cls=resource.cls))
print(indent(pformat(resource.asdict()), prefix=" "))
else:
results = []
for exporter, groups in sorted(filtered.items()):
for group_name, group in sorted(groups.items()):
for resource_name, resource in sorted(group.items()):
if self.args.sort_by_matched_place_change:
resource_path = (exporter, group_name, resource.cls, resource_name)
places = list(self._get_places_by_resource(resource_path))
# most recently changed place last
places = sorted(places, key=lambda p: p.changed, reverse=True)
else:
places = None
results.append((places, exporter, group_name, resource.cls))
results = sorted(results, key=lambda res: res[0][0].changed if res[0] else 0)
for places, exporter, group_name, resource_cls in results:
if self.args.sort_by_matched_place_change:
places_strs = [
"{}: {:%Y-%m-%d}".format(p.name, datetime.fromtimestamp(p.changed))
for p in places
]
places_info = ", ".join(places_strs) if places_strs else "not used by any place"
else:
places_info = None
line = "{}/{}/{}".format(exporter, group_name, resource_cls)
if places_info is not None:
print("{0:<50s} {1}".format(line, places_info))
else:
print(line)
async def print_places(self):
"""Print out the places"""
if self.args.sort_last_changed:
places = sorted(self.places.items(), key=lambda p: p[1].changed)
else:
places = sorted(self.places.items())
for name, place in places:
if self.args.acquired and place.acquired is None:
continue
if self.args.verbose:
print("Place '{}':".format(name))
place.show(level=1)
else:
line = "{}".format(name)
if place.aliases:
line += " ({})".format(' '.join(place.aliases))
print("{0:<40s} {1}".format(line, place.comment))
def print_who(self):
"""Print acquired places by user"""
result = [tuple('User Host Place Changed'.split())]
for name, place in self.places.items():
if place.acquired is None:
continue
host, user = place.acquired.split('/')
result.append((user, host, name, str(datetime.fromtimestamp(place.changed))))
result.sort()
widths = [max(map(len, c)) for c in zip(*result)]
for user, host, name, changed in result:
print("{0:<{width[0]}s} {1:<{width[1]}s} {2:<{width[2]}s} {3}".format(
user, host, name, changed, width=widths))
def _match_places(self, pattern):
"""search for substring matches of pattern in place names and aliases
Aliases in the format "namespace:alias" only match if the namespace is
the current user name.
"""
result = set()
# reservation token lookup
token = None
if pattern.startswith('+'):
token = pattern[1:]
if not token:
token = os.environ.get('LG_TOKEN', None)
if not token:
return []
for name, place in self.places.items():
if place.reservation == token:
result.add(name)
if not result:
raise UserError("reservation token {} matches nothing".format(token))
return list(result)
# name and alias lookup
for name, place in self.places.items():
if pattern in name:
result.add(name)
for alias in place.aliases:
if ':' in alias:
namespace, alias = alias.split(':', 1)
if namespace != getuser():
continue
elif alias == pattern: # prefer user namespace
return [name]
if pattern in alias:
result.add(name)
return list(result)
def _check_allowed(self, place):
if not place.acquired:
raise UserError("place {} is not acquired".format(place.name))
if gethostname()+'/'+getuser() not in place.allowed:
host, user = place.acquired.split('/')
if user != getuser():
raise UserError("place {} is not acquired by your user, acquired by {}".format(
place.name, user))
if host != gethostname():
raise UserError("place {} is not acquired on this computer, acquired on {}".format(
place.name, host))
def get_place(self, place=None):
pattern = place or self.args.place
if pattern is None:
raise UserError("place pattern not specified")
places = self._match_places(pattern)
if not places:
raise UserError("place pattern {} matches nothing".format(pattern))
if pattern in places:
return self.places[pattern]
if len(places) > 1:
raise UserError(
"pattern {} matches multiple places ({})".
format(pattern, ', '.join(places))
)
return self.places[places[0]]
def get_idle_place(self, place=None):
place = self.get_place(place)
if place.acquired:
raise UserError("place {} is not idle (acquired by {})".format(
place.name, place.acquired))
return place
def get_acquired_place(self, place=None):
place = self.get_place(place)
self._check_allowed(place)
return place
async def print_place(self):
"""Print out the current place and related resources"""
place = self.get_place()
print("Place '{}':".format(place.name))
place.show(level=1)
if place.acquired:
for resource_path in place.acquired_resources:
(exporter, group_name, cls, resource_name) = resource_path
match = place.getmatch(resource_path)
name = resource_name
if match.rename:
name = match.rename
resource = self.resources[exporter][group_name][resource_name]
print("Acquired resource '{}' ({}/{}/{}/{}):".format(
name, exporter, group_name, resource.cls, resource_name))
print(indent(pformat(resource.asdict()), prefix=" "))
assert resource.cls == cls
else:
for exporter, groups in sorted(self.resources.items()):
for group_name, group in sorted(groups.items()):
for resource_name, resource in sorted(group.items()):
resource_path = (exporter, group_name, resource.cls, resource_name)
match = place.getmatch(resource_path)
if match is None:
continue
name = resource_name
if match.rename:
name = match.rename
print("Matching resource '{}' ({}/{}/{}/{}):".format(
name, exporter, group_name, resource.cls, resource_name))
print(indent(pformat(resource.asdict()), prefix=" "))
async def add_place(self):
"""Add a place to the coordinator"""
name = self.args.place
if not name:
raise UserError("missing place name. Set with -p <place> or via env var $PLACE")
if name in self.places:
raise UserError("{} already exists".format(name))
res = await self.call('org.labgrid.coordinator.add_place', name)
if not res:
raise ServerError("failed to add place {}".format(name))
return res
async def del_place(self):
"""Delete a place from the coordinator"""
pattern = self.args.place
if pattern not in self.places:
raise UserError("deletes require an exact place name")
place = self.places[pattern]
if place.acquired:
raise UserError("place {} is not idle (acquired by {})".format(
place.name, place.acquired))
name = place.name
if not name:
raise UserError("missing place name. Set with -p <place> or via env var $PLACE")
if name not in self.places:
raise UserError("{} does not exist".format(name))
res = await self.call('org.labgrid.coordinator.del_place', name)
if not res:
raise ServerError("failed to delete place {}".format(name))
return res
async def add_alias(self):
"""Add an alias for a place on the coordinator"""
place = self.get_idle_place()
alias = self.args.alias
if alias in place.aliases:
raise UserError(
"place {} already has alias {}".format(place.name, alias)
)
res = await self.call(
'org.labgrid.coordinator.add_place_alias', place.name, alias
)
if not res:
raise ServerError(
"failed to add alias {} for place {}".format(alias, place.name)
)
return res
async def del_alias(self):
"""Delete an alias for a place from the coordinator"""
place = self.get_idle_place()
alias = self.args.alias
if alias not in place.aliases:
raise UserError("place {} has no alias {}".format(place.name, alias))
res = await self.call(
'org.labgrid.coordinator.del_place_alias', place.name, alias
)
if not res:
raise ServerError(
"failed to delete alias {} for place {}".format(alias, place.name)
)
return res
async def set_comment(self):
"""Set the comment on a place"""
place = self.get_place()
comment = ' '.join(self.args.comment)
res = await self.call(
'org.labgrid.coordinator.set_place_comment', place.name, comment
)
if not res:
raise ServerError(
"failed to set comment {} for place {}".format(comment, place.name)
)
return res
async def set_tags(self):
"""Set the tags on a place"""
place = self.get_place()
tags = {}
for pair in self.args.tags:
try:
k, v = pair.split('=')
except ValueError:
raise UserError("tag '{}' needs to match '<key>=<value>'".format(pair))
if not TAG_KEY.match(k):
raise UserError(
"tag key '{}' needs to match the rexex '{}'".format(k, TAG_KEY.pattern)
)
if not TAG_VAL.match(v):
raise UserError(
"tag value '{}' needs to match the rexex '{}'".format(v, TAG_VAL.pattern)
)
tags[k] = v
res = await self.call(
'org.labgrid.coordinator.set_place_tags', place.name, tags
)
if not res:
raise ServerError(
"failed to set tags {} for place {}".format(' '.join(self.args.tags), place.name)
)
return res
async def add_match(self):
"""Add a match for a place, making fuzzy matching available to the
client"""
place = self.get_idle_place()
if place.acquired:
raise UserError("can not change acquired place {}".format(place.name))
for pattern in self.args.patterns:
if pattern in map(repr, place.matches):
print("pattern '{}' exists, skipping".format(pattern))
continue
if not 2 <= pattern.count("/") <= 3:
raise UserError(
"invalid pattern format '{}' (use 'exporter/group/cls/name')".
format(pattern)
)
res = await self.call(
'org.labgrid.coordinator.add_place_match', place.name, pattern
)
if not res:
raise ServerError(
"failed to add match {} for place {}".format(pattern, place.name)
)
async def del_match(self):
"""Delete a match for a place"""
place = self.get_idle_place()
if place.acquired:
raise UserError("can not change acquired place {}".format(place.name))
for pattern in self.args.patterns:
if pattern not in map(repr, place.matches):
print("pattern '{}' not found, skipping".format(pattern))
continue
if not 2 <= pattern.count("/") <= 3:
raise UserError(
"invalid pattern format '{}' (use 'exporter/group/cls/name')".
format(pattern)
)
res = await self.call(
'org.labgrid.coordinator.del_place_match', place.name, pattern
)
if not res:
raise ServerError(
"failed to delete match {} for place {}".
format(pattern, place.name)
)
async def add_named_match(self):
"""Add a named match for a place.
Fuzzy matching is not allowed to avoid accidental names conflicts."""
place = self.get_idle_place()
if place.acquired:
raise UserError("can not change acquired place {}".format(place.name))
pattern = self.args.pattern
name = self.args.name
if pattern in map(repr, place.matches):
raise UserError("pattern '{}' exists".format(pattern))
if not 2 <= pattern.count("/") <= 3:
raise UserError(
"invalid pattern format '{}' (use 'exporter/group/cls/name')".
format(pattern)
)
if '*' in pattern:
raise UserError(
"invalid pattern '{}' ('*' not allowed for named matches)".
format(pattern)
)
if not name:
raise UserError(
"invalid name '{}'".
format(name)
)
res = await self.call(
'org.labgrid.coordinator.add_place_match', place.name, pattern, name
)
if not res:
raise ServerError(
"failed to add match {} for place {}".format(pattern, place.name)
)
async def acquire(self):
"""Acquire a place, marking it unavailable for other clients"""
place = self.get_place()
if place.acquired:
raise UserError(
"place {} is already acquired by {}".
format(place.name, place.acquired)
)
res = await self.call(
'org.labgrid.coordinator.acquire_place', place.name
)
if res:
print("acquired place {}".format(place.name))
return
# check potential failure causes
for exporter, groups in sorted(self.resources.items()):
for group_name, group in sorted(groups.items()):
for resource_name, resource in sorted(group.items()):
resource_path = (exporter, group_name, resource.cls, resource_name)
if resource.acquired is None:
continue
match = place.getmatch(resource_path)
if match is None:
continue
name = resource_name
if match.rename:
name = match.rename
print("Matching resource '{}' ({}/{}/{}/{}) already acquired by place '{}'"
.format(name, exporter, group_name, resource.cls, resource_name,
resource.acquired))
raise ServerError("failed to acquire place {}".format(place.name))
async def release(self):
"""Release a previously acquired place"""
place = self.get_place()
if not place.acquired:
raise UserError("place {} is not acquired".format(place.name))
_, user = place.acquired.split('/')
if user != getuser():
if not self.args.kick:
raise UserError("place {} is acquired by a different user ({}), use --kick if you are sure".format(place.name, place.acquired)) # pylint: disable=line-too-long
print("warning: kicking user ({})".format(place.acquired))
res = await self.call(
'org.labgrid.coordinator.release_place', place.name
)
if not res:
raise ServerError("failed to release place {}".format(place.name))
print("released place {}".format(place.name))
async def allow(self):
"""Allow another use access to a previously acquired place"""
place = self.get_place()
if not place.acquired:
raise UserError("place {} is not acquired".format(place.name))
_, user = place.acquired.split('/')
if user != getuser():
raise UserError(
"place {} is acquired by a different user ({})".format(place.name, place.acquired)
)
if not '/' in self.args.user:
raise UserError(
"user {} must be in <host>/<username> format".format(self.args.user)
)
res = await self.call('org.labgrid.coordinator.allow_place', place.name, self.args.user)
if not res:
raise ServerError("failed to allow {} for place {}".format(self.args.user, place.name))
print("allowed {} for place {}".format(self.args.user, place.name))
def get_target_resources(self, place):
self._check_allowed(place)
resources = {}
for resource_path in place.acquired_resources:
match = place.getmatch(resource_path)
(exporter, group_name, _, resource_name) = resource_path
name = resource_name
if match.rename:
name = match.rename
resources[name] = self.resources[exporter][group_name][resource_name]
return resources
def get_target_config(self, place):
config = {}
resources = config['resources'] = []
for name, resource in self.get_target_resources(place).items():
args = OrderedDict()
if name != resource.cls:
args['name'] = name
args.update(resource.args)
resources.append({resource.cls: args})
return config
def print_env(self):
place = self.get_acquired_place()
env = {'targets': {place.name: self.get_target_config(place)}}
print(dump(env))
def _prepare_manager(self):
manager = RemotePlaceManager.get()
manager.session = self
manager.loop = self.loop
def _get_target(self, place):
self._prepare_manager()
target = None
if self.env:
target = self.env.get_target(self.role)
if target:
if self.args.state:
if self.args.verbose >= 2:
from labgrid.stepreporter import StepReporter
StepReporter()
from labgrid.strategy import Strategy
from labgrid.driver import SerialDriver
strategy = target.get_driver(Strategy)
print("Transitioning into state {}".format(self.args.state))
strategy.transition(self.args.state)
serial = target.get_active_driver(SerialDriver)
target.deactivate(serial)
else:
target = Target(place.name, env=self.env)
RemotePlace(target, name=place.name)
return target
def power(self):
place = self.get_acquired_place()
action = self.args.action
delay = self.args.delay
target = self._get_target(place)
from ..driver.powerdriver import NetworkPowerDriver, PDUDaemonDriver, USBPowerDriver
from ..resource.power import NetworkPowerPort, PDUDaemonPort
from ..resource.remote import NetworkUSBPowerPort
drv = None
for resource in target.resources:
if isinstance(resource, NetworkPowerPort):
try:
drv = target.get_driver(NetworkPowerDriver)
except NoDriverFoundError:
drv = NetworkPowerDriver(target, name=None, delay=delay)
break
elif isinstance(resource, NetworkUSBPowerPort):
try:
drv = target.get_driver(USBPowerDriver)
except NoDriverFoundError:
drv = USBPowerDriver(target, name=None, delay=delay)
break
elif isinstance(resource, PDUDaemonPort):
try:
drv = target.get_driver(PDUDaemonDriver)
except NoDriverFoundError:
drv = PDUDaemonDriver(target, name=None, delay=int(delay))
break
if not drv:
raise UserError("target has no compatible resource available")
target.activate(drv)
res = getattr(drv, action)()
if action == 'get':
print(
"power for place {} is {}".format(
place.name,
'on' if res else 'off',
)
)
def digital_io(self):
place = self.get_acquired_place()
action = self.args.action
name = self.args.name
target = self._get_target(place)
from ..resource.modbus import ModbusTCPCoil
from ..resource.onewireport import OneWirePIO
from ..resource.remote import NetworkDeditecRelais8
from ..resource.remote import NetworkSysfsGPIO
from ..driver.modbusdriver import ModbusCoilDriver
from ..driver.onewiredriver import OneWirePIODriver
from ..driver.deditecrelaisdriver import DeditecRelaisDriver
from ..driver.gpiodriver import GpioDigitalOutputDriver
drv = None
for resource in target.resources:
if isinstance(resource, ModbusTCPCoil):
try:
drv = target.get_driver(ModbusCoilDriver, name=name)
except NoDriverFoundError:
target.set_binding_map({"coil": name})
drv = ModbusCoilDriver(target, name=name)
break
elif isinstance(resource, OneWirePIO):
try:
drv = target.get_driver(OneWirePIODriver, name=name)
except NoDriverFoundError:
target.set_binding_map({"port": name})
drv = OneWirePIODriver(target, name=name)
break
elif isinstance(resource, NetworkDeditecRelais8):
try:
drv = target.get_driver(DeditecRelaisDriver, name=name)
except NoDriverFoundError:
target.set_binding_map({"relais": name})
drv = DeditecRelaisDriver(target, name=name)
break
elif isinstance(resource, NetworkSysfsGPIO):
try:
drv = target.get_driver(GpioDigitalOutputDriver, name=name)
except NoDriverFoundError:
target.set_binding_map({"gpio": name})
drv = GpioDigitalOutputDriver(target, name=name)
break
if not drv:
raise UserError("target has no compatible resource available")
target.activate(drv)
if action == 'get':
print("digital IO {} for place {} is {}".format(
name, place.name, 'high' if drv.get() else 'low'))
elif action == 'high':
drv.set(True)
elif action == 'low':
drv.set(False)
async def _console(self, place, target):
name = self.args.name
from ..resource import NetworkSerialPort
resource = target.get_resource(NetworkSerialPort, name=name)
host, port = proxymanager.get_host_and_port(resource)
# check for valid resources
assert port is not None, "Port is not set"
call = [
'microcom', '-s', str(resource.speed), '-t',
"{}:{}".format(host, port)
]
print("connecting to {} calling {}".format(resource, " ".join(call)))
try:
p = await asyncio.create_subprocess_exec(*call)
except FileNotFoundError as e:
raise ServerError("failed to execute microcom: {}".format(e))
while p.returncode is None:
try:
await asyncio.wait_for(p.wait(), 1.0)
except asyncio.TimeoutError:
# subprocess is still running
pass
try:
self._check_allowed(place)
except UserError:
p.terminate()
try:
await asyncio.wait_for(p.wait(), 1.0)
except asyncio.TimeoutError:
# try harder
p.kill()
await asyncio.wait_for(p.wait(), 1.0)
raise
if p.returncode:
print("connection lost")
return False
return True
async def console(self, place, target):
while True:
res = await self._console(place, target)
if res:
break
if not self.args.loop:
break
await asyncio.sleep(1.0)
console.needs_target = True
def fastboot(self):
place = self.get_acquired_place()
args = self.args.fastboot_args
if not args:
raise UserError("not enough arguments for fastboot")
if args[0] == 'flash':
if len(args) < 3:
raise UserError("not enough arguments for fastboot flash")
args[2] = os.path.abspath(args[2])
elif args[0] == 'boot':
if len(args) < 2:
raise UserError("not enough arguments for fastboot boot")
args[1:] = map(os.path.abspath, args[1:])
target = self._get_target(place)
from ..driver.fastbootdriver import AndroidFastbootDriver
try:
drv = target.get_driver(AndroidFastbootDriver)
except NoDriverFoundError:
drv = AndroidFastbootDriver(target, name=None)
drv.fastboot.timeout = self.args.wait
target.activate(drv)
if args[0] == 'flash':
drv.flash(args[1], args[2])
return
if args[0] == 'boot':
drv.boot(args[1])
return
if args[0:2] == ['oem', 'exec']:
drv.run(" ".join(args[2:]))
return
drv(*args)
def bootstrap(self):
place = self.get_acquired_place()
args = self.args.filename
target = self._get_target(place)
from ..protocol.bootstrapprotocol import BootstrapProtocol
from ..driver.usbloader import IMXUSBDriver, MXSUSBDriver, RKUSBDriver
from ..driver.openocddriver import OpenOCDDriver
from ..resource.remote import (NetworkMXSUSBLoader, NetworkIMXUSBLoader, NetworkRKUSBLoader,
NetworkAlteraUSBBlaster)
drv = None
try:
drv = target.get_driver(BootstrapProtocol)
except NoDriverFoundError:
for resource in target.resources:
if isinstance(resource, NetworkIMXUSBLoader):
try:
drv = target.get_driver(IMXUSBDriver)
except NoDriverFoundError:
drv = IMXUSBDriver(target, name=None)
drv.loader.timeout = self.args.wait
break
elif isinstance(resource, NetworkMXSUSBLoader):
try:
drv = target.get_driver(MXSUSBDriver)
except NoDriverFoundError:
drv = MXSUSBDriver(target, name=None)
drv.loader.timeout = self.args.wait
break
elif isinstance(resource, NetworkAlteraUSBBlaster):
args = dict(arg.split('=', 1) for arg in self.args.bootstrap_args)
try:
drv = target.get_driver(OpenOCDDriver)
except NoDriverFoundError:
drv = OpenOCDDriver(target, name=None, **args)
drv.interface.timeout = self.args.wait
break
elif isinstance(resource, NetworkRKUSBLoader):
try:
drv = target.get_driver(RKUSBDriver)
except NoDriverFoundError:
drv = RKUSBDriver(target, name=None)
drv.loader.timeout = self.args.wait
break
if not drv:
raise UserError("target has no compatible resource available")
target.activate(drv)
drv.load(self.args.filename)
def sd_mux(self):
place = self.get_acquired_place()
action = self.args.action
target = self._get_target(place)
from ..driver.usbsdmuxdriver import USBSDMuxDriver
from ..resource.remote import NetworkUSBSDMuxDevice
drv = None
for resource in target.resources:
if isinstance(resource, NetworkUSBSDMuxDevice):
try:
drv = target.get_driver(USBSDMuxDriver)
except NoDriverFoundError:
drv = USBSDMuxDriver(target, name=None)
break
if not drv:
raise UserError("target has no compatible resource available")
target.activate(drv)
drv.set_mode(action)
def _get_ip(self, place):
target = self._get_target(place)
from ..resource import EthernetPort, NetworkService
try:
resource = target.get_resource(EthernetPort)
except NoResourceFoundError:
resource = target.get_resource(NetworkService)
return resource.address
matches = []
for details in resource.extra.get('macs').values():
ips = details.get('ips', [])
if not ips:
continue
matches.append((details['timestamp'], ips))
matches.sort()
newest = matches[-1][1]
if len(ips) > 1:
print("multiple IPs found: {}".format(ips))
return None
return newest[0]
def ssh(self):
from ..resource import NetworkService
place = self.get_acquired_place()
ip = self._get_ip(place)
if not ip:
return
target = self._get_target(place)
env = os.environ.copy()
try:
resource = target.get_resource(NetworkService)
username = resource.username
port = resource.port or 22
# use sshpass if we have a password
if resource.password:
env['SSHPASS'] = resource.password
sshpass = ['sshpass', '-e'] if resource.password else []
except NoResourceFoundError:
username = 'root'
sshpass = []
port = 22
args = sshpass + [
'ssh',
'-l', username,
'-p', str(port),
'-o', 'StrictHostKeyChecking no',
'-o', 'UserKnownHostsFile /dev/null',
str(ip),
] + self.args.leftover
print('Note: Using dummy known hosts file.')
res = subprocess.run(args, env=env)
if res:
print("connection lost")
def telnet(self):
place = self.get_acquired_place()
ip = self._get_ip(place)
if not ip:
return
args = ['telnet', str(ip)]
res = subprocess.call(args)
if res:
print("connection lost")