forked from vast-ai/vast-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vast.py
executable file
·4680 lines (4025 loc) · 183 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
from typing import Dict, List, Tuple
import hashlib
from datetime import date, datetime, timedelta
import math
import threading
from concurrent.futures import ThreadPoolExecutor
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://console.vast.ai"
# server_url_default = "http://localhost:5002"
#server_url_default = "host.docker.internal"
#server_url_default = "http://localhost:5002"
#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()
headers = {}
class Object(object):
pass
def strip_strings(value):
if isinstance(value, str):
return value.strip()
elif isinstance(value, dict):
return {k: strip_strings(v) for k, v in value.items()}
elif isinstance(value, list):
return [strip_strings(item) for item in value]
return value # Return as is if not a string, list, or dict
def string_to_unix_epoch(date_string):
if date_string is None:
return None
try:
# Check if the input is a float or integer representing Unix time
return float(date_string)
except ValueError:
# If not, parse it as a date string
date_object = datetime.strptime(date_string, "%m/%d/%Y")
return time.mktime(date_object.timetuple())
def fix_date_fields(query: Dict[str, Dict], date_fields: List[str]):
"""Takes in a query and date fields to correct and returns query with appropriate epoch dates"""
new_query: Dict[str, Dict] = {}
for field, sub_query in query.items():
# fix date values for given date fields
if field in date_fields:
new_sub_query = {k: string_to_unix_epoch(v) for k, v in sub_query.items()}
new_query[field] = new_sub_query
# else, use the original
else: new_query[field] = sub_query
return new_query
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)
def http_get(args, req_url, headers = None, json = None):
t = 0.15
for i in range(0, args.retry):
r = requests.get(req_url, headers=headers, json=json)
if (r.status_code == 429):
time.sleep(t)
t *= 1.5
else:
break
return r
def http_put(args, req_url, headers, json):
t = 0.3
for i in range(0, int(args.retry)):
r = requests.put(req_url, headers=headers, json=json)
if (r.status_code == 429):
time.sleep(t)
t *= 1.5
else:
break
return r
def http_post(args, req_url, headers, json={}):
t = 0.3
for i in range(0, int(args.retry)):
#if (args.explain):
# print(req_url)
r = requests.post(req_url, headers=headers, json=json)
if (r.status_code == 429):
time.sleep(t)
t *= 1.5
else:
break
return r
def http_del(args, req_url, headers, json={}):
t = 0.3
for i in range(0, int(args.retry)):
r = requests.delete(req_url, headers=headers, json=json)
if (r.status_code == 429):
time.sleep(t)
t *= 1.5
else:
break
return r
def load_permissions_from_file(file_path):
with open(file_path, 'r') as file:
return json.load(file)
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: Dict) -> 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
#req_url = apiurl(args, "/instances", {"owner": "me"});
def apiurl(args: argparse.Namespace, subpath: str, query_args: 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:
"""
result = None
if query_args is None:
query_args = {}
if args.api_key is not None:
query_args["api_key"] = args.api_key
query_json = None
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>)
query_json = "&".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())
result = args.url + "/api/v0" + subpath + "?" + query_json
else:
result = args.url + "/api/v0" + subpath
if (args.explain):
print("query args:")
print(query_args)
print("")
print(f"base: {args.url + '/api/v0' + subpath + '?'} + query: ")
print(result)
print("")
return result
def apiheaders(args: argparse.Namespace) -> Dict:
"""Creates the headers for a given combination of parameters.
:param argparse.Namespace args: Namespace with many fields relevant to the endpoint.
:rtype Dict:
"""
result = {}
if args.api_key is not None:
result["Authorization"] = "Bearer " + args.api_key
return result
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", "N", "{}x", None, False),
("gpu_name", "Model", "{}", None, True),
("pcie_bw", "PCIE", "{:0.1f}", None, True),
("cpu_ghz", "cpu_ghz", "{:0.1f}", None, True),
("cpu_cores_effective", "vCPUs", "{:0.1f}", None, True),
("cpu_ram", "RAM", "{:0.1f}", lambda x: x / 1000, False),
("disk_space", "Disk", "{:.0f}", None, True),
("dph_total", "$/hr", "{:0.4f}", None, True),
("dlperf", "DLP", "{:0.1f}", None, True),
("dlperf_per_dphtotal", "DLP/$", "{:0.2f}", None, True),
("score", "score", "{:0.1f}", None, True),
("driver_version", "NV Driver", "{}", None, True),
("inet_up", "Net_up", "{:0.1f}", None, True),
("inet_down", "Net_down", "{:0.1f}", None, True),
("reliability", "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", "mach_id", "{}", None, True),
("verification", "status", "{}", None, True),
("direct_port_count", "ports", "{}", None, True),
("geolocation", "country", "{}", None, True),
# ("direct_port_count", "Direct Port Count", "{}", None, True),
)
displayable_fields_reserved = (
# ("bw_nvlink", "Bandwidth NVLink", "{}", None, True),
("id", "ID", "{}", None, True),
("cuda_max_good", "CUDA", "{:0.1f}", None, True),
("num_gpus", "N", "{}x", None, False),
("gpu_name", "Model", "{}", None, True),
("pcie_bw", "PCIE", "{:0.1f}", None, True),
("cpu_ghz", "cpu_ghz", "{:0.1f}", None, True),
("cpu_cores_effective", "vCPUs", "{:0.1f}", None, True),
("cpu_ram", "RAM", "{:0.1f}", lambda x: x / 1000, False),
("disk_space", "Disk", "{:.0f}", None, True),
("discounted_dph_total", "$/hr", "{:0.4f}", None, True),
("dlperf", "DLP", "{:0.1f}", None, True),
("dlperf_per_dphtotal", "DLP/$", "{:0.2f}", None, True),
("driver_version", "NV Driver", "{}", None, True),
("inet_up", "Net_up", "{:0.1f}", None, True),
("inet_down", "Net_down", "{:0.1f}", None, True),
("reliability", "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", "mach_id", "{}", None, True),
("verification", "status", "{}", None, True),
("direct_port_count", "ports", "{}", None, True),
("geolocation", "country", "{}", 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", "age(hours)", "{:0.2f}", lambda x: x/(3600.0), True),
)
# These fields are displayed when you do 'show machines'
machine_fields = (
("id", "ID", "{}", None, True),
("num_gpus", "#gpus", "{}", None, True),
("gpu_name", "gpu_name", "{}", None, True),
("disk_space", "disk", "{}", None, True),
("hostname", "hostname", "{}", lambda x: x[:16], True),
("driver_version", "driver", "{}", None, True),
("reliability2", "reliab", "{:0.4f}", None, True),
("verification", "veri", "{}", None, True),
("public_ipaddr", "ip", "{}", None, True),
("geolocation", "geoloc", "{}", None, True),
("num_reports", "reports", "{}", None, True),
("listed_gpu_cost", "gpuD_$/h", "{:0.2f}", None, True),
("min_bid_price", "gpuI$/h", "{:0.2f}", None, True),
("credit_discount_max", "rdisc", "{:0.2f}", None, True),
("listed_inet_up_cost", "netu_$/TB", "{:0.2f}", lambda x: x * 1024, True),
("listed_inet_down_cost", "netd_$/TB", "{:0.2f}", lambda x: x * 1024, True),
("gpu_occupancy", "occup", "{}", None, True),
)
ipaddr_fields = (
("ip", "ip", "{}", None, True),
("first_seen", "first_seen", "{}", None, True),
("first_location", "first_location", "{}", None, True),
)
audit_log_fields = (
("ip_address", "ip_address", "{}", None, True),
("api_key_id", "api_key_id", "{}", None, True),
("created_at", "created_at", "{}", None, True),
("api_route", "api_route", "{}", None, True),
("args", "args", "{}", None, True),
)
invoice_fields = (
("description", "Description", "{}", None, True),
("quantity", "Quantity", "{}", None, True),
("rate", "Rate", "{}", None, True),
("amount", "Amount", "{}", 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)
)
connection_fields = (
("id", "ID", "{}", None, True),
("name", "NAME", "{}", None, True),
("cloud_type", "Cloud Type", "{}", 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
offers_fields = {
"bw_nvlink",
"compute_cap",
"cpu_arch",
"cpu_cores",
"cpu_cores_effective",
"cpu_ghz",
"cpu_ram",
"cuda_max_good",
"datacenter",
"direct_port_count",
"driver_version",
"disk_bw",
"disk_space",
"dlperf",
"dlperf_per_dphtotal",
"dph_total",
"duration",
"external",
"flops_per_dphtotal",
"gpu_arch",
"gpu_display_active",
"gpu_frac",
# "gpu_ram_free_min",
"gpu_mem_bw",
"gpu_name",
"gpu_ram",
"gpu_total_ram",
"gpu_display_active",
"gpu_max_power",
"gpu_max_temp",
"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",
"reliability",
#"reliability2",
"rentable",
"rented",
"storage_cost",
"static_ip",
"total_flops",
"ubuntu_version",
"verification",
"verified",
"geolocation"
}
offers_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",
}
offers_mult = {
"cpu_ram": 1000,
"gpu_ram": 1000,
"gpu_total_ram" : 1000,
"duration": 24.0 * 60.0 * 60.0,
}
def parse_query(query_str: str, res: Dict = None, fields = {}, field_alias = {}, field_multiplier = {}) -> 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 query_str is None:
return res
if res is None: res = {}
if type(query_str) == list:
query_str = " ".join(query_str)
query_str = query_str.strip()
# Revised regex pattern to accurately capture quoted strings, bracketed lists, and single words/numbers
#pattern = r"([a-zA-Z0-9_]+)\s*(=|!=|<=|>=|<|>| in | nin | eq | neq | not eq | not in )?\s*(\"[^\"]*\"|\[[^\]]+\]|[^ ]+)"
#pattern = "([a-zA-Z0-9_]+)( *[=><!]+| +(?:[lg]te?|nin|neq|eq|not ?eq|not ?in|in) )?( *)(\[[^\]]+\]|[^ ]+)?( *)"
pattern = r"([a-zA-Z0-9_]+)( *[=><!]+| +(?:[lg]te?|nin|neq|eq|not ?eq|not ?in|in) )?( *)(\[[^\]]+\]|\"[^\"]+\"|[^ ]+)?( *)"
opts = re.findall(pattern, query_str)
#print("parse_query regex:")
#print(opts)
#print(opts)
# 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",
}
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:
res.pop(field)
field = field_alias[field]
if (field == "driver_version") and ('.' in value):
value = numeric_version(value)
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 isinstance(value, str):
value = value.replace('_', ' ')
value = value.strip('\"')
elif isinstance(value, list):
value = [x.replace('_', ' ') for x in value]
value = [x.strip('\"') for x in value]
if field in field_multiplier:
value = float(value) * field_multiplier[field]
v[op_name] = value
else:
#print(value)
if (value == 'true') or (value == 'True'):
v[op_name] = True
elif (value == 'false') or (value == 'False'):
v[op_name] = False
elif (value == 'None') or (value == 'null'):
v[op_name] = None
else:
v[op_name] = value
if field not in res:
res[field] = v
else:
res[field].update(v)
#print(res)
return res
def display_table(rows: list, fields: 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("instance_id", help="id of instance to attach to", type=int),
argument("ssh_key", help="ssh key to attach to instance", type=str),
usage="vastai attach instance_id ssh_key",
help="Attach an ssh key to an instance. This will allow you to connect to the instance with the ssh key.",
epilog=deindent("""
Attach an ssh key to an instance. This will allow you to connect to the instance with the ssh key.
Examples:
vast attach 12371 ssh-rsa AAAAB3NzaC1yc2EAAA...
vast attach 12371 ssh-rsa $(cat ~/.ssh/id_rsa)
The first example attaches the ssh key to instance 12371
"""),
)
def attach__ssh(args):
url = apiurl(args, "/instances/{id}/ssh/".format(id=args.instance_id))
req_json = {"ssh_key": args.ssh_key}
r = http_post(args, url, headers=headers, json=req_json)
r.raise_for_status()
print(r.json())
@parser.command(
argument("dst", help="instance_id:/path to target of copy operation.", type=str),
usage="vastai cancel copy DST",
help=" Cancel a remote copy in progress, specified by DST id",
epilog=deindent("""
Use this command to cancel any/all current remote copy operations copying to a specific named instance, given by DST.
Examples:
vast cancel copy 12371
The first example cancels all copy operations currently copying data into instance 12371
"""),
)
def cancel__copy(args: argparse.Namespace):
"""
Cancel a remote copy in progress, specified by DST id"
@param dst: ID of copy instance Target to cancel.
"""
url = apiurl(args, f"/commands/rsync/")
dst_id = args.dst
if (dst_id is None):
print("invalid arguments")
return
print(f"canceling remote copies to {dst_id} ")
req_json = { "client_id": "me", "dst_id": dst_id, }
r = http_del(args, url, headers=headers,json=req_json)
r.raise_for_status()
if (r.status_code == 200):
rj = r.json();
if (rj["success"]):
print("Remote copy canceled - 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("dst", help="instance_id:/path to target of sync operation.", type=str),
usage="vastai cancel sync DST",
help=" Cancel a remote copy in progress, specified by DST id",
epilog=deindent("""
Use this command to cancel any/all current remote cloud sync operations copying to a specific named instance, given by DST.
Examples:
vast cancel sync 12371
The first example cancels all copy operations currently copying data into instance 12371
"""),
)
def cancel__sync(args: argparse.Namespace):
"""
Cancel a remote cloud sync in progress, specified by DST id"
@param dst: ID of cloud sync instance Target to cancel.
"""
url = apiurl(args, f"/commands/rclone/")
dst_id = args.dst
if (dst_id is None):
print("invalid arguments")
return
print(f"canceling remote copies to {dst_id} ")
req_json = { "client_id": "me", "dst_id": dst_id, }
r = http_del(args, url, headers=headers,json=req_json)
r.raise_for_status()
if (r.status_code == 200):
rj = r.json();
if (rj["success"]):
print("Remote copy canceled - 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("id", help="id of instance type to change bid", type=int),
argument("--price", help="per machine bid price in $/hour", type=float),
usage="vastai change bid id [--price PRICE]",
help="Change the bid price for a spot/interruptible instance",
epilog=deindent("""
Change the current bid price of instance id to PRICE.
If PRICE is not specified, then a winning bid price is used as the default.
"""),
)
def change__bid(args: argparse.Namespace):
"""Alter the bid with id contained in args.
:param argparse.Namespace args: should supply all the command-line options
:rtype int:
"""
url = apiurl(args, "/instances/bid_price/{id}/".format(id=args.id))
json_blob = {"client_id": "me", "price": args.price,}
if (args.explain):
print("request json: ")
print(json_blob)
r = http_put(args, url, headers=headers, json=json_blob)
r.raise_for_status()
print("Per gpu bid price changed".format(r.json()))
@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="vastai 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.
You should not copy to /root or / as a destination directory, as this can mess up the permissions on your instance ssh folder, breaking future copy operations (as they use ssh authentication)
You can see more information about constraints here: https://vast.ai/docs/gpu-instances/data-movement#constraints
Examples:
vast copy 6003036:/workspace/ 6003038:/workspace/
vast copy 11824:/data/test data/test
vast copy data/test 11824:/data/test
The first example copy syncs all files from the absolute directory '/workspace' on instance 6003036 to the directory '/workspace' on instance 6003038.
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,
}
if (args.explain):
print("request json: ")
print(req_json)
r = http_put(args, url, headers=headers,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)