forked from vast-ai/vast-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvast.py
executable file
·1621 lines (1386 loc) · 59.1 KB
/
vast.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
from __future__ import unicode_literals, print_function
import re
import json
import sys
import argparse
import os
import time
import typing
from datetime import date, datetime
import requests
import getpass
import subprocess
from subprocess import PIPE
try:
from urllib import quote_plus # Python 2.X
except ImportError:
from urllib.parse import quote_plus # Python 3+
try:
JSONDecodeError = json.JSONDecodeError
except AttributeError:
JSONDecodeError = ValueError
try:
input = raw_input
except NameError:
pass
server_url_default = "https://vast.ai"
#server_url_default = "https://vast.ai/api/v0"
api_key_file_base = "~/.vast_api_key"
api_key_file = os.path.expanduser(api_key_file_base)
api_key_guard = object()
class Object(object):
pass
class argument(object):
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
class hidden_aliases(object):
# just a bit of a hack
def __init__(self, l):
self.l = l
def __iter__(self):
return iter(self.l)
def __bool__(self):
return False
def __nonzero__(self):
return False
def append(self, x):
self.l.append(x)
class apwrap(object):
def __init__(self, *args, **kwargs):
kwargs["formatter_class"] = argparse.RawDescriptionHelpFormatter
self.parser = argparse.ArgumentParser(*args, **kwargs)
self.parser.set_defaults(func=self.fail_with_help)
self.subparsers_ = None
self.subparser_objs = []
self.added_help_cmd = False
self.post_setup = []
self.verbs = set()
self.objs = set()
def fail_with_help(self, *a, **kw):
self.parser.print_help(sys.stderr)
raise SystemExit
def add_argument(self, *a, **kw):
if not kw.get("parent_only"):
for x in self.subparser_objs:
try:
x.add_argument(*a, **kw)
except argparse.ArgumentError:
# duplicate - or maybe other things, hopefully not
pass
return self.parser.add_argument(*a, **kw)
def subparsers(self, *a, **kw):
if self.subparsers_ is None:
kw["metavar"] = "command"
kw["help"] = "command to run. one of:"
self.subparsers_ = self.parser.add_subparsers(*a, **kw)
return self.subparsers_
def get_name(self, verb, obj):
if obj:
self.verbs.add(verb)
self.objs.add(obj)
name = verb + ' ' + obj
else:
self.objs.add(verb)
name = verb
return name
def command(self, *arguments, aliases=(), help=None, **kwargs):
help_ = help
if not self.added_help_cmd:
self.added_help_cmd = True
@self.command(argument("subcommand", default=None, nargs="?"), help="print this help message")
def help(*a, **kw):
self.fail_with_help()
def inner(func):
dashed_name = func.__name__.replace("_", "-")
verb, _, obj = dashed_name.partition("--")
name = self.get_name(verb, obj)
aliases_transformed = [] if aliases else hidden_aliases([])
for x in aliases:
verb, _, obj = x.partition(" ")
aliases_transformed.append(self.get_name(verb, obj))
kwargs["formatter_class"] = argparse.RawDescriptionHelpFormatter
sp = self.subparsers().add_parser(name, aliases=aliases_transformed, help=help_, **kwargs)
self.subparser_objs.append(sp)
for arg in arguments:
sp.add_argument(*arg.args, **arg.kwargs)
sp.set_defaults(func=func)
return func
if len(arguments) == 1 and type(arguments[0]) != argument:
func = arguments[0]
arguments = []
return inner(func)
return inner
def parse_args(self, argv=None, *a, **kw):
if argv is None:
argv = sys.argv[1:]
argv_ = []
for x in argv:
if argv_ and argv_[-1] in self.verbs:
argv_[-1] += " " + x
else:
argv_.append(x)
args = self.parser.parse_args(argv_, *a, **kw)
for func in self.post_setup:
func(args)
return args
parser = apwrap(epilog="Use 'vast COMMAND --help' for more info about a command")
def translate_null_strings_to_blanks(d: typing.Dict) -> typing.Dict:
"""Map over a dict and translate any null string values into ' '.
Leave everything else as is. This is needed because you cannot add TableCell
objects with only a null string or the client crashes.
:param Dict d: dict of item values.
:rtype Dict:
"""
# Beware: locally defined function.
def translate_nulls(s):
if s == "":
return " "
return s
new_d = {k: translate_nulls(v) for k, v in d.items()}
return new_d
def apiurl(args: argparse.Namespace, subpath: str, query_args: typing.Dict = None) -> str:
"""Creates the endpoint URL for a given combination of parameters.
:param argparse.Namespace args: Namespace with many fields relevant to the endpoint.
:param str subpath: added to end of URL to further specify endpoint.
:param typing.Dict query_args: specifics such as API key and search parameters that complete the URL.
:rtype str:
"""
if query_args is None:
query_args = {}
if args.api_key is not None:
query_args["api_key"] = args.api_key
if query_args:
# a_list = [<expression> for <l-expression> in <expression>]
'''
vector result;
for (l_expression: expression) {
result.push_back(expression);
}
'''
# an_iterator = (<expression> for <l-expression> in <expression>)
return args.url + "/api/v0" + subpath + "?" + "&".join(
"{x}={y}".format(x=x, y=quote_plus(y if isinstance(y, str) else json.dumps(y))) for x, y in
query_args.items())
else:
return args.url + "/api/v0" + subpath
def deindent(message: str) -> str:
"""
Deindent a quoted string. Scans message and finds the smallest number of whitespace characters in any line and
removes that many from the start of every line.
:param str message: Message to deindent.
:rtype str:
"""
message = re.sub(r" *$", "", message, flags=re.MULTILINE)
indents = [len(x) for x in re.findall("^ *(?=[^ ])", message, re.MULTILINE) if len(x)]
a = min(indents)
message = re.sub(r"^ {," + str(a) + "}", "", message, flags=re.MULTILINE)
return message.strip()
# These are the fields that are displayed when a search is run
displayable_fields = (
# ("bw_nvlink", "Bandwidth NVLink", "{}", None, True),
("id", "ID", "{}", None, True),
("cuda_max_good", "CUDA", "{:0.1f}", None, True),
("num_gpus", "Num", "{}x", None, False),
("gpu_name", "Model", "{}", None, True),
("pcie_bw", "PCIE_BW", "{:0.1f}", None, True),
("cpu_cores_effective", "vCPUs", "{:0.1f}", None, True),
("cpu_ram", "RAM", "{:0.1f}", lambda x: x / 1000, False),
("disk_space", "Storage", "{:.0f}", None, True),
("dph_total", "$/hr", "{:0.4f}", None, True),
("dlperf", "DLPerf", "{:0.1f}", None, True),
("dlperf_per_dphtotal", "DLP/$", "{:0.1f}", None, True),
("driver_version", "Nvidia Driver Version", "{}", None, True),
("inet_up", "Net_up", "{:0.1f}", None, True),
("inet_down", "Net_down", "{:0.1f}", None, True),
("reliability2", "R", "{:0.1f}", lambda x: x * 100, True),
("duration", "Max_Days", "{:0.1f}", lambda x: x / (24.0 * 60.0 * 60.0), True),
("machine_id", "machine_id", "{}", None, True),
# ("direct_port_count", "Direct Port Count", "{}", None, True),
)
# Need to add bw_nvlink, machine_id, direct_port_count to output.
# These fields are displayed when you do 'show instances'
instance_fields = (
("id", "ID", "{}", None, True),
("machine_id", "Machine", "{}", None, True),
("actual_status", "Status", "{}", None, True),
("num_gpus", "Num", "{}x", None, False),
("gpu_name", "Model", "{}", None, True),
("gpu_util", "Util. %", "{:0.1f}", None, True),
("cpu_cores_effective", "vCPUs", "{:0.1f}", None, True),
("cpu_ram", "RAM", "{:0.1f}", lambda x: x / 1000, False),
("disk_space", "Storage", "{:.0f}", None, True),
("ssh_host", "SSH Addr", "{}", None, True),
("ssh_port", "SSH Port", "{}", None, True),
("dph_total", "$/hr", "{:0.4f}", None, True),
("image_uuid", "Image", "{}", None, True),
# ("dlperf", "DLPerf", "{:0.1f}", None, True),
# ("dlperf_per_dphtotal", "DLP/$", "{:0.1f}", None, True),
("inet_up", "Net up", "{:0.1f}", None, True),
("inet_down", "Net down", "{:0.1f}", None, True),
("reliability2", "R", "{:0.1f}", lambda x: x * 100, True),
("label", "Label", "{}", None, True)
# ("duration", "Max Days", "{:0.1f}", lambda x: x/(24.0*60.0*60.0), True),
)
invoice_fields = (
("amount", "Amount", "{}", None, True),
("description", "Description", "{}", None, True),
("quantity", "Quantity", "{}", None, True),
("rate", "Rate", "{}", None, True),
("timestamp", "Timestamp", "{:0.1f}", None, True),
("type", "Type", "{}", None, True)
)
user_fields = (
# ("api_key", "api_key", "{}", None, True),
("balance", "Balance", "{}", None, True),
("balance_threshold", "Bal. Thld", "{}", None, True),
("balance_threshold_enabled", "Bal. Thld Enabled", "{}", None, True),
("billaddress_city", "City", "{}", None, True),
("billaddress_country", "Country", "{}", None, True),
("billaddress_line1", "Addr Line 1", "{}", None, True),
("billaddress_line2", "Addr line 2", "{}", None, True),
("billaddress_zip", "Zip", "{}", None, True),
("billed_expected", "Billed Expected", "{}", None, True),
("billed_verified", "Billed Vfy", "{}", None, True),
("billing_creditonly", "Billing Creditonly", "{}", None, True),
("can_pay", "Can Pay", "{}", None, True),
("credit", "Credit", "{:0.2f}", None, True),
("email", "Email", "{}", None, True),
("email_verified", "Email Vfy", "{}", None, True),
("fullname", "Full Name", "{}", None, True),
("got_signup_credit", "Got Signup Credit", "{}", None, True),
("has_billing", "Has Billing", "{}", None, True),
("has_payout", "Has Payout", "{}", None, True),
("id", "Id", "{}", None, True),
("last4", "Last4", "{}", None, True),
("paid_expected", "Paid Expected", "{}", None, True),
("paid_verified", "Paid Vfy", "{}", None, True),
("password_resettable", "Pwd Resettable", "{}", None, True),
("paypal_email", "Paypal Email", "{}", None, True),
("ssh_key", "Ssh Key", "{}", None, True),
("user", "User", "{}", None, True),
("username", "Username", "{}", None, True)
)
def version_string_sort(a, b) -> int:
"""
Accepts two version strings and decides whether a > b, a == b, or a < b.
This is meant as a sort function to be used for the driver versions in which only
the == operator currently works correctly. Not quite finished...
:param str a:
:param str b:
:return int:
"""
a_parts = a.split(".")
b_parts = b.split(".")
return 0
def parse_query(query_str: str, res: typing.Dict = None) -> typing.Dict:
"""
Basically takes a query string (like the ones in the examples of commands for the search__offers function) and
processes it into a dict of URL parameters to be sent to the server.
:param str query_str:
:param Dict res:
:return Dict:
"""
if res is None: res = {}
if type(query_str) == list:
query_str = " ".join(query_str)
query_str = query_str.strip()
opts = re.findall(
"([a-zA-Z0-9_]+)( *[=><!]+| +(?:[lg]te?|nin|neq|eq|not ?eq|not ?in|in) )?( *)(\[[^\]]+\]|[^ ]+)?( *)",
query_str)
# res = {}
op_names = {
">=": "gte",
">": "gt",
"gt": "gt",
"gte": "gte",
"<=": "lte",
"<": "lt",
"lt": "lt",
"lte": "lte",
"!=": "neq",
"==": "eq",
"=": "eq",
"eq": "eq",
"neq": "neq",
"noteq": "neq",
"not eq": "neq",
"notin": "notin",
"not in": "notin",
"nin": "notin",
"in": "in",
};
field_alias = {
"cuda_vers": "cuda_max_good",
"display_active": "gpu_display_active",
"reliability": "reliability2",
"dlperf_usd": "dlperf_per_dphtotal",
"dph": "dph_total",
"flops_usd": "flops_per_dphtotal",
};
field_multiplier = {
"cpu_ram": 1000,
"gpu_ram": 1000,
"duration": 1.0 / (24.0 * 60.0 * 60.0),
}
fields = {
"bw_nvlink",
"compute_cap",
"cpu_cores",
"cpu_cores_effective",
"cpu_ram",
"cuda_max_good",
"direct_port_count",
"driver_version",
"disk_bw",
"disk_space",
"dlperf",
"dlperf_per_dphtotal",
"dph_total",
"duration",
"external",
"flops_per_dphtotal",
"gpu_display_active",
# "gpu_ram_free_min",
"gpu_mem_bw",
"gpu_name",
"gpu_ram",
"has_avx",
"host_id",
"id",
"inet_down",
"inet_down_cost",
"inet_up",
"inet_up_cost",
"machine_id",
"min_bid",
"mobo_name",
"num_gpus",
"pci_gen",
"pcie_bw",
"reliability2",
"rentable",
"rented",
"storage_cost",
"total_flops",
"verified",
};
joined = "".join("".join(x) for x in opts)
if joined != query_str:
raise ValueError(
"Unconsumed text. Did you forget to quote your query? " + repr(joined) + " != " + repr(query_str))
for field, op, _, value, _ in opts:
value = value.strip(",[]")
v = res.setdefault(field, {})
op = op.strip()
op_name = op_names.get(op)
if field in field_alias:
field = field_alias[field];
if not field in fields:
print("Warning: Unrecognized field: {}, see list of recognized fields.".format(field), file=sys.stderr);
if not op_name:
raise ValueError("Unknown operator. Did you forget to quote your query? " + repr(op).strip("u"))
if op_name in ["in", "notin"]:
value = [x.strip() for x in value.split(",") if x.strip()]
if not value:
raise ValueError("Value cannot be blank. Did you forget to quote your query? " + repr((field, op, value)))
if not field:
raise ValueError("Field cannot be blank. Did you forget to quote your query? " + repr((field, op, value)))
if value in ["?", "*", "any"]:
if op_name != "eq":
raise ValueError("Wildcard only makes sense with equals.")
if field in v:
del v[field]
if field in res:
del res[field]
continue
if field in field_multiplier:
value = str(float(value) * field_multiplier[field]);
v[op_name] = value
res[field] = v;
return res
def display_table(rows: list, fields: typing.Tuple) -> None:
"""Basically takes a set of field names and rows containing the corresponding data and prints a nice tidy table
of it.
:param list rows: Each row is a dict with keys corresponding to the field names (first element) in the fields tuple.
:param Tuple fields: 5-tuple describing a field. First element is field name, second is human readable version, third is format string, fourth is a lambda function run on the data in that field, fifth is a bool determining text justification. True = left justify, False = right justify. Here is an example showing the tuples in action.
:rtype None:
Example of 5-tuple: ("cpu_ram", "RAM", "{:0.1f}", lambda x: x / 1000, False)
"""
header = [name for _, name, _, _, _ in fields]
out_rows = [header]
lengths = [len(x) for x in header]
for instance in rows:
row = []
out_rows.append(row)
for key, name, fmt, conv, _ in fields:
conv = conv or (lambda x: x)
val = instance.get(key, None)
if val is None:
s = "-"
else:
val = conv(val)
s = fmt.format(val)
s = s.replace(' ', '_')
idx = len(row)
lengths[idx] = max(len(s), lengths[idx])
row.append(s)
for row in out_rows:
out = []
for l, s, f in zip(lengths, row, fields):
_, _, _, _, ljust = f
if ljust:
s = s.ljust(l)
else:
s = s.rjust(l)
out.append(s)
print(" ".join(out))
class VRLException(Exception):
pass
def parse_vast_url(url_str):
"""
Breaks up a vast-style url in the form instance_id:path and does
some basic sanity type-checking.
:param url_str:
:return:
"""
instance_id = None
path = url_str
if (":" in url_str):
url_parts = url_str.split(":", 2)
if len(url_parts) == 2:
(instance_id, path) = url_parts
else:
raise VRLException("Invalid VRL (Vast resource locator).")
try:
instance_id = int(instance_id)
except:
raise VRLException("Instance id must be an integer.")
valid_unix_path_regex = re.compile('^(/)?([^/\0]+(/)?)+$')
# Got this regex from https://stackoverflow.com/questions/537772/what-is-the-most-correct-regular-expression-for-a-unix-file-path
if (path != "/") and (valid_unix_path_regex.match(path) is None):
raise VRLException(f"Path component: {path} of VRL is not a valid Unix style path.")
return (instance_id, path)
@parser.command(
argument("src", help="instance_id:/path to source of object to copy.", type=str),
argument("dst", help="instance_id:/path to target of copy operation.", type=str),
argument("-i", "--identity", help="Location of ssh private key", type=str),
usage="./vast copy src dst",
help=" Copy directories between instances and/or local",
epilog=deindent("""
Copies a directory from a source location to a target location. Each of source and destination
directories can be either local or remote, subject to appropriate read and write
permissions required to carry out the action. The format for both src and dst is [instance_id:]path.
Examples:
vast copy 11824:/data/test 12371:/temp
vast copy 11824:/data/test data/test
vast copy data/test 11824:/data/test
The first example copy syncs the directory '/tmp' in instance 12371 from the directory '/data/test' in instance 11824.
The second example copy syncs the relative directory 'data/test' on the local machine from '/data/test' in instance 11824.
The third example copy syncs the directory '/data/test' in instance 11824 from the relative directory 'data/test' on the local machine.
"""),
)
def copy(args: argparse.Namespace):
"""
Transfer data from one instance to another.
@param src: Location of data object to be copied.
@param dst: Target to copy object to.
"""
url = apiurl(args, f"/commands/rsync/")
(src_id, src_path) = parse_vast_url(args.src)
(dst_id, dst_path) = parse_vast_url(args.dst)
if (src_id is None) and (dst_id is None):
print("invalid arguments")
return
print(f"copying {src_id}:{src_path} {dst_id}:{dst_path}")
req_json = {
"client_id": "me",
"src_id": src_id,
"dst_id": dst_id,
"src_path": src_path,
"dst_path": dst_path,
}
r = requests.put(url, json=req_json)
r.raise_for_status()
if (r.status_code == 200):
rj = r.json();
#print(json.dumps(rj, indent=1, sort_keys=True))
if (rj["success"]) and ((src_id is None) or (dst_id is None)):
homedir = subprocess.getoutput("echo $HOME")
#print(f"homedir: {homedir}")
remote_port = None
identity = args.identity if (args.identity is not None) else f"{homedir}/.ssh/id_rsa"
if (src_id is None):
#result = subprocess.run(f"mkdir -p {src_path}", shell=True)
remote_port = rj["dst_port"]
remote_addr = rj["dst_addr"]
cmd = f"sudo rsync -arz -v --progress --rsh=ssh -e 'sudo ssh -i {identity} -p {remote_port} -o StrictHostKeyChecking=no' {src_path} vastai_kaalia@{remote_addr}::{dst_id}/{dst_path}"
print(cmd)
result = subprocess.run(cmd, shell=True)
#result = subprocess.run(["sudo", "rsync" "-arz", "-v", "--progress", "-rsh=ssh", "-e 'sudo ssh -i {homedir}/.ssh/id_rsa -p {remote_port} -o StrictHostKeyChecking=no'", src_path, "vastai_kaalia@{remote_addr}::{dst_id}"], shell=True)
elif (dst_id is None):
result = subprocess.run(f"mkdir -p {dst_path}", shell=True)
remote_port = rj["src_port"]
remote_addr = rj["src_addr"]
cmd = f"sudo rsync -arz -v --progress --rsh=ssh -e 'sudo ssh -i {identity} -p {remote_port} -o StrictHostKeyChecking=no' vastai_kaalia@{remote_addr}::{src_id}/{src_path} {dst_path}"
print(cmd)
result = subprocess.run(cmd, shell=True)
#result = subprocess.run(["sudo", "rsync" "-arz", "-v", "--progress", "-rsh=ssh", "-e 'sudo ssh -i {homedir}/.ssh/id_rsa -p {remote_port} -o StrictHostKeyChecking=no'", "vastai_kaalia@{remote_addr}::{src_id}", dst_path], shell=True)
else:
if (rj["success"]):
print("Remote to Remote copy initiated - check instance status bar for progress updates (~30 seconds delayed).")
else:
print(rj["msg"]);
else:
print(r.text);
print("failed with error {r.status_code}".format(**locals()));
@parser.command(
argument("-t", "--type", default="on-demand", help="Show 'bid'(interruptible) or 'on-demand' offers. default: on-demand"),
argument("-i", "--interruptible", dest="type", const="bid", action="store_const", help="Alias for --type=bid"),
argument("-b", "--bid", dest="type", const="bid", action="store_const", help="Alias for --type=bid"),
argument("-d", "--on-demand", dest="type", const="on-demand", action="store_const", help="Alias for --type=on-demand"),
argument("-n", "--no-default", action="store_true", help="Disable default query"),
argument("--disable-bundling", action="store_true", help="Show identical offers. This request is more heavily rate limited."),
argument("--storage", type=float, default=5.0, help="Amount of storage to use for pricing, in GiB. default=5.0GiB"),
argument("-o", "--order", type=str, help="Comma-separated list of fields to sort on. postfix field with - to sort desc. ex: -o 'num_gpus,total_flops-'. default='score-'", default='score-'),
argument("query", help="Query to search for. default: 'external=false rentable=true verified=true', pass -n to ignore default", nargs="*", default=None),
usage="./vast search offers [--help] [--api-key API_KEY] [--raw] <query>",
help="Search for instance types using custom query",
epilog=deindent("""
Query syntax:
query = comparison comparison...
comparison = field op value
field = <name of a field>
op = one of: <, <=, ==, !=, >=, >, in, notin
value = <bool, int, float, etc> | 'any'
note: to pass '>' and '<' on the command line, make sure to use quotes
Examples:
./vast search offers 'compute_cap > 610 total_flops < 5'
./vast search offers 'reliability > 0.99 num_gpus>=4' -o 'num_gpus-'
./vast search offers 'rentable = any'
Available fields:
Name Type Description
bw_nvlink float bandwidth NVLink
compute_cap: int cuda compute capability*100 (ie: 650 for 6.5, 700 for 7.0)
cpu_cores: int # virtual cpus
cpu_cores_effective: float # virtual cpus you get
cpu_ram: float system RAM in gigabytes
cuda_vers: float cuda version
direct_port_count int open ports on host's router
disk_bw: float disk read bandwidth, in MB/s
disk_space: float disk storage space, in GB
dlperf: float DL-perf score (see FAQ for explanation)
dlperf_usd: float DL-perf/$
dph: float $/hour rental cost
driver_version string driver version in use on a host.
duration: float max rental duration in days
external: bool show external offers
flops_usd: float TFLOPs/$
gpu_mem_bw: float GPU memory bandwidth in GB/s
gpu_ram: float GPU RAM in GB
gpu_frac: float Ratio of GPUs in the offer to gpus in the system
has_avx: bool CPU supports AVX instruction set.
id: int instance unique ID
inet_down: float internet download speed in Mb/s
inet_down_cost: float internet download bandwidth cost in $/GB
inet_up: float internet upload speed in Mb/s
inet_up_cost: float internet upload bandwidth cost in $/GB
machine_id int machine id of instance
min_bid: float current minimum bid price in $/hr for interruptible
num_gpus: int # of GPUs
pci_gen: float PCIE generation
pcie_bw: float PCIE bandwidth (CPU to GPU)
reliability: float machine reliability score (see FAQ for explanation)
rentable: bool is the instance currently rentable
rented: bool is the instance currently rented
storage_cost: float storage cost in $/GB/month
total_flops: float total TFLOPs from all GPUs
verified: bool is the machine verified
"""),
aliases=hidden_aliases(["search instances"]),
)
def search__offers(args):
"""Creates a query based on search parameters as in the examples above.
:param argparse.Namespace args: should supply all the command-line options
"""
field_alias = {
"cuda_vers": "cuda_max_good",
"reliability": "reliability2",
"dlperf_usd": "dlperf_per_dphtotal",
"dph": "dph_total",
"flops_usd": "flops_per_dphtotal",
};
try:
if args.no_default:
query = {}
else:
query = {"verified": {"eq": True}, "external": {"eq": False}, "rentable": {"eq": True}}
if args.query is not None:
query = parse_query(args.query, query)
order = []
for name in args.order.split(","):
name = name.strip()
if not name: continue
direction = "asc"
if name.strip("-") != name:
direction = "desc"
field = name.strip("-");
if field in field_alias:
field = field_alias[field];
order.append([field, direction])
query["order"] = order
query["type"] = args.type
# For backwards compatibility, support --type=interruptible option
if query["type"] == 'interruptible':
query["type"] = 'bid'
if args.disable_bundling:
query["disable_bundling"] = True
except ValueError as e:
print("Error: ", e)
return 1
url = apiurl(args, "/bundles", {"q": query})
r = requests.get(url);
r.raise_for_status()
rows = r.json()["offers"]
if args.raw:
print(json.dumps(rows, indent=1, sort_keys=True))
else:
display_table(rows, displayable_fields)
@parser.command(
usage="./vast show instances [--api-key API_KEY] [--raw]",
help="Display user's current instances"
)
def show__instances(args):
"""
Shows the stats on the machine the user is renting.
:param argparse.Namespace args: should supply all the command-line options
:rtype:
"""
req_url = apiurl(args, "/instances", {"owner": "me"});
r = requests.get(req_url);
r.raise_for_status()
rows = r.json()["instances"]
if args.raw:
print(json.dumps(rows, indent=1, sort_keys=True))
else:
display_table(rows, instance_fields)
@parser.command(
argument("--id", help="id of instance", type=int),
usage="./vast ssh-url",
help="ssh url helper",
)
def ssh_url(args):
"""
:param argparse.Namespace args: should supply all the command-line options
:rtype:
"""
return _ssh_url(args, "ssh://")
@parser.command(
argument("--id", help="id of instance", type=int),
usage="./vast scp-url",
help="scp url helper",
)
def scp_url(args):
"""
:param argparse.Namespace args: should supply all the command-line options
:rtype:
"""
return _ssh_url(args, "scp://")
def _ssh_url(args, protocol):
req_url = apiurl(args, "/instances", {"owner": "me"});
r = requests.get(req_url);
r.raise_for_status()
rows = r.json()["instances"]
if args.id:
instance, = [r for r in rows if r['id'] == args.id]
elif len(rows) > 1:
print("Found multiple running instances")
return 1
else:
instance, = rows
print(f'{protocol}root@{instance["ssh_host"]}:{instance["ssh_port"]}')
@parser.command(
argument("-q", "--quiet", action="store_true", help="only display numeric ids"),
usage="./vast show machines [OPTIONS]",
help="[Host] Show hosted machines",
)
def show__machines(args):
"""
Show the machines user is offering for rent.
:param argparse.Namespace args: should supply all the command-line options
:rtype:
"""
req_url = apiurl(args, "/machines", {"owner": "me"});
r = requests.get(req_url);
r.raise_for_status()
rows = r.json()["machines"]
if args.raw:
print(json.dumps(rows, indent=1, sort_keys=True))
else:
for machine in rows:
if args.quiet:
print("{id}".format(id=machine["id"]))
else:
print("{N} machines: ".format(N=len(rows)));
print("{id}: {json}".format(id=machine["id"], json=json.dumps(machine, indent=4, sort_keys=True)))
@parser.command(
argument("-q", "--quiet", action="store_true", help="only display numeric ids"),
argument("-s", "--start_date", help="start date and time for report. Many formats accepted (optional)", type=str),
argument("-e", "--end_date", help="end date and time for report. Many formats accepted (optional)", type=str),
argument("-c", "--only_charges", action="store_true", help="Show only charge items."),
argument("-p", "--only_credits", action="store_true", help="Show only credit items."),
usage="./vast show invoices [OPTIONS]",
help="Get billing history reports",
)
def show__invoices(args):
"""
Show current payments and charges. Various options available to limit time range and type
of items. Default is to show everything for user's entire billing history.
:param argparse.Namespace args: should supply all the command-line options
:rtype:
"""
req_url = apiurl(args, "/users/me/invoices", {"owner": "me"});
r = requests.get(req_url)
r.raise_for_status()
rows = r.json()["invoices"]
# print("Timestamp for first row: ", rows[0]["timestamp"])
invoice_filter_data = filter_invoice_items(args, rows)
rows = invoice_filter_data["rows"]
filter_header = invoice_filter_data["header_text"]
current_charges = r.json()["current"]
if args.raw:
print(json.dumps(rows, indent=1, sort_keys=True))
# print("Current: ", current_charges)
else:
print(filter_header)
display_table(rows, invoice_fields)
print("Current: ", current_charges)
@parser.command(
argument("-q", "--quiet", action="store_true", help="display information about user"),
usage="./vast show user [OPTIONS]",
help=" Get current user data"
)
def show__user(args):
"""
Shows stats for logged-in user. Does not show API key.
:param argparse.Namespace args: should supply all the command-line options
:rtype:
"""
req_url = apiurl(args, "/users/current", {"owner": "me"});
print(f"URL: {req_url}")
print("HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHh\n")
r = requests.get(req_url);
r.raise_for_status()
user_blob = r.json()
user_blob.pop("api_key")
if args.raw:
print(json.dumps(user_blob, indent=1, sort_keys=True))
else:
display_table([user_blob], user_fields)
def filter_invoice_items(args: argparse.Namespace, rows: typing.List) -> typing.Dict:
"""This applies various filters to the invoice items. Currently it filters on start and end date and applies the
'only_charge' and 'only_credits' options.invoice_number
:param argparse.Namespace args: should supply all the command-line options
:param List rows: The rows of items in the invoice
:rtype List: Returns the filtered list of rows.
"""
try:
import vast_pdf
import dateutil
from dateutil import parser
except ImportError:
print("""\nWARNING: The 'vast_pdf' library is not present. This library is used to print invoices in PDF format. If
you do not need this feature you can ignore this message. To get the library you should download the vast-python
github repository. Just do 'git@github.com:vast-ai/vast-python.git' and then 'cd vast-python'. Once in that
directory you can run 'vast.py' and it will have access to 'vast_pdf.py'. The library depends on a Python
package called Borb to make the PDF files. To install this package do 'pip3 install borb'.\n""")
try:
vast_pdf
except NameError:
vast_pdf = Object()
vast_pdf.invoice_number = -1
selector_flag = ""
end_timestamp: float = 9999999999
start_timestamp: float = 0
start_date_txt = ""
end_date_txt = ""
if args.end_date:
try:
end_date = dateutil.parser.parse(str(args.end_date))
end_date_txt = end_date.isoformat()
end_timestamp = time.mktime(end_date.timetuple())
except ValueError:
print("Warning: Invalid end date format! Ignoring end date!")
if args.start_date:
try:
start_date = dateutil.parser.parse(str(args.start_date))
start_date_txt = start_date.isoformat()
start_timestamp = time.mktime(start_date.timetuple())
except ValueError:
print("Warning: Invalid start date format! Ignoring start date!")
if args.only_charges:
type_txt = "Only showing charges."
selector_flag = "only_charges"
def type_filter_fn(row):
return True if row["type"] == "charge" else False
elif args.only_credits:
type_txt = "Only showing credits."
selector_flag = "only_credits"
def type_filter_fn(row):
return True if row["type"] == "payment" else False
else:
type_txt = ""
def type_filter_fn(row):
return True
if args.end_date:
if args.start_date:
header_text = f'Invoice items after {start_date_txt} and before {end_date_txt}.'
else:
header_text = f'Invoice items before {end_date_txt}.'
elif args.start_date:
header_text = f'Invoice items after {start_date_txt}.'
else:
header_text = " "
header_text = header_text + " " + type_txt
rows = list(filter(lambda row: end_timestamp >= row["timestamp"] >= start_timestamp
and type_filter_fn(row) and float(row["amount"]) != 0, rows))
if start_date_txt:
start_date_txt = "S:" + start_date_txt
if end_date_txt:
end_date_txt = "E:" + end_date_txt
now = date.today()