This repository has been archived by the owner on Mar 20, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 121
/
Copy pathfleet.py
4948 lines (4685 loc) · 205 KB
/
fleet.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
# Copyright (c) Microsoft Corporation
#
# All rights reserved.
#
# MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
# compat imports
from __future__ import (
absolute_import, division, print_function, unicode_literals
)
from builtins import ( # noqa
bytes, dict, int, list, object, range, str, ascii, chr, hex, input,
next, oct, open, pow, round, super, filter, map, zip)
# stdlib imports
import logging
import os
try:
import pathlib2 as pathlib
except ImportError:
import pathlib
import requests
import tempfile
import time
import uuid
# non-stdlib imports
import azure.batch.models as batchmodels
# local imports
from . import autoscale
from . import batch
from . import crypto
from . import data
from . import federation
from . import keyvault
from . import misc
from . import monitor
from . import remotefs
from . import resource
from . import settings
from . import storage
from . import util
from .version import __version__
# create logger
logger = logging.getLogger(__name__)
util.setup_logger(logger)
# global defines
_REQUEST_CHUNK_SIZE = 4194304
_ROOT_PATH = pathlib.Path(__file__).resolve().parent.parent
_RESOURCES_PATH = None
_NVIDIA_DRIVER = {
'compute_cc37': {
'url': (
'http://us.download.nvidia.com/tesla/'
'410.79/NVIDIA-Linux-x86_64-410.79.run'
),
'sha256': (
'ded482e54a0d538c89b3fb70fe306611c2ad475ebbef805645a5911a3a05c173'
),
'target': 'nvidia-driver_cc37.run'
},
'compute_cc6-7': {
'url': (
'http://us.download.nvidia.com/tesla/'
'410.79/NVIDIA-Linux-x86_64-410.79.run'
),
'sha256': (
'ded482e54a0d538c89b3fb70fe306611c2ad475ebbef805645a5911a3a05c173'
),
'target': 'nvidia-driver_cc6-7.run'
},
'viz_cc52': {
# https://go.microsoft.com/fwlink/?linkid=874272
'url': (
'http://download.microsoft.com/download/8/5/D/'
'85DC7798-B9F7-4BB9-84E8-B3350D7B52F7/'
'NVIDIA-Linux-x86_64-410.71-grid.run'
),
'sha256': (
'48b0457d3fc18da29f7db743e812d2e0cbb5101e8f4d1bcb154b66784c34e361'
),
'target': 'nvidia-driver-grid.run'
},
'license': (
'http://www.nvidia.com/content/DriverDownload-March2009'
'/licence.php?lang=us'
),
}
_INTEL_MPI_RT_PACKAGE = {
'url': (
'http://registrationcenter-download.intel.com/akdlm/irc_nas/tec/9279/'
'l_mpi-rt_p_5.1.3.223.tgz'
),
'sha256': (
'91c5f7575c6b5fbf493c07a255c39ae91e15cd75b26ee90355fa27e0e1b4f22e'
),
'target': 'intel_mpi_rt.tar.gz',
'license': (
'https://software.intel.com/license/intel-simplified-software-license'
)
}
_LIS_PACKAGE = {
# https://aka.ms/lis
'url': (
'http://download.microsoft.com/download/6/8/F/'
'68FE11B8-FAA4-4F8D-8C7D-74DA7F2CFC8C/'
'lis-rpms-4.2.6-2.tar.gz'
),
'sha256': (
'a0916fe5497e9f399be3ce0a3a532c3e9b56b33ee9948d0f8c744aa15db6f05d'
),
'target': 'lis.tar.gz',
'intermediate': 'lis_compact.tar',
'target_compact': 'lis_compact.tar.gz'
}
_PROMETHEUS = {
'node_exporter': {
'url': (
'https://github.com/prometheus/node_exporter/releases/download/v'
'0.16.0/node_exporter-0.16.0.linux-amd64.tar.gz'
),
'sha256': (
'e92a601a5ef4f77cce967266b488a978711dabc527a720bea26505cba426c029'
),
'target': 'node_exporter.tar.gz'
},
'cadvisor': {
'url': (
'https://github.com/google/cadvisor/releases/download/v'
'0.27.4/cadvisor'
),
'sha256': (
'378df92f532166251fa3f116beea26ca6364e45e3d6a63ea78b7627ea54bd303'
),
'target': 'cadvisor',
'target_compact': 'cadvisor.gz'
},
}
_CASCADE_FILE = (
'cascade.py',
pathlib.Path(_ROOT_PATH, 'cascade/cascade.py')
)
_PERF_FILE = (
'perf.py',
pathlib.Path(_ROOT_PATH, 'cascade/perf.py')
)
_MIRROR_SYSTEM_IMAGES_FILE = (
'replicate_batch_shipyard_images.sh',
pathlib.Path(_ROOT_PATH, 'scripts/replicate_batch_shipyard_images.sh')
)
_NODEPREP_FILE = (
'shipyard_nodeprep.sh',
pathlib.Path(_ROOT_PATH, 'scripts/shipyard_nodeprep.sh')
)
_NODEPREP_WINDOWS_FILE = (
'shipyard_nodeprep_nativedocker.ps1',
pathlib.Path(
_ROOT_PATH,
'scripts/windows/shipyard_nodeprep_nativedocker.ps1'
)
)
_GLUSTERPREP_FILE = (
'shipyard_glusterfs_on_compute.sh',
pathlib.Path(_ROOT_PATH, 'scripts/shipyard_glusterfs_on_compute.sh')
)
_GLUSTERRESIZE_FILE = (
'shipyard_glusterfs_on_compute_resize.sh',
pathlib.Path(
_ROOT_PATH, 'scripts/shipyard_glusterfs_on_compute_resize.sh')
)
_AUTOSCRATCH_FILE = (
'shipyard_auto_scratch.sh',
pathlib.Path(_ROOT_PATH, 'scripts/shipyard_auto_scratch.sh')
)
_HPNSSH_FILE = (
'shipyard_hpnssh.sh',
pathlib.Path(_ROOT_PATH, 'scripts/shipyard_hpnssh.sh')
)
_IMAGE_BLOCK_FILE = (
'wait_for_images.sh',
pathlib.Path(_ROOT_PATH, 'scripts/wait_for_images.sh')
)
_REGISTRY_LOGIN_FILE = (
'registry_login.sh',
pathlib.Path(_ROOT_PATH, 'scripts/registry_login.sh')
)
_REGISTRY_LOGIN_WINDOWS_FILE = (
'registry_login.ps1',
pathlib.Path(_ROOT_PATH, 'scripts/windows/registry_login.ps1')
)
_BLOBXFER_FILE = (
'shipyard_blobxfer.sh',
pathlib.Path(_ROOT_PATH, 'scripts/shipyard_blobxfer.sh')
)
_BLOBXFER_WINDOWS_FILE = (
'shipyard_blobxfer.ps1',
pathlib.Path(_ROOT_PATH, 'scripts/windows/shipyard_blobxfer.ps1')
)
_REMOTEFSPREP_FILE = (
'shipyard_remotefs_bootstrap.sh',
pathlib.Path(_ROOT_PATH, 'scripts/shipyard_remotefs_bootstrap.sh')
)
_REMOTEFSADDBRICK_FILE = (
'shipyard_remotefs_addbrick.sh',
pathlib.Path(_ROOT_PATH, 'scripts/shipyard_remotefs_addbrick.sh')
)
_REMOTEFSSTAT_FILE = (
'shipyard_remotefs_stat.sh',
pathlib.Path(_ROOT_PATH, 'scripts/shipyard_remotefs_stat.sh')
)
_ALL_REMOTEFS_FILES = [
_REMOTEFSPREP_FILE, _REMOTEFSADDBRICK_FILE, _REMOTEFSSTAT_FILE,
]
_MONITORINGPREP_FILE = (
'shipyard_monitoring_bootstrap.sh',
pathlib.Path(_ROOT_PATH, 'scripts/shipyard_monitoring_bootstrap.sh')
)
_MONITORINGSERVICES_FILE = (
'docker-compose.yml',
pathlib.Path(_ROOT_PATH, 'heimdall/docker-compose.yml')
)
_MONITORINGSERVICESNONGINX_FILE = (
'docker-compose-nonginx.yml',
pathlib.Path(_ROOT_PATH, 'heimdall/docker-compose-nonginx.yml')
)
_MONITORINGPROMCONF_FILE = (
'prometheus.yml',
pathlib.Path(_ROOT_PATH, 'heimdall/prometheus.yml')
)
_MONITORINGNGINXCONF_FILE = (
'nginx.conf',
pathlib.Path(_ROOT_PATH, 'heimdall/nginx.conf')
)
_MONITORINGGRAFANADASHBOARD_FILE = (
'batch_shipyard_dashboard.json',
pathlib.Path(_ROOT_PATH, 'heimdall/batch_shipyard_dashboard.json')
)
_CONFIGURABLE_MONITORING_FILES = {
'compose': _MONITORINGSERVICES_FILE,
'compose-nonginx': _MONITORINGSERVICESNONGINX_FILE,
'prometheus': _MONITORINGPROMCONF_FILE,
'nginx': _MONITORINGNGINXCONF_FILE,
'dashboard': _MONITORINGGRAFANADASHBOARD_FILE,
}
_FEDERATIONPREP_FILE = (
'shipyard_federation_bootstrap.sh',
pathlib.Path(_ROOT_PATH, 'scripts/shipyard_federation_bootstrap.sh')
)
_FEDERATIONSERVICES_FILE = (
'docker-compose.yml',
pathlib.Path(_ROOT_PATH, 'federation/docker-compose.yml')
)
_ALL_FEDERATION_FILES = [
_FEDERATIONPREP_FILE, _FEDERATIONSERVICES_FILE,
]
def initialize_globals(verbose):
# type: (bool) -> None
"""Initialize any runtime globals
:param bool verbose: verbose
"""
global _RESOURCES_PATH
if _RESOURCES_PATH is None:
_RESOURCES_PATH = _ROOT_PATH / 'resources'
if not _RESOURCES_PATH.exists():
_RESOURCES_PATH = pathlib.Path(
tempfile.gettempdir()) / 'batch-shipyard-{}-resources'.format(
__version__)
_RESOURCES_PATH.mkdir(parents=True, exist_ok=True)
if verbose:
logger.debug('initialized resources path to: {}'.format(
_RESOURCES_PATH))
def populate_global_settings(config, fs_storage, pool_id=None, sc=None):
# type: (dict, bool, str, settings.StorageCredentialsSettings) -> None
"""Populate global settings from config
:param dict config: configuration dict
:param bool fs_storage: adjust for fs context
:param str pool_id: pool id override
:param settings.StorageCredentialsSettings sc: storage creds
"""
bs = settings.batch_shipyard_settings(config)
if sc is None:
sc = settings.credentials_storage(config, bs.storage_account_settings)
if fs_storage:
# set postfix to empty for now, it will be populated with the
# storage cluster during the actual calls
postfix = ''
if util.is_not_empty(pool_id):
raise ValueError('pool id specified for fs_storage')
else:
bc = settings.credentials_batch(config)
if util.is_none_or_empty(pool_id):
pool_id = settings.pool_id(config, lower=True)
postfix = '-'.join((bc.account.lower(), pool_id))
storage.set_storage_configuration(
bs.storage_entity_prefix,
postfix,
sc.account,
sc.account_key,
sc.endpoint,
bs.generated_sas_expiry_days)
def fetch_credentials_conf_from_keyvault(
keyvault_client, keyvault_uri, keyvault_credentials_secret_id):
# type: (azure.keyvault.KeyVaultClient, str, str) -> dict
"""Fetch a credentials conf from keyvault
:param azure.keyvault.KeyVaultClient keyvault_client: keyvault client
:param str keyvault_uri: keyvault uri
:param str keyvault_credentials_secret_id: keyvault cred secret id
:rtype: dict
:return: credentials conf
"""
if keyvault_uri is None:
raise ValueError('credentials conf was not specified or is invalid')
if keyvault_client is None:
raise ValueError('no Azure KeyVault or AAD credentials specified')
return keyvault.fetch_credentials_conf(
keyvault_client, keyvault_uri, keyvault_credentials_secret_id)
def fetch_secrets_from_keyvault(keyvault_client, config):
# type: (azure.keyvault.KeyVaultClient, dict) -> None
"""Fetch secrets with secret ids in config from keyvault
:param azure.keyvault.KeyVaultClient keyvault_client: keyvault client
:param dict config: configuration dict
"""
if keyvault_client is not None:
keyvault.parse_secret_ids(keyvault_client, config)
def fetch_storage_account_keys_from_aad(
storage_mgmt_client, config, fs_storage):
# type: (azure.mgmt.storage.StorageManagementClient, dict, bool) -> None
"""Fetch secrets with secret ids in config from keyvault
:param azure.mgmt.storage.StorageManagementClient storage_mgmt_client:
storage client
:param dict config: configuration dict
:param bool fs_storage: adjust for fs context
"""
if storage.populate_storage_account_keys_from_aad(
storage_mgmt_client, config):
populate_global_settings(config, fs_storage)
def _download_file(desc, pkg, dldict):
# type: (str, pathlib.Path, dict) -> None
"""Download a file and check sha256
:param str desc: description
:param pathlib.Path pkg: package
:param dict dldict: download dict
"""
logger.debug('downloading {} to {}'.format(desc, dldict['target']))
response = requests.get(dldict['url'], stream=True)
with pkg.open('wb') as f:
for chunk in response.iter_content(chunk_size=_REQUEST_CHUNK_SIZE):
if chunk:
f.write(chunk)
logger.debug('wrote {} bytes to {}'.format(pkg.stat().st_size, pkg))
# check sha256
if util.compute_sha256_for_file(pkg, False) != dldict['sha256']:
raise RuntimeError('sha256 mismatch for {}'.format(pkg))
def _setup_nvidia_driver_package(config, vm_size):
# type: (dict, str) -> pathlib.Path
"""Set up the nvidia driver package
:param dict config: configuration dict
:param str vm_size: vm size
:rtype: pathlib.Path
:return: package path
"""
gpu_type = settings.get_gpu_type_from_vm_size(vm_size)
pkg = _RESOURCES_PATH / _NVIDIA_DRIVER[gpu_type]['target']
# check to see if package is downloaded
if (not pkg.exists() or
util.compute_sha256_for_file(pkg, False) !=
_NVIDIA_DRIVER[gpu_type]['sha256']):
# display license link
if not util.confirm_action(
config,
msg=('agreement with License for Customer Use of NVIDIA '
'Software @ {}').format(_NVIDIA_DRIVER['license']),
allow_auto=True):
raise RuntimeError(
'Cannot proceed with deployment due to non-agreement with '
'license for NVIDIA driver')
else:
logger.info('NVIDIA Software License accepted')
# download driver
_download_file('NVIDIA driver', pkg, _NVIDIA_DRIVER[gpu_type])
return pkg
def _setup_intel_mpi_rt_package(config, pool_settings):
# type: (dict, settings.PoolSettings) -> pathlib.Path
"""Set up the intel mpi runtime package
:param dict config: configuration dict
:param settings.PoolSettings pool_settings: pool settings
:rtype: pathlib.Path
:return: package path
"""
# only for native ubuntu rdma
if (not settings.is_rdma_pool(pool_settings.vm_size) or
not pool_settings.vm_configuration.offer ==
'ubuntu-server-container-rdma'):
return None
pkg = _RESOURCES_PATH / _INTEL_MPI_RT_PACKAGE['target']
# check to see if package is downloaded
if (not pkg.exists() or
util.compute_sha256_for_file(pkg, False) !=
_INTEL_MPI_RT_PACKAGE['sha256']):
# display license link
if not util.confirm_action(
config,
msg=('agreement with Intel Simplified Software License @ '
'{}').format(_INTEL_MPI_RT_PACKAGE['license']),
allow_auto=True):
raise RuntimeError(
'Cannot proceed with deployment due to non-agreement with '
'license for Intel MPI Runtime')
else:
logger.info('Intel Simplified Software License accepted')
# download package
_download_file('Intel MPI Runtime', pkg, _INTEL_MPI_RT_PACKAGE)
return pkg
def _setup_lis_package(config, vm_size):
# type: (dict, str) -> pathlib.Path
"""Set up the LIS package
:param dict config: configuration dict
:param str vm_size: vm size
:rtype: pathlib.Path
:return: package path
"""
# check to see if lis is required first
if not settings.is_lis_install_required(config, vm_size=vm_size):
return None
pkg = _RESOURCES_PATH / _LIS_PACKAGE['target']
compact_pkg = _RESOURCES_PATH / _LIS_PACKAGE['target_compact']
# check to see if package is downloaded
if (not compact_pkg.exists() or not pkg.exists() or
util.compute_sha256_for_file(pkg, False) !=
_LIS_PACKAGE['sha256']):
_download_file('LIS package', pkg, _LIS_PACKAGE)
logger.debug('compacting LIS package')
util.subprocess_with_output(
'gunzip -f -k {}'.format(pkg), shell=True, suppress_output=True)
tmp = pkg.parent / pkg.stem
inter = pkg.parent / _LIS_PACKAGE['intermediate']
tmp.replace(inter)
util.subprocess_with_output(
('tar vf {} --wildcards --delete LISISO/Oracle* '
'--delete LISISO/RHEL* --delete LISISO/CentOS5* '
'--delete LISISO/CentOS6* --delete LISISO/CentOS70* '
'--delete LISISO/CentOS71* --delete LISISO/CentOS72* '
'--delete LISISO/CentOS73* ').format(inter),
shell=True, suppress_output=True)
util.subprocess_with_output(
'gzip -f {}'.format(inter), shell=True, suppress_output=True)
logger.debug('LIS package compacted: {} => {} bytes'.format(
compact_pkg, compact_pkg.stat().st_size))
return compact_pkg
def setup_prometheus_node_exporter():
# type: (None) -> pathlib.Path
"""Setup node exporter package
:return ne package
"""
ne_pkg = _RESOURCES_PATH / _PROMETHEUS['node_exporter']['target']
if (not ne_pkg.exists() or
util.compute_sha256_for_file(ne_pkg, False) !=
_PROMETHEUS['node_exporter']['sha256']):
_download_file(
'Prometheus Node Exporter', ne_pkg,
_PROMETHEUS['node_exporter'])
return ne_pkg
def _setup_prometheus_monitoring_tools(pool_settings):
# type: settings.PoolSettings -> Tuple[pathlib.Path, pathlib.Path]
"""Setup the prometheus monitoring tools
:param settings.PoolSettings pool_settings: pool settings
:rtype: tuple
:return: tuple of ne_pkg, ca_pkg
"""
ne_pkg = None
ca_pkg_compact = None
if pool_settings.prometheus.ne_enabled:
ne_pkg = setup_prometheus_node_exporter()
if pool_settings.prometheus.ca_enabled:
ca_pkg = _RESOURCES_PATH / _PROMETHEUS['cadvisor']['target']
ca_pkg_compact = (
_RESOURCES_PATH / _PROMETHEUS['cadvisor']['target_compact']
)
if (not ca_pkg.exists() or not ca_pkg_compact.exists() or
util.compute_sha256_for_file(ca_pkg, False) !=
_PROMETHEUS['cadvisor']['sha256']):
_download_file('cAdvisor', ca_pkg, _PROMETHEUS['cadvisor'])
logger.debug('compacting cAdvisor package')
util.subprocess_with_output(
'gzip -f -k {}'.format(ca_pkg), shell=True,
suppress_output=True)
logger.debug('cAdvisor package compacted: {} => {} bytes'.format(
ca_pkg_compact, ca_pkg_compact.stat().st_size))
return ne_pkg, ca_pkg_compact
def _generate_azure_mount_script_name(
batch_account_name, pool_id, is_file_share, is_windows):
# type: (str, str, bool, bool) -> pathlib.Path
"""Generate an azure blob/file mount script name
:param str batch_account_name: batch account name
:param str pool_id: pool id
:param boo is_file_share: is file share
:param bool is_windows: is windows
:rtype: pathlib.Path
:return: path to azure mount script
"""
if is_file_share:
prefix = 'azurefile'
else:
prefix = 'azureblob'
return _RESOURCES_PATH / '{}-mount-{}-{}.{}'.format(
prefix, batch_account_name.lower(), pool_id.lower(),
'cmd' if is_windows else 'sh')
def _setup_azureblob_mounts(blob_client, config, bc):
# type: (azure.storage.blob.BlockBlobService, dict,
# settings.BatchCredentials) -> tuple
"""Set up the Azure Blob container via blobfuse
:param azure.storage.blob.BlockBlobService blob_client: blob client
:param dict config: configuration dict
:param settings.BatchCredentials bc: batch creds
:rtype: tuple
:return: (bin path, service file path, service env file path,
volume creation script path)
"""
tmpmount = settings.temp_disk_mountpoint(config)
# construct mount commands
cmds = []
sdv = settings.global_resources_shared_data_volumes(config)
for svkey in sdv:
if settings.is_shared_data_volume_azure_blob(sdv, svkey):
sa = settings.credentials_storage(
config,
settings.azure_storage_account_settings(sdv, svkey))
cont = settings.azure_blob_container_name(sdv, svkey)
hmp = settings.azure_blob_host_mount_path(sa.account, cont)
sas = storage.create_blob_container_saskey(
sa, cont, 'egress', create_container=True)
tmpmp = '{}/blobfuse-tmp/{}-{}'.format(tmpmount, sa.account, cont)
cmds.append('mkdir -p {}'.format(hmp))
cmds.append('chmod 0770 {}'.format(hmp))
cmds.append('mkdir -p {}'.format(tmpmp))
cmds.append('chown _azbatch:_azbatchgrp {}'.format(tmpmp))
cmds.append('chmod 0770 {}'.format(tmpmp))
cmds.append('export AZURE_STORAGE_ACCOUNT="{}"'.format(sa.account))
cmds.append('export AZURE_STORAGE_SAS_TOKEN="{}"'.format(sas))
cmd = (
'blobfuse {hmp} --container-name={cont} '
'--tmp-path={tmpmp} -o allow_other'
).format(hmp=hmp, cont=cont, tmpmp=tmpmp)
# add any additional mount options
mo = settings.shared_data_volume_mount_options(sdv, svkey)
if util.is_not_empty(mo):
opts = []
for opt in mo:
if opt.strip() == '-o allow_other':
continue
opts.append(opt)
cmd = '{} {}'.format(cmd, ' '.join(opts))
if '-o attr_timeout=' not in cmd:
cmd = '{} -o attr_timeout=240'.format(cmd)
if '-o entry_timeout=' not in cmd:
cmd = '{} -o entry_timeout=240'.format(cmd)
if '-o negative_timeout=' not in cmd:
cmd = '{} -o negative_timeout=120'.format(cmd)
cmds.append(cmd)
# create file share mount command script
if util.is_none_or_empty(cmds):
raise RuntimeError('Generated Azure blob mount commands are invalid')
volcreate = _generate_azure_mount_script_name(
bc.account, settings.pool_id(config), False, False)
newline = '\n'
with volcreate.open('w', newline=newline) as f:
f.write('#!/usr/bin/env bash')
f.write(newline)
f.write('set -e')
f.write(newline)
f.write('set -o pipefail')
f.write(newline)
for cmd in cmds:
f.write(cmd)
f.write(newline)
return volcreate
def _setup_azurefile_mounts(blob_client, config, bc, is_windows):
# type: (azure.storage.blob.BlockBlobService, dict,
# settings.BatchCredentials, bool) -> tuple
"""Set up the Azure File shares
:param azure.storage.blob.BlockBlobService blob_client: blob client
:param dict config: configuration dict
:param settings.BatchCredentials bc: batch creds
:param bool is_windows: is windows pool
:rtype: tuple
:return: (bin path, service file path, service env file path,
volume creation script path)
"""
# construct mount commands
cmds = []
sdv = settings.global_resources_shared_data_volumes(config)
for svkey in sdv:
if settings.is_shared_data_volume_azure_file(sdv, svkey):
sa = settings.credentials_storage(
config,
settings.azure_storage_account_settings(sdv, svkey))
share = settings.azure_file_share_name(sdv, svkey)
hmp = settings.azure_file_host_mount_path(
sa.account, share, is_windows)
if is_windows:
cmd = (
'net use \\\\{sa}.file.{ep}\{share} {sakey} ' # noqa
'/user:Azure\{sa}'
).format(
sa=sa.account, ep=sa.endpoint, share=share,
sakey=sa.account_key)
cmds.append(cmd)
cmd = (
'mklink /d {hmp} \\\\{sa}.file.{ep}\{share}'.format( # noqa
hmp=hmp, sa=sa.account, ep=sa.endpoint, share=share)
)
else:
cmd = (
'mount -t cifs //{sa}.file.{ep}/{share} {hmp} -o '
'vers=3.0,username={sa},password={sakey},'
'serverino'
).format(
sa=sa.account, ep=sa.endpoint, share=share, hmp=hmp,
sakey=sa.account_key)
# add any additional mount options
mo = settings.shared_data_volume_mount_options(sdv, svkey)
if util.is_not_empty(mo):
opts = []
# retain backward compatibility with filemode/dirmode
# options from the old Azure File Docker volume driver
for opt in mo:
tmp = opt.split('=')
if tmp[0] == 'filemode':
opts.append('file_mode={}'.format(tmp[1]))
elif tmp[0] == 'dirmode':
opts.append('dir_mode={}'.format(tmp[1]))
else:
opts.append(opt)
cmd = '{},{}'.format(cmd, ','.join(opts))
if not is_windows:
cmds.append('mkdir -p {}'.format(hmp))
cmds.append(cmd)
# create file share mount command script
if util.is_none_or_empty(cmds):
raise RuntimeError('Generated Azure file mount commands are invalid')
volcreate = _generate_azure_mount_script_name(
bc.account, settings.pool_id(config), True, is_windows)
newline = '\r\n' if is_windows else '\n'
with volcreate.open('w', newline=newline) as f:
if is_windows:
f.write('@echo off')
f.write(newline)
else:
f.write('#!/usr/bin/env bash')
f.write(newline)
f.write('set -e')
f.write(newline)
f.write('set -o pipefail')
f.write(newline)
for cmd in cmds:
f.write(cmd)
f.write(newline)
return volcreate
def _create_storage_cluster_mount_args(
compute_client, network_client, batch_mgmt_client, config, sc_id,
bc, subnet_id):
# type: (azure.mgmt.compute.ComputeManagementClient,
# azure.mgmt.network.NetworkManagementClient,
# azure.mgmt.batch.BatchManagementClient, dict, str,
# settings.BatchCredentials, str) -> Tuple[str, str]
"""Create storage cluster mount arguments
:param azure.mgmt.compute.ComputeManagementClient compute_client:
compute client
:param azure.mgmt.network.NetworkManagementClient network_client:
network client
:param azure.mgmt.batch.BatchManagementClient: batch_mgmt_client
:param dict config: configuration dict
:param str sc_id: storage cluster id
:param settings.BatchCredentials bc: batch creds
:param str subnet_id: subnet id
:rtype: tuple
:return: (fstab mount, storage cluster arg)
"""
fstab_mount = None
sc_arg = None
ba, _ = batch.get_batch_account(batch_mgmt_client, config)
# check for vnet/subnet presence
if util.is_none_or_empty(subnet_id):
raise RuntimeError(
'cannot mount a storage cluster without a valid virtual '
'network or subnet')
# get remotefs settings
rfs = settings.remotefs_settings(config, sc_id)
sc = rfs.storage_cluster
# iterate through shared data volumes and fine storage clusters
sdv = settings.global_resources_shared_data_volumes(config)
if (sc_id not in sdv or
not settings.is_shared_data_volume_storage_cluster(
sdv, sc_id)):
raise RuntimeError(
'No storage cluster {} found in configuration'.format(sc_id))
vnet_subid, vnet_rg, _, vnet_name, subnet_name = _explode_arm_subnet_id(
subnet_id)
# check for same vnet name
if vnet_name.lower() != sc.virtual_network.name.lower():
raise RuntimeError(
'cannot link storage cluster {} on virtual '
'network {} with pool virtual network {}'.format(
sc_id, sc.virtual_network.name, vnet_name))
# cross check vnet resource group
if vnet_rg.lower() != sc.virtual_network.resource_group.lower():
raise RuntimeError(
'cannot link storage cluster {} virtual network in resource group '
'{} with pool virtual network in resource group {}'.format(
sc_id, sc.virtual_network.resource_group, vnet_rg))
# cross check vnet subscription id
_ba_tmp = ba.id.lower().split('/')
if vnet_subid.lower() != _ba_tmp[2]:
raise RuntimeError(
'cannot link storage cluster {} virtual network in subscription '
'{} with pool virtual network in subscription {}'.format(
sc_id, vnet_subid, _ba_tmp[2]))
del _ba_tmp
# get vm count
if sc.vm_count < 1:
raise RuntimeError(
'storage cluster {} vm_count {} is invalid'.format(
sc_id, sc.vm_count))
# get fileserver type
if sc.file_server.type == 'nfs':
# query first vm for info
vm_name = settings.generate_virtual_machine_name(sc, 0)
vm = compute_client.virtual_machines.get(
resource_group_name=sc.resource_group,
vm_name=vm_name,
)
nic = resource.get_nic_from_virtual_machine(
network_client, sc.resource_group, vm)
# get private ip of vm
remote_ip = nic.ip_configurations[0].private_ip_address
# construct mount options
mo = '_netdev,noauto,nfsvers=4,intr'
amo = settings.shared_data_volume_mount_options(sdv, sc_id)
if util.is_not_empty(amo):
if 'udp' in mo:
raise RuntimeError(
('udp cannot be specified as a mount option for '
'storage cluster {}').format(sc_id))
if 'auto' in mo:
raise RuntimeError(
('auto cannot be specified as a mount option for '
'storage cluster {}').format(sc_id))
if any([x.startswith('nfsvers=') for x in amo]):
raise RuntimeError(
('nfsvers cannot be specified as a mount option for '
'storage cluster {}').format(sc_id))
if any([x.startswith('port=') for x in amo]):
raise RuntimeError(
('port cannot be specified as a mount option for '
'storage cluster {}').format(sc_id))
mo = ','.join((mo, ','.join(amo)))
# construct mount string for fstab
fstab_mount = (
'{remoteip}:{srcpath} {hmp}/{scid} '
'{fstype} {mo} 0 2').format(
remoteip=remote_ip,
srcpath=sc.file_server.mountpoint,
hmp=settings.get_host_mounts_path(False),
scid=sc_id,
fstype=sc.file_server.type,
mo=mo)
elif sc.file_server.type == 'glusterfs':
# walk vms and find non-overlapping ud/fds
primary_ip = None
primary_ud = None
primary_fd = None
backup_ip = None
backup_ud = None
backup_fd = None
vms = {}
# first pass, attempt to populate all ip, ud/fd
for i in range(sc.vm_count):
vm_name = settings.generate_virtual_machine_name(sc, i)
vm = compute_client.virtual_machines.get(
resource_group_name=sc.resource_group,
vm_name=vm_name,
expand=compute_client.virtual_machines.models.
InstanceViewTypes.instance_view,
)
nic = resource.get_nic_from_virtual_machine(
network_client, sc.resource_group, vm)
vms[i] = (vm, nic)
# get private ip and ud/fd of vm
remote_ip = nic.ip_configurations[0].private_ip_address
ud = vm.instance_view.platform_update_domain
fd = vm.instance_view.platform_fault_domain
if primary_ip is None:
primary_ip = remote_ip
primary_ud = ud
primary_fd = fd
if backup_ip is None:
if (primary_ip == backup_ip or primary_ud == ud or
primary_fd == fd):
continue
backup_ip = remote_ip
backup_ud = ud
backup_fd = fd
# second pass, fill in with at least non-overlapping update domains
if backup_ip is None:
for i in range(sc.vm_count):
vm, nic = vms[i]
remote_ip = nic.ip_configurations[0].private_ip_address
ud = vm.instance_view.platform_update_domain
fd = vm.instance_view.platform_fault_domain
if primary_ud != ud:
backup_ip = remote_ip
backup_ud = ud
backup_fd = fd
break
if primary_ip is None or backup_ip is None:
raise RuntimeError(
'Could not find either a primary ip {} or backup ip {} for '
'glusterfs client mount'.format(primary_ip, backup_ip))
logger.debug('primary ip/ud/fd={} backup ip/ud/fd={}'.format(
(primary_ip, primary_ud, primary_fd),
(backup_ip, backup_ud, backup_fd)))
# construct mount options
mo = '_netdev,noauto,transport=tcp,backupvolfile-server={}'.format(
backup_ip)
amo = settings.shared_data_volume_mount_options(sdv, sc_id)
if util.is_not_empty(amo):
if 'auto' in mo:
raise RuntimeError(
('auto cannot be specified as a mount option for '
'storage cluster {}').format(sc_id))
if any([x.startswith('backupvolfile-server=') for x in amo]):
raise RuntimeError(
('backupvolfile-server cannot be specified as a mount '
'option for storage cluster {}').format(sc_id))
if any([x.startswith('transport=') for x in amo]):
raise RuntimeError(
('transport cannot be specified as a mount option for '
'storage cluster {}').format(sc_id))
mo = ','.join((mo, ','.join(amo)))
# construct mount string for fstab, srcpath is the gluster volume
fstab_mount = (
'{remoteip}:/{srcpath} {hmp}/{scid} '
'{fstype} {mo} 0 2').format(
remoteip=primary_ip,
srcpath=settings.get_file_server_glusterfs_volume_name(sc),
hmp=settings.get_host_mounts_path(False),
scid=sc_id,
fstype=sc.file_server.type,
mo=mo)
else:
raise NotImplementedError(
('cannot handle file_server type {} for storage '
'cluster {}').format(sc.file_server.type, sc_id))
if util.is_none_or_empty(fstab_mount):
raise RuntimeError(
('Could not construct an fstab mount entry for storage '
'cluster {}').format(sc_id))
# construct sc_arg
sc_arg = '{}:{}'.format(sc.file_server.type, sc_id)
# log config
if settings.verbose(config):
logger.debug('storage cluster {} fstab mount: {}'.format(
sc_id, fstab_mount))
return (fstab_mount, sc_arg)
def _create_custom_linux_mount_args(config, mount_name):
# type: (dict, str) -> str
"""Create a custom linux mount fstab entry
:param dict config: configuration dict
:param str mount_name: mount name
:rtype: str
:return: fstab entry
"""
sdv = settings.global_resources_shared_data_volumes(config)
fstab = settings.custom_linux_mount_fstab_options(sdv, mount_name)
if 'noauto' in fstab.fs_mntops:
raise RuntimeError(
('noauto cannot be specified as a mount option for custom '
'linux mount {}').format(mount_name))
elif 'auto' in fstab.fs_mntops:
raise RuntimeError(
('auto cannot be specified as a mount option for custom '
'linux mount {}').format(mount_name))
fstab_mount = (
'{fs_spec} {hmp}/{name} {fs_vfstype} noauto,{fs_mntops} {fs_freq} '
'{fs_passno}').format(
fs_spec=fstab.fs_spec,
hmp=settings.get_host_mounts_path(False),
name=mount_name,
fs_vfstype=fstab.fs_vfstype,
fs_mntops=fstab.fs_mntops,
fs_freq=fstab.fs_freq,
fs_passno=fstab.fs_passno)
return fstab_mount
def _pick_node_agent_for_vm(batch_client, config, pool_settings):
# type: (azure.batch.batch_service_client.BatchServiceClient,
# dict, settings.PoolSettings) -> (str, str)
"""Pick a node agent id for the vm
:param azure.batch.batch_service_client.BatchServiceClient batch_client:
batch client
:param dict config: configuration dict
:param settings.PoolSettings pool_settings: pool settings
:rtype: tuple
:return: image reference to use, node agent id to use
"""
publisher = pool_settings.vm_configuration.publisher
offer = pool_settings.vm_configuration.offer
sku = pool_settings.vm_configuration.sku
# backward compat for CentOS HPC 7.1, 7.3 and normal 7.4, 7.5
if publisher == 'openlogic':
if ((offer == 'centos-hpc' and
(sku == '7.1' or sku == '7.3')) or
(offer == 'centos' and (sku == '7.4' or sku == '7.5'))):
return ({
'publisher': publisher,
'offer': offer,
'sku': sku,
'version': pool_settings.vm_configuration.version,
}, 'batch.node.centos 7')
# support windows server semi annual
if (publisher == 'microsoftwindowsserver' and
offer == 'windowsserversemiannual' and 'with-containers' in sku):
return ({
'publisher': publisher,
'offer': offer,
'sku': sku,
'version': pool_settings.vm_configuration.version,
}, 'batch.node.windows amd64')
# pick latest sku
node_agent_skus = batch_client.account.list_node_agent_skus()
skus_to_use = [
(nas, image_ref) for nas in node_agent_skus
for image_ref in sorted(
nas.verified_image_references,
key=lambda item: item.sku
)
if image_ref.publisher.lower() == publisher and
image_ref.offer.lower() == offer and
image_ref.sku.lower() == sku
]
try:
sku_to_use, image_ref_to_use = skus_to_use[-1]
except IndexError:
raise RuntimeError(
('Could not find an Azure Batch Node Agent Sku for this '
'offer={} publisher={} sku={}. You can list the valid and '
'available Marketplace images with the command: pool '
'listskus').format(
pool_settings.vm_configuration.offer,
pool_settings.vm_configuration.publisher,