forked from vast-ai/vast-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvast.py
More file actions
executable file
·7533 lines (6448 loc) · 293 KB
/
vast.py
File metadata and controls
executable file
·7533 lines (6448 loc) · 293 KB
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
# PYTHON_ARGCOMPLETE_OK
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, Optional
from datetime import date, datetime, timedelta, timezone
import hashlib
import math
import threading
from concurrent.futures import ThreadPoolExecutor
import requests
import getpass
import subprocess
from time import sleep
from subprocess import PIPE
import urllib3
import atexit
from contextlib import redirect_stdout, redirect_stderr
from io import StringIO
from typing import Optional
import shutil
import logging
import textwrap
from pathlib import Path
import warnings
import importlib.metadata
PYPI_BASE_PATH = "https://pypi.org"
# INFO - Change to False if you don't want to check for update each run.
should_check_for_update = False
ARGS = None
TABCOMPLETE = False
try:
import argcomplete
TABCOMPLETE = True
except:
# No tab-completion for you
pass
try:
import curlify
except ImportError:
pass
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 = os.getenv("VAST_URL") or "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"
logging.basicConfig(
level=os.getenv("LOGLEVEL") or logging.WARN,
format="%(levelname)s - %(message)s"
)
def parse_version(version: str) -> tuple[int, ...]:
parts = version.split(".")
if len(parts) < 3:
print(f"Invalid version format: {version}", file=sys.stderr)
return tuple(int(part) for part in parts)
def get_git_version():
try:
result = subprocess.run(
["git", "describe", "--tags", "--abbrev=0"],
capture_output=True,
text=True,
check=True,
)
tag = result.stdout.strip()
return tag[1:] if tag.startswith("v") else tag
except Exception:
return "0.0.0"
def get_pip_version():
try:
return importlib.metadata.version("vastai")
except Exception:
return "0.0.0"
def is_pip_package():
try:
return importlib.metadata.metadata("vastai") is not None
except Exception:
return False
def get_update_command(stable_version: str) -> str:
if is_pip_package():
if "test.pypi.org" in PYPI_BASE_PATH:
return f"{sys.executable} -m pip install --force-reinstall --no-cache-dir -i {PYPI_BASE_PATH} vastai=={stable_version}"
else:
return f"{sys.executable} -m pip install --force-reinstall --no-cache-dir vastai=={stable_version}"
else:
return f"git fetch --all --tags --prune && git checkout tags/v{stable_version}"
def get_local_version():
if is_pip_package():
return get_pip_version()
return get_git_version()
def get_project_data(project_name: str) -> dict[str, dict[str, str]]:
url = PYPI_BASE_PATH + f"/pypi/{project_name}/json"
response = requests.get(url, headers={"Accept": "application/json"})
# this will raise for HTTP status 4xx and 5xx
response.raise_for_status()
# this will raise for HTTP status >200,<=399
if response.status_code != 200:
raise Exception(
f"Could not get PyPi Project: {project_name}. Response: {response.status_code}"
)
response_data: dict[str, dict[str, str]] = response.json()
return response_data
def get_pypi_version(project_data: dict[str, dict[str, str]]) -> str:
info_data = project_data.get("info")
if not info_data:
raise Exception("Could not get PyPi Project")
version_data: str = str(info_data.get("version"))
return str(version_data)
def check_for_update():
pypi_data = get_project_data("vastai")
pypi_version = get_pypi_version(pypi_data)
local_version = get_local_version()
local_tuple = parse_version(local_version)
pypi_tuple = parse_version(pypi_version)
if local_tuple >= pypi_tuple:
return
user_wants_update = input(
f"Update available from {local_version} to {pypi_version}. Would you like to update [Y/n]: "
).lower()
if user_wants_update not in ["y", ""]:
print("You selected no. If you don't want to check for updates each time, update should_check_for_update in vast.py")
return
update_command = get_update_command(pypi_version)
print("Updating...")
_ = subprocess.run(
update_command,
shell=True,
check=True,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
print("Update completed successfully!\nAttempt to run your command again!")
sys.exit(0)
APP_NAME = "vastai"
VERSION = get_local_version()
try:
# Although xdg-base-dirs is the newer name, there's
# python compatibility issues with dependencies that
# can be unresolvable using things like python 3.9
# So we actually use the older name, thus older
# version for now. This is as of now (2024/11/15)
# the safer option. -cjm
import xdg
DIRS = {
'config': xdg.xdg_config_home(),
'temp': xdg.xdg_cache_home()
}
except:
# Reasonable defaults.
DIRS = {
'config': os.path.join(os.getenv('HOME'), '.config'),
'temp': os.path.join(os.getenv('HOME'), '.cache'),
}
for key in DIRS.keys():
DIRS[key] = path = os.path.join(DIRS[key], APP_NAME)
if not os.path.exists(path):
os.makedirs(path)
CACHE_FILE = os.path.join(DIRS['temp'], "gpu_names_cache.json")
CACHE_DURATION = timedelta(hours=24)
APIKEY_FILE = os.path.join(DIRS['config'], "vast_api_key")
APIKEY_FILE_HOME = os.path.expanduser("~/.vast_api_key") # Legacy
if not os.path.exists(APIKEY_FILE) and os.path.exists(APIKEY_FILE_HOME):
#print(f'copying key from {APIKEY_FILE_HOME} -> {APIKEY_FILE}')
shutil.copyfile(APIKEY_FILE_HOME, APIKEY_FILE)
api_key_guard = object()
headers = {}
class Object(object):
pass
def validate_seconds(value):
"""Validate that the input value is a valid number for seconds between yesterday and Jan 1, 2100."""
try:
val = int(value)
# Calculate min_seconds as the start of yesterday in seconds
yesterday = datetime.now() - timedelta(days=1)
min_seconds = int(yesterday.timestamp())
# Calculate max_seconds for Jan 1st, 2100 in seconds
max_date = datetime(2100, 1, 1, 0, 0, 0)
max_seconds = int(max_date.timestamp())
if not (min_seconds <= val <= max_seconds):
raise argparse.ArgumentTypeError(f"{value} is not a valid second timestamp.")
return val
except ValueError:
raise argparse.ArgumentTypeError(f"{value} is not a valid integer.")
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_request(verb, args, req_url, headers: dict[str, str] | None = None, json = None):
t = 0.15
for i in range(0, args.retry):
req = requests.Request(method=verb, url=req_url, headers=headers, json=json)
session = requests.Session()
prep = session.prepare_request(req)
if ARGS.curl:
as_curl = curlify.to_curl(prep)
simple = re.sub(r" -H '[^']*'", '', as_curl)
parts = re.split(r'(?=\s+-\S+)', simple)
pp = parts[-1].split("'")
pp[-3] += "\n "
parts = [*parts[:-1], *[x.rstrip() for x in "'".join(pp).split("\n")]]
print("\n" + ' \\\n '.join(parts).strip() + "\n")
sys.exit(0)
else:
r = session.send(prep)
if (r.status_code == 429):
time.sleep(t)
t *= 1.5
else:
break
return r
def http_get(args, req_url, headers = None, json = None):
return http_request('GET', args, req_url, headers, json)
def http_put(args, req_url, headers = None, json = {}):
return http_request('PUT', args, req_url, headers, json)
def http_post(args, req_url, headers = None, json={}):
return http_request('POST', args, req_url, headers, json)
def http_del(args, req_url, headers = None, json={}):
return http_request('DELETE', args, req_url, headers, json)
def load_permissions_from_file(file_path):
with open(file_path, 'r') as file:
return json.load(file)
def complete_instance_machine(prefix=None, action=None, parser=None, parsed_args=None):
return show__instances(ARGS, {'internal': True, 'field': 'machine_id'})
def complete_instance(prefix=None, action=None, parser=None, parsed_args=None):
return show__instances(ARGS, {'internal': True, 'field': 'id'})
def complete_sshkeys(prefix=None, action=None, parser=None, parsed_args=None):
return [str(m) for m in Path.home().joinpath('.ssh').glob('*.pub')]
class apwrap(object):
def __init__(self, *args, **kwargs):
if "formatter_class" not in kwargs:
kwargs["formatter_class"] = MyWideHelpFormatter
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))
if "formatter_class" not in kwargs:
kwargs["formatter_class"] = MyWideHelpFormatter
sp = self.subparsers().add_parser(name, aliases=aliases_transformed, help=help_, **kwargs)
# TODO: Sometimes the parser.command has a help parameter. Ideally
# I'd extract this during the sdk phase but for the life of me
# I can't find it.
setattr(func, "mysignature", sp)
setattr(func, "mysignature_help", help_)
self.subparser_objs.append(sp)
for arg in arguments:
tsp = sp.add_argument(*arg.args, **arg.kwargs)
myCompleter= None
comparator = arg.args[0].lower()
if comparator.startswith('machine'):
myCompleter = complete_instance_machine
elif comparator.startswith('id') or comparator.endswith('id'):
myCompleter = complete_instance
elif comparator.startswith('ssh'):
myCompleter = complete_sshkeys
if myCompleter:
setattr(tsp, 'completer', myCompleter)
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
class MyWideHelpFormatter(argparse.RawTextHelpFormatter):
def __init__(self, prog):
super().__init__(prog, width=128, max_help_position=50, indent_increment=1)
parser = apwrap(
epilog="Use 'vast COMMAND --help' for more info about a command",
formatter_class=MyWideHelpFormatter
)
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),
("host_id", "host_id", "{}", 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),
("host_id", "host_id", "{}", None, True),
("direct_port_count", "ports", "{}", None, True),
("geolocation", "country", "{}", None, True),
# ("direct_port_count", "Direct Port Count", "{}", None, True),
)
vol_offers_fields = {
"cpu_arch",
"cuda_vers",
"cluster_id",
"nw_disk_min_bw",
"nw_disk_avg_bw",
"nw_disk_max_bw",
"datacenter",
"disk_bw",
"disk_space",
"driver_version",
"duration",
"geolocation",
"gpu_arch",
"has_avx",
"host_id",
"id",
"inet_down",
"inet_up",
"machine_id",
"pci_gen",
"pcie_bw",
"reliability",
"storage_cost",
"static_ip",
"total_flops",
"ubuntu_version",
"verified",
}
vol_displayable_fields = (
("id", "ID", "{}", None, True),
("cuda_max_good", "CUDA", "{:0.1f}", None, True),
("cpu_ghz", "cpu_ghz", "{:0.1f}", None, True),
("disk_bw", "Disk B/W", "{:0.1f}", None, True),
("disk_space", "Disk", "{:.0f}", None, True),
("disk_name", "Disk Name", "{}", None, True),
("storage_cost", "$/Gb/Month", "{:.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),
("host_id", "host_id", "{}", None, True),
("geolocation", "country", "{}", None, True),
)
nw_vol_displayable_fields = (
("id", "ID", "{}", None, True),
("disk_space", "Disk", "{:.0f}", None, True),
("storage_cost", "$/Gb/Month", "{:.2f}", 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),
("verification", "status", "{}", None, True),
("host_id", "host_id", "{}", None, True),
("cluster_id", "cluster_id", "{}", None, True),
("geolocation", "country", "{}", None, True),
("nw_disk_min_bw", "Min BW MiB/s", "{}", None, True),
("nw_disk_max_bw", "Max BW MiB/s", "{}", None, True),
("nw_disk_avg_bw", "Avg BW MiB/s", "{}", 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),
("uptime_mins", "uptime(mins)", "{:0.2f}", None, True),
)
cluster_fields = (
("id", "ID", "{}", None, True),
("subnet", "Subnet", "{}", None, True),
("node_count", "Nodes", "{}", None, True),
("manager_id", "Manager ID", "{}", None, True),
("manager_ip", "Manager IP", "{}", None, True),
("machine_ids", "Machine ID's", "{}", None, True)
)
network_disk_fields = (
("network_disk_id", "Network Disk ID", "{}", None, True),
("free_space", "Free Space (GB)", "{}", None, True),
("total_space", "Total Space (GB)", "{}", None, True),
)
network_disk_machine_fields = (
("machine_id", "Machine ID", "{}", None, True),
("mount_point", "Mount Point", "{}", None, True),
)
overlay_fields = (
("overlay_id", "Overlay ID", "{}", None, True),
("name", "Name", "{}", None, True),
("subnet", "Subnet", "{}", None, True),
("cluster_id", "Cluster ID", "{}", None, True),
("instance_count", "Instances", "{}", None, True),
("instances", "Instance IDs", "{}", None, True),
)
volume_fields = (
("id", "ID", "{}", None, True),
("cluster_id", "Cluster ID", "{}", None, True),
("label", "Name", "{}", None, True),
("disk_space", "Disk", "{:.0f}", None, True),
("status", "status", "{}", None, True),
("disk_name", "Disk Name", "{}", None, True),
("driver_version", "NV Driver", "{}", 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", "age(hours)", "{:0.2f}", lambda x: x/(3600.0), True),
("machine_id", "mach_id", "{}", None, True),
("verification", "Verification", "{}", None, True),
("host_id", "host_id", "{}", None, True),
("geolocation", "country", "{}", None, True),
("instances", "instances","{}", None, 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),
)
# These fields are displayed when you do 'show maints'
maintenance_fields = (
("machine_id", "Machine ID", "{}", None, True),
("start_time", "Start (Date/Time)", "{}", lambda x: datetime.fromtimestamp(x).strftime('%Y-%m-%d/%H:%M'), True),
("end_time", "End (Date/Time)", "{}", lambda x: datetime.fromtimestamp(x).strftime('%Y-%m-%d/%H:%M'), True),
("duration_hours", "Duration (Hrs)", "{}", None, True),
("maintenance_category", "Category", "{}", 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),
)
scheduled_jobs_fields = (
("id", "Scheduled Job ID", "{}", None, True),
("instance_id", "Instance ID", "{}", None, True),
("api_endpoint", "API Endpoint", "{}", None, True),
("start_time", "Start (Date/Time in UTC)", "{}", lambda x: datetime.fromtimestamp(x).strftime('%Y-%m-%d/%H:%M'), True),
("end_time", "End (Date/Time in UTC)", "{}", lambda x: datetime.fromtimestamp(x).strftime('%Y-%m-%d/%H:%M'), True),
("day_of_the_week", "Day of the Week", "{}", None, True),
("hour_of_the_day", "Hour of the Day in UTC", "{}", None, True),
("min_of_the_hour", "Minute of the Hour", "{}", None, True),
("frequency", "Frequency", "{}", 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",
"vms_enabled",
"geolocation",
"cluster_id"
}
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) )?( *)(\[[^\]]+\]|\"[^\"]+\"|[^ ]+)?( *)"