-
Notifications
You must be signed in to change notification settings - Fork 24
/
dodo.py
3140 lines (2632 loc) · 105 KB
/
dodo.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
# Only import from the standard lib, to keep this module easily importable!
# Inline external libraries imports.
import collections
import contextlib
import datetime
import functools
import glob
import imghdr
import itertools
import json
import os
import pathlib
import shlex
import shutil
import struct
import subprocess
import time
try:
import requests
except ModuleNotFoundError:
requests = None
##### Globals and default config #####
DEFAULT_EXCLUDE = [
'doc',
'envs',
'test_data',
'builtdocs',
'jupyter_execute',
'_extensions',
'postBuild', # needed just onece, can be removed
*glob.glob( '.*'),
*glob.glob( '_*'),
]
DEFAULT_DOC_EXCLUDE = [
'_static',
'_templates',
# We don't want to include the template project in the main website
'template',
]
PROJECT_CONFIG_IGNORES_KEYS_WEBSITE = [
'description',
'examples_config.created',
'examples_config.maintainers',
'examples_config.labels',
'examples_config.title',
'examples_config.categories',
]
PROJECT_CONFIG_IGNORES_KEYS_DEPLOYMENTS = [
'examples_config.deployments',
'commands',
]
CATNAME_TO_CAT_MAP = {
'⭐ Featured': ['Featured'],
'Geospatial': ['Geospatial'],
'Finance and Economics': ['Finance', 'Economics'],
'Mathematics': ['Mathematics'],
'Cybersecurity and Networks': ['Cybersecurity', 'Networks'],
'Other Sciences': ['Other Sciences'],
'Neuroscience': ['Neuroscience'],
'Sports': ['Sports'],
# 'No Category':[],
}
CAT_TO_CATNAME_MAP = {
category: catname
for catname, categories in CATNAME_TO_CAT_MAP.items()
for category in categories
}
LAST_UPDATED_PATTERNS = [
# Notably excluded:
# - anaconda-project.yml (has website/deployment metadata)
# - /thumbnails
'*.ipynb',
'*.py',
'anaconda-project-lock.yml',
'catalog.yml',
'assets',
'data',
]
README_TEMPLATE = 'readme_template.md'
# But it's included on the dev site if this env var is set.
if os.getenv('EXAMPLES_HOLOVIZ_DEV_SITE') is not None:
DEFAULT_DOC_EXCLUDE.remove('template')
DEFAULT_SKIP_NOTEBOOKS_EVALUATION = False
DEFAULT_NO_DATA_INGESTION = False
DEFAULT_GH_RUNNER = 'ubuntu-latest'
DEFAULT_DEPLOYMENTS_AUTO_DEPLOY = True
DEFAULT_DEPLOYMENTS_RESOURCE_PROFILE = "default"
NOTEBOOK_EVALUATION_TIMEOUT = 3600 # in seconds.
ENDPOINT_TEMPLATE_NOTEBOOK = '{servername}-notebook'
ENDPOINT_TEMPLATE_DASHBOARD = '{servername}'
# Same for hostname, different for username and password
AE5_CREDENTIALS_ENV_VARS = {
'admin': {
'username': 'EXAMPLES_HOLOVIZ_AE5_ADMIN_USERNAME',
'password': 'EXAMPLES_HOLOVIZ_AE5_ADMIN_PASSWORD',
},
'non-admin': {
'username': 'EXAMPLES_HOLOVIZ_AE5_USERNAME',
'password': 'EXAMPLES_HOLOVIZ_AE5_PASSWORD',
}
}
EXAMPLES_DEPLOYMENTS_URL = "https://examples.holoviz.org/_static/deployments.json"
# python-dotenv is an optional dep,
# use it to define environment variables
try:
from dotenv import load_dotenv
except ImportError:
pass
else:
load_dotenv('.env') # take environment variables from .env.
EXAMPLES_HOLOVIZ_AE5_ENDPOINT = os.getenv('EXAMPLES_HOLOVIZ_AE5_ENDPOINT', 'holoviz-demo.anaconda.com')
#### doit config and shared parameters ####
DOIT_CONFIG = {
"verbosity": 2,
"backend": "sqlite3",
}
ae5_hostname = {
'name': 'hostname',
'long': 'hostname',
'type': str,
'default': EXAMPLES_HOLOVIZ_AE5_ENDPOINT,
}
ae5_username = {
'name': 'username',
'long': 'username',
'type': str,
'default': '',
}
ae5_password = {
'name': 'password',
'long': 'password',
'type': str,
'default': '',
}
ae5_admin_username = {
'name': 'admin_username',
'long': 'admin-username',
'type': str,
'default': '',
}
ae5_admin_password = {
'name': 'admin_password',
'long': 'admin-password',
'type': str,
'default': '',
}
env_spec_param = {
'name': 'env_spec',
'long': 'env-spec',
'type': str,
'default': 'default'
}
githubrepo_param = {
'name': 'githubrepo',
'type': str,
'default': 'holoviz-topics/examples'
}
name_param = {
'name': 'name',
'long': 'name',
'type': str,
'default': 'all'
}
exclude_website_metadata_param = {
'name': 'exclude_website_metadata',
'long': 'exclude-website-metadata',
'type': bool,
'default': False,
}
exclude_deployments_metadata_param = {
'name': 'exclude_deployments_metadata',
'long': 'exclude-deployments-metadata',
'type': bool,
'default': False,
}
only_project_file_param = {
'name': 'only_project_file',
'long': 'only-project-file',
'type': bool,
'default': False,
}
exclude_test_data_param = {
'name': 'exclude_test_data',
'long': 'exclude-test-data',
'type': bool,
'default': False,
}
##### Exceptions ####
class ExamplesError(Exception):
"""Base error"""
class ValidationError(Exception):
"""Validation error"""
#### Utils ####
def all_project_names(root, exclude=DEFAULT_EXCLUDE):
"""
Return a sorted list of the projects directory names.
"""
if root == '':
root = os.getcwd()
root = os.path.abspath(root)
projects = []
for path in pathlib.Path(root).iterdir():
if not path.is_dir():
continue
if path.name in exclude:
continue
projects.append(path.name)
return sorted(projects)
def complain(msg, level='WARNING'):
"""
Print a warning, unless the environment variable
EXAMPLES_HOLOVIZ_WARNING_AS_ERROR is set.
"""
if (
os.getenv('EXAMPLES_HOLOVIZ_WARNING_AS_ERROR', None) is not None
and level == 'WARNING'
):
raise ValidationError(msg)
else:
print(f'{level}: ' + msg)
def deployment_cmd_to_endpoint(cmd, name, full=True):
"""
Given a project command and a project name returns an endpoint.
"""
servername = projname_to_servername(name)
if cmd == 'notebook':
endpoint = ENDPOINT_TEMPLATE_NOTEBOOK.format(servername=servername)
elif cmd == 'dashboard':
endpoint = ENDPOINT_TEMPLATE_DASHBOARD.format(servername=servername)
else:
raise ValueError(f'Unexpected command {cmd}')
if not full:
return endpoint
full_url = 'https://' + endpoint + '.' + EXAMPLES_HOLOVIZ_AE5_ENDPOINT
return full_url
def find_notebooks(proj_dir_name, exclude_config=['notebooks_to_skip'], root=''):
"""
Find the notebooks in a project.
"""
if not root:
proj_dir = pathlib.Path(proj_dir_name)
else:
proj_dir = pathlib.Path(root, proj_dir_name)
spec = project_spec(proj_dir)
excluded = []
if 'notebooks_to_skip' in exclude_config:
excluded.extend(spec.get('examples_config', {}).get('notebooks_to_skip', []))
notebooks = []
for notebook in proj_dir.glob('*.ipynb'):
if notebook.name in excluded:
continue
notebooks.append(notebook)
return notebooks
def get_png_dims(fname):
"""
From https://stackoverflow.com/a/20380514/10875966
"""
with open(fname, 'rb') as fhandle:
head = fhandle.read(24)
if len(head) != 24:
raise ValueError
imgtype = imghdr.what(fname)
if imghdr.what(fname) == 'png':
check = struct.unpack('>i', head[4:8])[0]
if check != 0x0d0a1a0a:
return
width, height = struct.unpack('>ii', head[16:24])
else:
raise ValueError(f'Only supports PNG, not {imgtype}')
return width, height
def last_commit_date(name, root='.', verbose=True):
"""
Return the last committer data as 'YYYY-MM-DD'
"""
paths = []
for patt in LAST_UPDATED_PATTERNS:
if '*' in patt:
spaths = list(pathlib.Path(root, name).glob(patt))
else:
spaths = [pathlib.Path(root, name, patt)]
paths.extend(spaths)
paths = ' '.join([str(p) for p in paths if p.exists()])
proc = subprocess.run(
[f'git log -n 1 --pretty=format:%cs {paths}'],
check=True, capture_output=True, text=True, shell=True,
)
last_committer_date = proc.stdout
if not last_committer_date:
raise ValueError('Last commit date not found')
if verbose:
print(f'Last commit date: {last_committer_date}')
return last_committer_date
def remove_ignored_keys(mapping, ignored_keys):
"""
>>> d = {'a': 1, 'b': {'c': 3, 'd': 4}, 'e': 5}
>>> remove_ignored_keys(d, ['a', 'b.d'])
{'b': {'c': 3}, 'e': 5}
"""
for key in ignored_keys:
mapping = remove_nested_key(mapping, key)
return mapping
def remove_nested_key(mapping, ref):
expanded = ref.split('.')
obj = mapping
for i, key in enumerate(expanded, 1):
if key in obj:
if i == len(expanded):
# last
del obj[key]
else:
obj = obj[key]
return mapping
def yaml_file_changed(file_path, git_cmd_tmpl, ignored_keys: list):
"""
Check whether the content of a yaml file changed between the current branch
and some git reference, optionally ignoring some keys.
"""
from yaml import safe_load
with open(file_path, 'r') as f:
current_yaml = safe_load(f)
previous_version = subprocess.run(
git_cmd_tmpl.format(file_path=file_path),
stdout=subprocess.PIPE,
shell=True,
)
previous_yaml = safe_load(previous_version.stdout.decode())
current_yaml = remove_ignored_keys(current_yaml, ignored_keys)
previous_yaml = remove_ignored_keys(previous_yaml, ignored_keys)
return current_yaml != previous_yaml
def print_changes_in_dir(paths: list[str], project_file_changed_cb, only_project_file=False, exclude_test_data=False):
"""Dumps as JSON a dict of the changed projects and removed projects.
New projects are in the changed list.
"""
paths = [pathlib.Path(p) for p in paths]
all_projects = set(all_project_names(root=''))
changed_dirs = []
removed_dirs = []
for path in paths:
if path.name != 'anaconda-project.yml' and only_project_file:
continue
root = path.parts[0]
# empty suffix is a hint for a directory, useful to catch when
# a non-project file has been removed
if pathlib.Path(root).is_file() or pathlib.Path(root).suffix != '':
continue
if not exclude_test_data and root == 'test_data':
try:
test_data_dir = path.parts[1]
except IndexError:
print(f'Unhandled path when printing the changes {path}')
continue
if test_data_dir in all_projects:
changed_dirs.append(test_data_dir)
continue
if root in DEFAULT_EXCLUDE:
continue
if root in all_projects:
if path.name == 'anaconda-project.yml':
if project_file_changed_cb(path):
changed_dirs.append(root)
else:
changed_dirs.append(root)
else:
removed_dirs.append(root)
changed_dirs = sorted(set(changed_dirs))
removed_dirs = sorted(set(removed_dirs))
updates = {
'changed': changed_dirs,
'removed': removed_dirs
}
print(json.dumps(updates))
def project_has_data_folder(name):
"""Whether a project has a data folder"""
path = pathlib.Path(name) / 'data'
if not path.is_dir():
return False
has_files = any(path.iterdir())
return has_files
def project_has_no_data_ingestion(name):
"""Whether a project defines `no_data_ingestion` to True"""
spec = project_spec(name)
return spec.get('examples_config', {}).get(
'no_data_ingestion', DEFAULT_NO_DATA_INGESTION
)
def project_has_downloads(name):
"""Whether a project has a non-empty `downloads` section."""
spec = project_spec(name)
downloads = spec.get('downloads', {})
return bool(downloads)
def project_has_intake_catalog(name):
"""Whether a project has an Intake catalog"""
path = pathlib.Path(name) / 'catalog.yml'
return path.is_file()
def project_has_test_catalog(name):
"""Whether a project has a test catalog"""
path = pathlib.Path('test_data') / name / 'catalog.yml'
return path.exists()
def project_has_test_data(name):
"""Whether a project has a test data"""
path = pathlib.Path('test_data') / name
if not path.is_dir():
return False
has_files = any(path.iterdir())
return has_files
def remove_empty_dirs(path):
"""
Remove all the empty dirs in a tree, including the root.
"""
# Remove children dirs
for root, dirnames, _ in os.walk(path, topdown=False):
for dirname in dirnames:
p = os.path.realpath(os.path.join(root, dirname))
error = False
try:
os.rmdir(p)
except OSError:
error = True
if not error:
print(f'Removed empty dir {p}')
# Remove root dir
error = False
try:
os.rmdir(path)
except OSError:
error = True
if not error:
print(f'Removed empty dir {path}')
@contextlib.contextmanager
def removing_files(paths, verbose=True):
"""
Context manager to remove a list of files on exit, if they were
not already there on enter.
"""
already_there = []
for path in paths:
if path.exists():
already_there.append(path)
yield
for path in paths:
if not path.exists():
continue
if path in already_there:
continue
if verbose:
print(f'Removing {path}')
path.unlink()
def run_fast_scandir(dir):
"""
Traverse the filesystem, ignoring /envs and .examples_snapshot
"""
subfolders, files = [], []
for f in os.scandir(dir):
if f.is_dir() and f.name != 'envs':
subfolders.append(f.path)
if f.is_file() and f.name != '.examples_snapshot':
files.append(f.path)
for dir in list(subfolders):
sf, f = run_fast_scandir(dir)
subfolders.extend(sf)
files.extend(f)
return subfolders, files
def _prepare_paths(root, name, test_data, filename='catalog.yml'):
"""
Return a dict of paths, useful to deal with the test data.
"""
if root == '':
root = os.getcwd()
root = os.path.abspath(root)
test_data = test_data if os.path.isabs(test_data) else os.path.join(root, test_data)
test_path = os.path.join(test_data, name)
project_path = os.path.join(root, name)
return {
# Path to the project, e.g. ./projname
'project': project_path,
# Path to the real data folder, e.g. ./projname/data
'real': os.path.join(project_path, 'data'),
# Path to the test data folder, e.g. ./test_data/projname
'test': test_path,
# Path to the real intake catalog, e.g. ./projname/catalog.yml
'cat_real': os.path.join(project_path, filename),
# Path to the real intake catalog, e.g. ./test_data/projname/catalog.yml
'cat_test': os.path.join(test_path, filename),
# Path to the temporary intake catalog, e.g. ./projname/tmp_catalog.yml
# This is used to store the original catalog
'cat_tmp': os.path.join(project_path, 'tmp_' + filename),
}
def project_spec(projname, filename='anaconda-project.yml'):
"""
Return the spec of a project.
"""
from yaml import safe_load
path = pathlib.Path(projname) / filename
with open(path, 'r') as f:
spec = safe_load(f)
return spec
def projname_to_servername(name):
"""
Replace '_' by '-'. Assumes projname only has [a-z_]
"""
return name.replace('_', '-')
def projname_to_title(name):
"""
Replace '_' by ' ' and apply `.title()`. Assumes projname only has [a-z_]
"""
return name.replace('_', ' ').title()
def proj_env_vars(project, filename='anaconda-project.yml'):
spec = project_spec(project, filename)
variables = spec.get('variables', {})
if not variables:
return {}
env_vars = {}
for name, value in variables.items():
if isinstance(value, dict):
value = value['default']
env_vars[name] = value
return env_vars
def parse_notebook_code(notebook_file):
import nbformat
with open(notebook_file, "r") as f:
notebook = nbformat.read(f, as_version=4)
has_code_cells = False
has_code_cell_with_output = False
for cell in notebook.cells:
if cell["cell_type"] != "code":
continue
has_code_cells = True
if cell.get('outputs', []) != []:
has_code_cell_with_output = True
return has_code_cells, has_code_cell_with_output
def should_skip_notebooks_evaluation(name):
"""
Get the value of the special config `skip_notebooks_evaluation`.
Use cases of skip_notebooks_evaluation:
- notebooks that requires data downloaded only based on indications
- notebooks that require too long downloads or too much data for the CI
- notebooks that are too long to run on the CI
- notebooks that need a special setup to run that is not compatible with the CI
"""
spec = project_spec(name)
skip_notebooks_evaluation = spec.get('examples_config', {}).get(
'skip_notebooks_evaluation', DEFAULT_SKIP_NOTEBOOKS_EVALUATION
)
return skip_notebooks_evaluation
def should_skip_test(name):
"""
Determines whether testing a project should be skipped.
"""
# skip_test = False
# if skip_test:
# print('skip_test: True')
# return False
# TODO: remove it if not needed
# Prepared for when skip_test is added
spec = project_spec(name)
skip_test = spec['examples_config'].get('skip_test', False)
return skip_test
#### AE5 utils ####
def ae5_session(hostname=None, username=None, password=None, admin=False):
"""
Return an AE5UserSession if the credentials are provided, either
directly or via environment variables. If not return None.
"""
from ae5_tools.api import AEUserSession
env_vars = AE5_CREDENTIALS_ENV_VARS
cat = 'admin' if admin else 'non-admin'
if not hostname:
raise ValueError('Missing hostname')
if not username:
username = os.getenv(env_vars.get(cat).get('username'), None)
if not password:
password = os.getenv(env_vars.get(cat).get('password'), None)
if any(arg is None for arg in (username, password)):
print('Missing credentials to initialize the AE5 session')
return None
return AEUserSession(
hostname=hostname, username=username, password=password
)
def canonical_url(u):
u = u.lower()
if u.startswith("https://"):
u = u[8:]
if u.endswith("/"):
u = u[:-1]
return u
def find_endpoints(root='', name='all', include_auto_deploy=False):
"""
Return a dict of <projectname>: <list of endpoints>
"""
endpoints = collections.defaultdict(list)
projects = all_project_names(root) if name == 'all' else [name]
for project in projects:
spec = project_spec(project)
deployments = spec.get('examples_config', {}).get('deployments', [])
for depl in deployments:
auto_deploy = depl.get('auto_deploy', DEFAULT_DEPLOYMENTS_AUTO_DEPLOY)
if auto_deploy or include_auto_deploy:
endpoint = deployment_cmd_to_endpoint(depl['command'], project, full=False)
endpoints[project].append(endpoint)
return dict(endpoints)
def list_ae5_projects(session):
"""
List all the project names available to the authenticated user on AE5.
"""
deployed_projects = session.project_list()
# {'url': 'http://anaconda-enterprise-ap-storage/projects/d9f53edcf52a4942bcdf5183854eadef',
# 'created': '2021-05-25T16:22:35.175500+00:00',
# 'repo_owned': True,
# 'repo_url': 'http://anaconda-enterprise-ap-git-storage/anaconda/anaconda-enterprise-d9f53edcf52a4942bcdf5183854eadef.git',
# 'repository': 'anaconda-enterprise-d9f53edcf52a4942bcdf5183854eadef',
# 'updated': '2022-04-07T17:01:17.616320+00:00',
# 'project_create_status': 'done',
# 'git_repos': {},
# 'resource_profile': 'default',
# 'owner': 'anaconda-enterprise',
# 'id': 'a0-d9f53edcf52a4942bcdf5183854eadef',
# 'git_server': 'default',
# 'editor': 'notebook',
# 'name': 'nyc_buildings',
# '_record_type': 'project'}
deployed_projects = set(project['name'] for project in deployed_projects)
return sorted(deployed_projects)
def list_ae5_deployments(session, name=None):
"""
List the deployments specs available to the authenticated user on AE5.
The returned list can be limited to a project only.
"""
deployments = session.deployment_list(format="json")
# {'url': 'https://gapminders.holoviz-demo.anaconda.com/',
# 'public': True,
# 'created': '2022-12-08T11:12:20.538714+00:00',
# 'project_name': 'gapminders',
# 'goal_state': 'started',
# 'source': 'http://anaconda-enterprise-ap-storage/projects/aa4854c00d1f475b95a45f2db3cf6bee/archive/latest',
# 'project_url': 'http://anaconda-enterprise-ap-storage/projects/aa4854c00d1f475b95a45f2db3cf6bee',
# 'updated': '2022-12-08T11:18:20.402424+00:00',
# 'git_repos': {},
# 'replicas': 1,
# 'variables': {},
# 'project_owner': 'anaconda-enterprise',
# 'status_text': 'Started',
# 'resource_profile': 'default',
# 'revision': 'latest',
# 'state': 'started',
# 'owner': 'anaconda-enterprise',
# 'id': 'a2-062618a509c94226a291fb938faeb1dd',
# 'command': 'dashboard',
# 'name': 'gapminders',
# 'project_id': 'a0-aa4854c00d1f475b95a45f2db3cf6bee',
# 'endpoint': 'gapminders',
# '_record_type': 'deployment'}
if name:
deployments = [
depl for depl in deployments
if depl['project_name'] == name
]
return deployments
def list_ae5_sessions(session, name):
"""
List the sessions specs available to the authenticated user on AE5
and for a given project.
"""
sessions = session.session_list(format='json')
# {'_project': {'_record_type': 'project',
# 'created': '2020-06-20T21:36:00.642785+00:00',
# 'editor': 'notebook',
# 'git_repos': {},
# 'git_server': 'default',
# 'id': 'a0-144c9dd8b1e34ee09ed8c555a42f2dce',
# 'name': 'Panel-Gallery',
# 'owner': 'anaconda-enterprise',
# 'project_create_status': 'done',
# 'repo_owned': True,
# 'repo_url': 'http://anaconda-enterprise-ap-git-storage/anaconda/anaconda-enterprise-144c9dd8b1e34ee09ed8c555a42f2dce.git',
# 'repository': 'anaconda-enterprise-144c9dd8b1e34ee09ed8c555a42f2dce',
# 'resource_profile': 'default',
# 'updated': '2022-10-14T10:50:26.781927+00:00',
# 'url': 'http://anaconda-enterprise-ap-storage/projects/144c9dd8b1e34ee09ed8c555a42f2dce'},
# '_record_type': 'session',
# 'created': '2022-12-14T15:38:25.795710+00:00',
# 'id': 'a1-8bfc935b04794519bc3d2b637d3b51a7',
# 'iframe_hosts': 'https://holoviz-demo.anaconda.com',
# 'name': 'Panel-Gallery',
# 'owner': 'anaconda-enterprise',
# 'project_branch': 'anaconda-enterprise-d979c8be607b4745ac817dc6477f770d',
# 'project_id': 'a0-144c9dd8b1e34ee09ed8c555a42f2dce',
# 'project_url': 'http://anaconda-enterprise-ap-storage/projects/144c9dd8b1e34ee09ed8c555a42f2dce',
# 'resource_profile': 'default',
# 'session_name': '8bfc935b04794519bc3d2b637d3b51a7',
# 'state': 'initial',
# 'updated': '2022-12-14T15:38:25.795710+00:00',
# 'url': 'http://anaconda-enterprise-ap-workspace/sessions/8bfc935b04794519bc3d2b637d3b51a7'}
proj_sessions = []
for session_ in sessions:
assert session_['name'] == session_['_project']['name'], f'Unexpected sessions payload\n\n{session_!r}'
if session_['name'] == name:
proj_sessions.append(session_)
return proj_sessions
def list_ae5_jobs(session, name):
"""
List the jobs specs available to the authenticated user on AE5 and
for a given project.
"""
jobs = session.job_list(format='json')
# {'_project': {'_record_type': 'project',
# 'created': '2023-01-20T17:09:51.552442+00:00',
# 'editor': 'notebook',
# 'git_repos': {},
# 'git_server': 'default',
# 'id': 'a0-6d99ba7ada9e45d996bb561d5a19f562',
# 'name': 'boids',
# 'owner': 'holoviz-examples',
# 'project_create_status': 'done',
# 'repo_owned': True,
# 'repo_url': 'http://anaconda-enterprise-ap-git-storage/anaconda/holoviz-examples-6d99ba7ada9e45d996bb561d5a19f562.git',
# 'repository': 'holoviz-examples-6d99ba7ada9e45d996bb561d5a19f562',
# 'resource_profile': 'default',
# 'updated': '2023-01-20T17:09:51.552442+00:00',
# 'url': 'http://anaconda-enterprise-ap-storage/projects/6d99ba7ada9e45d996bb561d5a19f562'},
# '_record_type': 'job',
# 'command': 'notebook',
# 'created': '2023-01-20T17:40:28.978378+00:00',
# 'git_repos': {},
# 'goal_state': 'scheduled',
# 'id': 'a2-c06fd89ed71844dc91f5476c92744bcd',
# 'name': 'test',
# 'owner': 'holoviz-examples',
# 'project_id': 'a0-6d99ba7ada9e45d996bb561d5a19f562',
# 'project_name': 'boids',
# 'project_owner': 'holoviz-examples',
# 'project_url': 'http://anaconda-enterprise-ap-storage/projects/6d99ba7ada9e45d996bb561d5a19f562',
# 'resource_profile': 'default',
# 'revision': 'latest',
# 'schedule': '5 4 5 5 *',
# 'source': 'http://anaconda-enterprise-ap-storage/projects/6d99ba7ada9e45d996bb561d5a19f562/archive/latest',
# 'state': 'scheduled',
# 'status_text': 'Scheduled job',
# 'updated': '2023-01-20T17:40:30.835304+00:00',
# 'url': 'http://anaconda-enterprise-ap-deploy/jobs/c06fd89ed71844dc91f5476c92744bcd',
# 'variables': {}}
proj_jobs = []
for job in jobs:
if job['project_name'] == name:
proj_jobs.append(job)
return proj_jobs
def remove_project(session, name):
"""
Remove a project on AE5, stopping its deployments before that if any.
"""
# from ae5_tools.api import AEUnexpectedResponseError
projects = list_ae5_projects(session)
if name not in projects:
print(f'Project {name!r} not found on AE5, skip.')
return
project_deployments = list_ae5_deployments(session, name=name)
if project_deployments:
print(f'Project {name!r} has {len(project_deployments)} deployments to stop...')
for depl in project_deployments:
print(f'Stopping endpoint {depl["endpoint"]!r} ...')
session.deployment_stop(ident=depl)
print(f'Endpoint {depl["endpoint"]!r} stopped.')
print(f'Deleting remote project {name}...')
session.project_delete(ident=name)
print(f'Remote project {name} deleted!')
def list_and_collect_ae5_deployments(hostname, username, password):
session = ae5_session(hostname, username, password)
if not session:
complain('AE5 Session could not be initialized', level='INFO')
return {}
projects_local = all_project_names(root='')
deployments_ae5_ = list_ae5_deployments(session)
# Sort for itertools.groupby to work as expected
deployments_ae5_ = sorted(deployments_ae5_, key=lambda l: l['project_name'])
endpoints_ae5 = [depl['endpoint'] for depl in deployments_ae5_]
deployments_ae5 = {}
for k, g in itertools.groupby(deployments_ae5_, key=lambda l: l['project_name']):
deployments_ae5[k] = list(g)
deployments_local = {}
for project in projects_local:
spec = project_spec(project)
depls = spec['examples_config'].get('deployments', [])
if depls:
deployments_local[project] = depls
endpoints_local = [
deployment_cmd_to_endpoint(depl['command'], name, full=False)
for name, depls in deployments_local.items()
for depl in depls
]
deployed = collections.defaultdict(list)
deployed_bad_state = collections.defaultdict(list)
missing = collections.defaultdict(list)
unexpected = collections.defaultdict(list)
for project, depls in deployments_local.items():
for depl in depls:
local_endpoint = deployment_cmd_to_endpoint(
depl['command'], project, full=False
)
if local_endpoint in endpoints_ae5:
ae5_depl = [
depl
for depl in deployments_ae5[project]
if depl['endpoint'] == local_endpoint
][0]
if ae5_depl['state'] == 'started':
deployed[project].append(ae5_depl)
else:
deployed_bad_state[project].append(ae5_depl)
else:
missing[project].append(depl)
for project, depls in deployments_ae5.items():
for depl in depls:
if depl['endpoint'] not in endpoints_local:
unexpected[project].append(depl)
return {
'deployed': deployed,
'deployed_bad_state': deployed_bad_state,
'missing': missing,
'unexpected': unexpected,
}
class EndpointStatus:
SUCCESS = "success"
ERROR = "error"
NA = "na"
MISSING = "missing"
UNSUPPORTED = "unsupported"
def expected_examples_deployments() -> dict[str, list[dict[str, str]]]:
resp = requests.get(EXAMPLES_DEPLOYMENTS_URL)
return resp.json()
def check_deployment(url, type_):
if not check_endpoint_exists(url):
return EndpointStatus.MISSING
if type_ == "notebook":
return check_notebook_running_at_endpoint(url)
elif type_ == "dashboard":
return check_bokeh_running_at_endpoint(url)
elif type_ == "api":
return check_api_running_at_endpoint(url)
else:
return EndpointStatus.UNSUPPORTED