-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathshared.py
executable file
·3434 lines (2749 loc) · 140 KB
/
shared.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
#
# shared.py - common functions, classes, and variables for Vac
#
# Andrew McNab, University of Manchester.
# Copyright (c) 2013-8. All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# o Redistributions of source code must retain the above
# copyright notice, this list of conditions and the following
# disclaimer.
# o Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials
# provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
# CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Contacts: [email protected] http://www.gridpp.ac.uk/vac/
#
import re
import os
import sys
import pwd
import uuid
import time
import glob
import errno
import ctypes
import base64
import shutil
import string
import signal
import hashlib
import subprocess
import StringIO
import urllib
import datetime
import tempfile
import socket
import stat
import pycurl
import libvirt
import ConfigParser
import json
json.encoder.FLOAT_REPR = lambda f: ("%.2f" % f)
import vac
class VacError(Exception):
pass
# All VacQuery requests and responses are in this file
# so we can define the VacQuery protocol version here.
# 01.00 is the one described in HSF-TN-2016-04
# 01.01 has daemon_* and processor renames
# 01.02 adds num_processors to machine_status
# 01.03 adds machine_model to machine_status
vacQueryVersion = '01.03'
vmModels = [ 'cernvm3', 'cernvm4', 'vm-raw' ] # Virtual Machine models
dcModels = [ 'docker' ] # Docker Container models
scModels = [ 'singularity' ] # Singularity Container models
lmModels = vmModels + dcModels + scModels # All Logical Machine models
dockerPath = '/usr/bin/docker'
singularityPath = '/usr/bin/singularity'
natNetwork = '169.254.0.0'
natNetmask = '255.255.0.0'
natPrefix = '169.254.169.'
metaAddress = '169.254.169.254'
mjfAddress = '169.254.169.253'
factoryAddress = mjfAddress
dummyAddress = metaAddress
udpBufferSize = 16777216
gbDiskPerProcessorDefault = 40
singularityUser = None
singularityUid = None
singularityGid = None
cpuCgroupFsRoot = None
memoryCgroupFsRoot = None
overloadPerProcessor = None
gocdbSitename = None
gocdbCertFile = None
gocdbKeyFile = None
gocdbUpdateSeconds = 86400
censusUpdateSeconds = 3600
factories = None
hs06PerProcessor = None
mbPerProcessor = None
fixNetworking = None
forwardDev = None
shutdownTime = None
draining = None
numMachineSlots = None
numProcessors = None
processorCount = None
spaceName = None
spaceDesc = None
udpTimeoutSeconds = None
vacqueryTries = 5
vacVersion = None
processorsPerSuperslot = None
versionLogger = None
machinetypes = None
vacmons = None
rootPublicKeyFile = None
volumeGroup = None
gbDiskPerProcessor = None
machinefeaturesOptions = None
def readConf(includePipes = False, updatePipes = False, checkVolumeGroup = False, printConf = False):
global gocdbSitename, gocdbCertFile, gocdbKeyFile, \
factories, hs06PerProcessor, mbPerProcessor, fixNetworking, forwardDev, shutdownTime, draining, \
numMachineSlots, numProcessors, processorCount, spaceName, spaceDesc, udpTimeoutSeconds, vacVersion, \
processorsPerSuperslot, versionLogger, machinetypes, vacmons, rootPublicKeyFile, \
singularityUser, singularityUid, singularityGid, \
volumeGroup, gbDiskPerProcessor, overloadPerProcessor, fixNetworking, machinefeaturesOptions
# reset to defaults
overloadPerProcessor = 1.25
gocdbSitename = None
gocdbCertFile = None
gocdbKeyFile = None
factories = []
hs06PerProcessor = None
mbPerProcessor = 2048
fixNetworking = True
forwardDev = None
shutdownTime = None
draining = False
processorCount = countProcProcessors()
numMachineSlots = processorCount
numProcessors = None
spaceName = None
spaceDesc = None
udpTimeoutSeconds = 10.0
vacVersion = '0.0.0'
processorsPerSuperslot = 1
versionLogger = 1
machinetypes = {}
vacmons = []
rootPublicKeyFile = '/root/.ssh/id_rsa.pub'
singularityUser = None
volumeGroup = None
machinefeaturesOptions = {}
# Temporary dictionary of common user_data_option_XXX
machinetypeCommon = {}
try:
f = open('/var/lib/vac/VERSION', 'r')
vacVersion = f.readline().split('=',1)[1].strip()
f.close()
except:
pass
if not '.' in os.uname()[1]:
return 'The hostname of the factory machine must be a fully qualified domain name!'
parser = ConfigParser.RawConfigParser()
# Look for configuration files in /etc/vac.d
try:
confFiles = os.listdir('/etc/vac.d')
except:
pass
else:
for oneFile in sorted(confFiles):
if oneFile[-5:] == '.conf':
parser.read('/etc/vac.d/' + oneFile)
# Standalone configuration file, read after vac.d in case of manual overrides
parser.read('/etc/vac.conf')
# Very last configuration file, which will be deleted at next boot
parser.read('/var/run/vac.conf')
# general settings from [Settings] section
if not parser.has_section('settings'):
return 'Must have a settings section!'
# Must have a space name
if not parser.has_option('settings', 'vac_space'):
return 'Must give vac_space in [settings]!'
spaceName = parser.get('settings','vac_space').strip()
if parser.has_option('settings', 'description'):
spaceDesc = parser.get('settings','description').strip()
if parser.has_option('settings', 'gocdb_sitename'):
gocdbSitename = parser.get('settings','gocdb_sitename').strip()
if parser.has_option('settings', 'gocdb_cert_file'):
gocdbCertFile = parser.get('settings','gocdb_cert_file').strip()
if parser.has_option('settings', 'gocdb_key_file'):
gocdbKeyFile = parser.get('settings','gocdb_key_file').strip()
if parser.has_option('settings', 'domain_type'):
print 'domain_type is deprecated - please remove from the Vac configuration!'
if parser.has_option('settings', 'cpu_total'):
# Option limit on number of processors Vac can allocate.
numProcessors = int(parser.get('settings','cpu_total').strip())
print 'cpu_total is deprecated - please use total_processors instead!'
# Check setting against counted number
if numProcessors > processorCount:
return 'cpu_total cannot be greater than number of processors!'
elif parser.has_option('settings', 'total_processors'):
# Option limit on number of processors Vac can allocate.
numProcessors = int(parser.get('settings','total_processors').strip())
# Check setting against counted number
if numProcessors > processorCount:
return 'total_processors cannot be greater than number of processors!'
else:
# Defaults to count from /proc/cpuinfo
numProcessors = processorCount
if parser.has_option('settings', 'total_machines'):
print 'total_machines is deprecated. Please use total_processors in [settings] to control number of VMs'
if parser.has_option('settings', 'overload_per_cpu'):
# Multiplier to calculate overload veto against creating more VMs
print 'overload_per_cpu is deprecated - please use overload_per_processor!'
overloadPerProcessor = float(parser.get('settings','overload_per_cpu'))
elif parser.has_option('settings', 'overload_per_processor'):
# Multiplier to calculate overload veto against creating more VMs
overloadPerProcessor = float(parser.get('settings','overload_per_processor'))
if parser.has_option('settings', 'singularity_user'):
singularityUser = parser.get('settings','singularity_user').strip()
try:
pwdStruct = pwd.getpwnam(singularityUser)
singularityUid = pwdStruct[2]
singularityGid = pwdStruct[3]
except:
return 'Singularity user %s does not exist!' % singularityUser
if singularityUid == 0:
return 'You cannot use root as the Singularity user!'
if parser.has_option('settings', 'volume_group'):
# Volume group to search for logical volumes
volumeGroup = parser.get('settings','volume_group').strip()
if checkVolumeGroup:
if volumeGroup:
if not measureVolumeGroup(volumeGroup):
# If volume_group is given, then it must exist
return 'Specified volume_group %s does not exist!' % volumeGroup
elif measureVolumeGroup('vac_volume_group'):
# If volume_group is not given, then it's ok if default does not exist
# but we use it if it does exist
volumeGroup = 'vac_volume_group'
if parser.has_option('settings', 'scratch_gb'):
# Deprecated
gbDiskPerProcessor = int(parser.get('settings','scratch_gb').strip())
print 'scratch_gb is deprecated. Please use disk_gb_per_processor in [settings] instead'
elif parser.has_option('settings', 'disk_gb_per_cpu'):
# Size in GB/cpu (1000^3) of disk assigned to machines, default is 40
gbDiskPerProcessor = int(parser.get('settings','disk_gb_per_cpu').strip())
print 'disk_gb_per_cpu is deprecated - please use disk_gb_per_processor!'
elif parser.has_option('settings', 'disk_gb_per_processor'):
# Size in GB/cpu (1000^3) of disk assigned to machines, default is 40
gbDiskPerProcessor = int(parser.get('settings','disk_gb_per_processor').strip())
if parser.has_option('settings', 'udp_timeout_seconds'):
# How long to wait before giving up on more UDP replies
udpTimeoutSeconds = float(parser.get('settings','udp_timeout_seconds').strip())
if (parser.has_option('settings', 'fix_networking') and
parser.get('settings','fix_networking').strip().lower() == 'false'):
fixNetworking = False
else:
fixNetworking = True
if parser.has_option('settings', 'root_public_key'):
rootPublicKeyFile = parser.get('settings', 'root_public_key').strip()
if parser.has_option('settings', 'forward_dev'):
forwardDev = parser.get('settings','forward_dev').strip()
if parser.has_option('settings', 'version_logger'):
# deprecated true/false then integer messages per day
if parser.get('settings','version_logger').strip().lower() == 'true':
print 'version_logger in [settings] now takes an integer rather true/false'
versionLogger = 1
elif parser.get('settings','version_logger').strip().lower() == 'false':
print 'version_logger in [settings] now takes an integer rather true/false'
versionLogger = 0
else:
try:
versionLogger = int(parser.get('settings','version_logger').strip())
except:
versionLogger = 0
if parser.has_option('settings', 'vacmon_hostport'):
try:
vacmons = parser.get('settings','vacmon_hostport').lower().split()
except:
return 'Failed to parse vacmon_hostport'
for v in vacmons:
if re.search('^[a-z0-9.-]+:[0-9]+$', v) is None:
return 'Failed to parse vacmon_hostport: must be host.domain:port'
if parser.has_option('settings', 'delete_old_files'):
print 'Old files are now always deleted: please remove delete_old_files from [settings]'
if parser.has_option('settings', 'vcpu_per_machine'):
# Warn that this deprecated
processorsPerSuperslot = int(parser.get('settings','vcpu_per_machine'))
print 'vcpu_per_machine is deprecated: please use processors_per_superslot in [settings]'
elif parser.has_option('settings', 'cpu_per_machine'):
processorsPerSuperslot = int(parser.get('settings','cpu_per_machine'))
print 'cpu_per_machine is deprecated: please use processors_per_superslot in [settings]'
if parser.has_option('settings', 'processors_per_superslot'):
# If this isn't set, then we allocate one cpu per superslot
processorsPerSuperslot = int(parser.get('settings','processors_per_superslot'))
if parser.has_option('settings', 'mb_per_cpu'):
# If this isn't set, then we use default (2048 MiB)
mbPerProcessor = int(parser.get('settings','mb_per_cpu'))
print 'mb_per_cpu is deprecated - please use mb_per_processor!'
elif parser.has_option('settings', 'mb_per_processor'):
# If this isn't set, then we use default (2048 MiB)
mbPerProcessor = int(parser.get('settings','mb_per_processor'))
if parser.has_option('settings', 'shutdown_time'):
try:
shutdownTime = int(parser.get('settings','shutdown_time'))
except:
return 'Failed to parse shutdown_time (must be a Unix time seconds date/time)'
if parser.has_option('settings', 'draining'):
if parser.get('settings','draining').lower() == 'yes':
draining = True
if parser.has_option('settings', 'hs06_per_cpu'):
hs06PerProcessor = float(parser.get('settings','hs06_per_cpu'))
print 'hs06_per_cpu is deprecated - please use hs06_per_processor!'
elif parser.has_option('settings', 'hs06_per_processor'):
hs06PerProcessor = float(parser.get('settings','hs06_per_processor'))
else:
# If this isn't set, then we will use the default 1.0 per processor
hs06PerProcessor = None
try:
# Get list of factory machines to query via UDP. Leave an empty list if none.
factories = (parser.get('settings', 'factories')).lower().split()
except:
if parser.has_option('factories', 'names'):
return 'Please use the factories option within [settings] rather than a separate [factories] section! See the Admin Guide for details.'
# additional machinefeatures key/value pairs
for (oneOption,oneValue) in parser.items('settings'):
if oneOption[0:23] == 'machinefeatures_option_':
if string.translate(oneOption, None, '0123456789abcdefghijklmnopqrstuvwxyz_') != '':
return 'Name of machinefeatures_option_xxx (' + oneOption + ') must only contain a-z 0-9 and _'
else:
machinefeaturesOptions[oneOption[23:]] = parser.get('settings', oneOption)
# set up commmon user_data_option_XXX subsitutions for all machinetypes
for (oneOption,oneValue) in parser.items('settings'):
if (oneOption[0:17] == 'user_data_option_') or (oneOption[0:15] == 'user_data_file_'):
if string.translate(oneOption, None, '0123456789abcdefghijklmnopqrstuvwxyz_') != '':
return 'Name of user_data_option_xxx (' + oneOption + ') in [settings] must only contain a-z 0-9 and _'
else:
machinetypeCommon[oneOption] = parser.get('settings', oneOption)
# find and process vacuum_pipe sections
if includePipes:
for sectionName in parser.sections():
sectionNameSplit = sectionName.lower().split(None,1)
if sectionNameSplit[0] == 'vacuum_pipe':
machinetypeNamePrefix = sectionNameSplit[1]
if string.translate(machinetypeNamePrefix, None, '0123456789abcdefghijklmnopqrstuvwxyz-') != '':
return 'Name of vacuum_pipe section [vacuum_pipe ' + machinetypeNamePrefix + '] can only contain a-z 0-9 or -'
try:
vacuumPipeURL = parser.get(sectionName, 'vacuum_pipe_url').strip()
except:
return 'Section [vacuum_pipe ' + machinetypeNamePrefix + '] must contain a vacuum_pipe_url option!'
try:
totalTargetShare = float(parser.get(sectionName, 'target_share').strip())
except:
totalTargetShare = 0.0
try:
vacuumPipe = vac.vacutils.readPipe('/var/lib/vac/pipescache/' + machinetypeNamePrefix + '.pipe',
vacuumPipeURL, 'Vac ' + vacVersion, updatePipes = updatePipes)
except Exception as e:
# If a vacuum pipe is given but cannot be read then skip
print "Cannot read vacuum_pipe_url (" + vacuumPipeURL + ": " + str(e) + ") - no machinetypes created!"
continue
if not 'machinetypes' in vacuumPipe:
continue
# Process the contents of this pipe: "machinetypes" is a list of dictionaries, one per machinetype
totalPipeTargetShare = 0.0
# First pass to get total target shares
for pipeMachinetype in vacuumPipe['machinetypes']:
try:
totalPipeTargetShare += float(pipeMachinetype['target_share'])
except:
pass
# Second pass to add options to the relevant machinetype sections
for pipeMachinetype in vacuumPipe['machinetypes']:
try:
suffix = str(pipeMachinetype['suffix'])
except:
print "suffix is missing from one machinetype within " + vacuumPipeURL + " - skipping!"
continue
try:
parser.add_section('machinetype ' + machinetypeNamePrefix + '-' + suffix)
except:
# Ok if it already exists
pass
# Copy almost all options from vacuum_pipe section to this new machinetype
# unless they have already been given. Skip vacuum_pipe_url and target_share
for n,v in parser.items(sectionName):
if n != 'vacuum_pipe_url' and n != 'target_share' and \
not parser.has_option('machinetype ' + machinetypeNamePrefix + '-' + suffix, n):
parser.set('machinetype ' + machinetypeNamePrefix + '-' + suffix, n, v)
# Record path to machinetype used to find the files on local disk
parser.set('machinetype ' + machinetypeNamePrefix + '-' + suffix,
'machinetype_path', '/var/lib/vac/machinetypes/' + machinetypeNamePrefix)
acceptedOptions = [
'accounting_fqan',
'backoff_seconds',
'container_command',
'cvmfs_repositories',
'fizzle_seconds',
'disk_gb_per_processor',
'heartbeat_file',
'heartbeat_seconds',
'image_signing_dn',
'legacy_proxy',
'machine_model',
'max_processors',
'max_wallclock_seconds',
'min_processors',
'min_wallclock_seconds',
'root_device',
'root_image',
'scratch_device',
'suffix',
'target_share',
'tmp_binds',
'user_data',
'user_data_proxy'
]
# Go through vacuumPipe adding options if not already present from configuration files
for optionRaw in pipeMachinetype:
option = str(optionRaw)
value = str(pipeMachinetype[optionRaw])
# Skip if option already exists - configuration files take precedence
if parser.has_option('machinetype ' + machinetypeNamePrefix + '-' + suffix, option):
continue
# Already dealt with
if option == 'suffix':
continue
# Deal with subdividing the total target share for this vacuum pipe here
# Each machinetype gets a share based on its target_share within the pipe
# We do the normalisation of the pipe target_shares here
if option == 'target_share':
try:
targetShare = totalTargetShare * (float(value) / totalPipeTargetShare)
except:
targetShare = 0.0
parser.set('machinetype ' + machinetypeNamePrefix + '-' + suffix, 'target_share', str(targetShare))
continue
# Check option is one we accept
if not option.startswith('user_data_file_' ) and \
not option.startswith('user_data_option_' ) and \
not option in acceptedOptions:
print 'Option %s is not accepted from vacuum pipe - ignoring!' % option
continue
# Any options which specify filenames on the hypervisor must be checked here
if (option.startswith('user_data_file_' ) or
option == 'cvmfs_repositories' or
option == 'heartbeat_file' ) and '/' in value:
print 'Option %s in %s cannot contain a "/" - ignoring!' % (option, vacuumPipeURL)
continue
elif (option == 'user_data' or option == 'root_image') and '/../' in value:
print 'Option %s in %s cannot contain "/../" - ignoring!' % (option, vacuumPipeURL)
continue
elif option == 'user_data' and '/' in value and \
not value.startswith('http://') and \
not value.startswith('https://'):
print 'Option %s in %s cannot contain a "/" unless http(s)://... - ignoring!' % (option, vacuumPipeURL)
continue
elif option == 'root_image' and '/' in value and \
not value.startswith('docker://') and \
not value.startswith('/cvmfs/') and \
not value.startswith('http://') and \
not value.startswith('https://'):
print 'Option %s in %s cannot contain a "/" unless http(s)://... or /cvmfs/... or docker://... - ignoring!' % (option, vacuumPipeURL)
continue
# if all OK, then can set value as if from configuration files
parser.set('machinetype ' + machinetypeNamePrefix + '-' + suffix, option, value)
if printConf:
print 'Configuration including any machinetypes from Vacuum Pipes:'
print
parser.write(sys.stdout)
print
# all other sections are machinetypes (other types of section are ignored)
for sectionName in parser.sections():
sectionNameSplit = sectionName.lower().split(None,1)
# For now, can still define these machinetype sections with [vmtype ...] too
if sectionNameSplit[0] == 'machinetype' or sectionNameSplit[0] == 'vmtype':
if string.translate(sectionNameSplit[1], None, '0123456789abcdefghijklmnopqrstuvwxyz-') != '':
return 'Name of machinetype section [machinetype ' + sectionNameSplit[1] + '] can only contain a-z 0-9 or -'
if sectionNameSplit[0] == 'vmtype':
print '[vmtype ...] is deprecated. Please use [machinetype ' + sectionNameSplit[1] + '] instead'
# Start from any factory-wide common values defined in [settings]
machinetype = machinetypeCommon.copy()
# Now go through the machinetype options, whether from configuration files or vacuum pipes
# Always set machinetype_path, saved in vacuum pipe processing or default using machinetype name
try:
machinetype['machinetype_path'] = parser.get(sectionName, 'machinetype_path').strip()
except:
machinetype['machinetype_path'] = '/var/lib/vac/machinetypes/' + sectionNameSplit[1]
if parser.has_option(sectionName, 'cernvm_signing_dn'):
machinetype['cernvm_signing_dn'] = parser.get(sectionName, 'cernvm_signing_dn').strip()
print 'cernvm_signing_dn is deprecated - please use image_signing_dn'
elif parser.has_option(sectionName, 'image_signing_dn'):
machinetype['image_signing_dn'] = parser.get(sectionName, 'image_signing_dn').strip()
if parser.has_option(sectionName, 'target_share'):
machinetype['share'] = float(parser.get(sectionName, 'target_share'))
elif parser.has_option('targetshares', sectionNameSplit[1]):
return "Please use a target_shares option within [" + sectionName + "] rather than a separate [targetshares] section. You can still group target shares together or put them in a separate file: see the Admin Guide for details."
else:
machinetype['share'] = 0.0
if parser.has_option(sectionName, 'vm_model'):
print 'vm_model is deprecated. Please use machine_model in [' + sectionName + '] instead'
machinetype['machine_model'] = parser.get(sectionName, 'vm_model')
elif parser.has_option(sectionName, 'machine_model'):
machinetype['machine_model'] = parser.get(sectionName, 'machine_model')
else:
machinetype['machine_model'] = 'cernvm3'
if machinetype['machine_model'] not in lmModels:
return 'Machine model %s is not defined!' % machinetype['machine_model']
if parser.has_option(sectionName, 'root_image'):
machinetype['root_image'] = parser.get(sectionName, 'root_image')
if machinetype['root_image'].startswith('docker://') and \
machinetype['machine_model'] not in dcModels:
return 'Can only use a docker:// image URI with Docker machine models!'
if parser.has_option(sectionName, 'root_device'):
if string.translate(parser.get(sectionName, 'root_device'), None, '0123456789abcdefghijklmnopqrstuvwxyz') != '':
print 'root_device can only contain characters a-z 0-9 so skipping machinetype!'
continue
machinetype['root_device'] = parser.get(sectionName, 'root_device')
else:
machinetype['root_device'] = 'vda'
if parser.has_option(sectionName, 'scratch_device'):
if string.translate(parser.get(sectionName, 'scratch_device'), None, '0123456789abcdefghijklmnopqrstuvwxyz') != '':
print 'scratch_device can only contain characters a-z 0-9 so skipping machinetype!'
continue
machinetype['scratch_device'] = parser.get(sectionName, 'scratch_device')
else:
machinetype['scratch_device'] = 'vdb'
if parser.has_option(sectionName, 'rootpublickey'):
print 'The rootpublickey option in ' + sectionName + ' is deprecated; please use root_public_key in [settings]!'
elif parser.has_option(sectionName, 'root_public_key'):
print 'The root_public_key option in ' + sectionName + ' is deprecated; please use root_public_key in [settings]!'
if parser.has_option(sectionName, 'user_data'):
machinetype['user_data'] = parser.get(sectionName, 'user_data')
if parser.has_option(sectionName, 'container_command'):
machinetype['container_command'] = parser.get(sectionName, 'container_command')
else:
machinetype['container_command'] = '/user_data'
if parser.has_option(sectionName, 'tmp_binds'):
machinetype['tmp_binds'] = set(parser.get(sectionName, 'tmp_binds').strip().split())
if parser.has_option(sectionName, 'disk_gb_per_processor'):
# Size in GB/cpu (1000^3) of disk assigned to machines
try:
machinetype['disk_gb_per_processor'] = int(parser.get(sectionName, 'disk_gb_per_processor').strip())
except:
pass
if parser.has_option(sectionName, 'min_processors'):
machinetype['min_processors'] = int(parser.get(sectionName, 'min_processors'))
else:
machinetype['min_processors'] = 1
if parser.has_option(sectionName, 'max_processors'):
machinetype['max_processors'] = int(parser.get(sectionName, 'max_processors'))
else:
machinetype['max_processors'] = 1
if machinetype['max_processors'] < machinetype['min_processors']:
return 'max_processors cannot be less than min_processors!'
if parser.has_option(sectionName, 'log_machineoutputs'):
print 'log_machineoutputs has been deprecated: please use machines_dir_days to control this'
if parser.has_option(sectionName, 'machineoutputs_days'):
print 'machineoutputs_days is deprecated. Please use machines_dir_days in [' + sectionName + '] instead'
machinetype['machines_dir_days'] = float(parser.get(sectionName, 'machineoutputs_days'))
elif parser.has_option(sectionName, 'machines_dir_days'):
machinetype['machines_dir_days'] = float(parser.get(sectionName, 'machines_dir_days'))
else:
machinetype['machines_dir_days'] = 3.0
if parser.has_option(sectionName, 'max_wallclock_seconds'):
machinetype['max_wallclock_seconds'] = int(parser.get(sectionName, 'max_wallclock_seconds'))
else:
machinetype['max_wallclock_seconds'] = 86400
if parser.has_option(sectionName, 'min_wallclock_seconds'):
machinetype['min_wallclock_seconds'] = int(parser.get(sectionName, 'min_wallclock_seconds'))
else:
machinetype['min_wallclock_seconds'] = machinetype['max_wallclock_seconds']
if parser.has_option(sectionName, 'backoff_seconds'):
machinetype['backoff_seconds'] = int(parser.get(sectionName, 'backoff_seconds'))
else:
machinetype['backoff_seconds'] = 10
if parser.has_option(sectionName, 'fizzle_seconds'):
machinetype['fizzle_seconds'] = int(parser.get(sectionName, 'fizzle_seconds'))
else:
machinetype['fizzle_seconds'] = 600
if parser.has_option(sectionName, 'heartbeat_file'):
machinetype['heartbeat_file'] = parser.get(sectionName, 'heartbeat_file')
if parser.has_option(sectionName, 'heartbeat_seconds'):
machinetype['heartbeat_seconds'] = int(parser.get(sectionName, 'heartbeat_seconds'))
else:
machinetype['heartbeat_seconds'] = 0
if parser.has_option(sectionName, 'accounting_fqan'):
machinetype['accounting_fqan'] = parser.get(sectionName, 'accounting_fqan')
if parser.has_option(sectionName, 'machinegroup'):
machinetype['machinegroup'] = parser.get(sectionName, 'machinegroup')
elif 'accounting_fqan' in machinetype:
machinetype['machinegroup'] = machinetype['accounting_fqan']
else:
machinetype['machinegroup'] = sectionNameSplit[1]
if parser.has_option(sectionName, 'cvmfs_repositories'):
machinetype['cvmfs_repositories'] = set(parser.get(sectionName, 'cvmfs_repositories').split())
else:
machinetype['cvmfs_repositories'] = set([])
for (oneOption,oneValue) in parser.items(sectionName):
if (oneOption[0:17] == 'user_data_option_') or (oneOption[0:15] == 'user_data_file_'):
if string.translate(oneOption, None, '0123456789abcdefghijklmnopqrstuvwxyz_') != '':
return 'Name of user_data_option_xxx (' + oneOption + ') must only contain a-z 0-9 and _'
else:
machinetype[oneOption] = parser.get(sectionName, oneOption)
if parser.has_option(sectionName, 'user_data_proxy_cert') or \
parser.has_option(sectionName, 'user_data_proxy_key') :
print 'user_data_proxy_cert and user_data_proxy_key are deprecated. Please use user_data_proxy = True and create x509cert.pem and x509key.pem!'
if parser.has_option(sectionName, 'user_data_proxy') and \
parser.get(sectionName,'user_data_proxy').strip().lower() == 'true':
machinetype['user_data_proxy'] = True
else:
machinetype['user_data_proxy'] = False
if parser.has_option(sectionName, 'legacy_proxy') and \
parser.get(sectionName,'legacy_proxy').strip().lower() == 'true':
machinetype['legacy_proxy'] = True
else:
machinetype['legacy_proxy'] = False
machinetypes[sectionNameSplit[1]] = machinetype
# Finished successfully, with no error to return
return None
def nameFromOrdinal(ordinal):
nameParts = os.uname()[1].split('.',1)
return nameParts[0] + '-%02d' % ordinal + '.' + nameParts[1]
def ipFromOrdinal(ordinal):
return natPrefix + str(ordinal)
def setCgroupFsRoots():
global cpuCgroupFsRoot, memoryCgroupFsRoot
cpuCgroupFsRoot = None
memoryCgroupFsRoot = None
try:
f = open('/proc/mounts', 'r')
except:
vac.vacutils.logLine('Failed to open /proc/mounts')
for line in f:
cgroup, path = line.split()[:2]
# CPU cgroup line in /proc/mounts might look like this, with cpuacct listed too:
# cgroup /sys/fs/cgroup/cpu,cpuacct cgroup rw,nosuid,nodev,noexec,relatime,cpuacct,cpu 0 0
if cgroup == 'cgroup':
if 'cpu' in path.split('/')[-1].split(','):
cpuCgroupFsRoot = path
elif 'memory' in path.split('/')[-1].split(','):
memoryCgroupFsRoot = path
f.close()
if cpuCgroupFsRoot:
vac.vacutils.logLine('Filesystem root of the CPU cgroup is ' + cpuCgroupFsRoot)
else:
vac.vacutils.logLine('Could not determine filesystem root of the CPU cgroup!')
if memoryCgroupFsRoot:
vac.vacutils.logLine('Filesystem root of the memory cgroup is ' + memoryCgroupFsRoot)
else:
vac.vacutils.logLine('Could not determine filesystem root of the memory cgroup!')
def getProcessCpuCgroupPath(pid):
if not cpuCgroupFsRoot:
raise VacError('cpuCgroupFsRoot is not set!')
try:
f = open('/proc/%d/cgroup' % pid, 'r')
except:
raise VacError('No cgroup file for PID %d!' % pid)
for line in f:
n,subsystems,path = line.strip().split(':')
if 'cpu' in subsystems.split(','):
f.close()
return cpuCgroupFsRoot + path
f.close()
raise VacError('No CPU cgroup for PID %d!' % pid)
def countProcProcessors():
numProcessors = 0
try:
f = open('/proc/cpuinfo','r')
except:
print 'Failed to open /proc/cpuinfo'
return numProcessors
oneLine = f.readline()
while oneLine:
if oneLine.startswith('processor\t:'):
numProcessors += 1
oneLine = f.readline()
f.close()
return numProcessors
def setSockBufferSize(sock):
try:
if int(open('/proc/sys/net/core/rmem_max', 'r').readline().strip()) < udpBufferSize:
open('/proc/sys/net/core/rmem_max', 'w').write(str(udpBufferSize) + '\n')
except:
pass
try:
if int(open('/proc/sys/net/core/wmem_max', 'r').readline().strip()) < udpBufferSize:
open('/proc/sys/net/core/wmem_max', 'w').write(str(udpBufferSize) + '\n')
except:
pass
try:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, udpBufferSize)
except:
vac.vacutils.logLine('Failed setting RCVBUF to %d' % udpBufferSize)
try:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, udpBufferSize)
except:
vac.vacutils.logLine('Failed setting SNDBUF to %d' % udpBufferSize)
def canonicalFQDN(hostName):
if hostName == '.':
# . is replaced with local hostname
return os.uname()[1]
if '.' in hostName:
# Otherwise assume ok if already contains '.'
return hostName
try:
# Try to get DNS domain from current host's FQDN
return hostName + '.' + os.uname()[1].split('.',1)[1]
except:
# If failed, then just return what we were given
return hostName
def killZombieVMs():
# Look for VMs which are not properly associated with
# logical machine slots and kill them
conn = libvirt.open(None)
if conn == None:
vac.vacutils.logLine('Failed to open connection to the hypervisor')
raise
for ordinal in xrange(numMachineSlots):
name = nameFromOrdinal(ordinal)
try:
createdStr, machinetypeName, machineModel = open('/var/lib/vac/slots/' + name,'r').read().split()
except:
createdStr = None
machinetypeName = None
machineModel = None
uuidStr = None
else:
try:
# Can't use self.machinesDir()
uuidStr = open('/var/lib/vac/machines/' + createdStr + '_' + machinetypeName + '_' + name + '/jobfeatures/job_id', 'r').read().strip()
except:
uuidStr = None
try:
dom = conn.lookupByName(name)
except:
# Not running so can continue
continue
killZombie = False
if machineModel not in vmModels:
# We think a non-VM should be running here
vac.vacutils.logLine('VM still running alongside %s LM in slot %s, killing zombie' % (self.machineModel, self.name))
killZombie = True
if uuidStr != dom.UUIDString():
# Doesn't match slot's UUID
vac.vacutils.logLine('UUID mismatch: %s (job_id) != %s (dom) for LM %s, killing zombie' % (str(uuidStr), dom.UUIDString(), name))
killZombie = True
if not createdStr or not os.path.isdir('/var/lib/vac/machines/' + createdStr + '_' + machinetypeName + '_' + name):
# Our files say otherwise
vac.vacutils.logLine('No created time (or missing machines dir), killing zombie')
killZombie = True
if killZombie:
try:
dom.shutdown()
except Exception as e:
vac.vacutils.logLine('Failed to shutdown %s (%s)' % (name, str(e)))
else:
# 30s delay for any ACPI handler in the VM
time.sleep(30.0)
try:
dom.destroy()
except Exception as e:
vac.vacutils.logLine('Failed to destroy %s (%s)' % (name, str(e)))
conn.close()
def killZombieDCs():
# Look for Docker Container processes which are not properly associated with
# logical machine slots and kill them
try:
containers = dockerPsCommand()
except Exception as e:
vac.vacutils.logLine('Failed to get list of Docker zombie candidates (%s)' % str(e))
return
for name in containers:
# Look at this container looking for a mismatch. Unless we continue, remove the container
try:
createdStr, machinetypeName, machineModel = open('/var/lib/vac/slots/' + name,'r').read().split()
except:
# The corresponding slot isn't defined. Container is a zombie!
pass
else:
if machineModel in dcModels:
# This slot IS a Docker container. So may not be a zombie!
try:
uuidStr = open('/var/lib/vac/machines/%s_%s_%s/jobfeatures/job_id' % (createdStr, machinetypeName, name),'r').read().strip()
except Exception as e:
# But no UUID/ID defined for the slot's container. A zombie!
pass
else:
if uuidStr == containers[name]['id']:
# UUID = ID, so in this one case, NOT a zombie!
continue
# We've fallen through one way or another. So a zombie!
vac.vacutils.logLine('Removing zombie Docker container %s' % name)
dockerRmCommand(name)
def killZombieSCs():
# Look for Singularity Container processes which are not properly
# associated with logical machine slots and kill them;
# And remove Vac Singularity cgroups which have no processes
if singularityUser:
# First compose a list of expected running Singularity Container CPU cgroups
singularityCpuCgroupPaths = []
for ordinal in xrange(numMachineSlots):
name = nameFromOrdinal(ordinal)
try:
createdStr, machinetypeName, machineModel = open('/var/lib/vac/slots/' + name,'r').read().split()
except:
continue
if machineModel not in scModels:
# If slot not meant to be an SC then ignore