forked from projectvacuum/vcycle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shared.py
2344 lines (1905 loc) · 101 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
#!/usr/bin/python
#
# shared.py - common functions, classes, and variables for Vcycle
#
# Andrew McNab, Raoul Hidalgo Charman,
# 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/vcycle/
#
import pprint
import os
import re
import sys
import stat
import glob
import time
import json
import socket
import shutil
import string
import pycurl
import urllib
import random
import base64
import datetime
import StringIO
import tempfile
import calendar
import collections
import ConfigParser
import xml.etree.cElementTree
import vcycle.vacutils
class VcycleError(Exception):
pass
vcycleVersion = None
vacQueryVersion = '01.02' # Has to match shared.py in Vac
spaces = None
maxWallclockSeconds = 0
class MachineState:
#
# not listed -> starting
# starting -> failed or running or shutdown (if we miss the time when running)
# running -> shutdown
# shutdown -> deleting
# deleting -> not listed or failed
#
# random OpenStack unreliability can require transition to failed at any time
# stopped file created when machine first seen in shutdown, deleting, or failed state
#
unknown, shutdown, starting, running, deleting, failed = ('Unknown', 'Shut down', 'Starting', 'Running', 'Deleting', 'Failed')
class Machine:
def __init__(self, name, spaceName, state, ip, createdTime, startedTime, updatedTime, uuidStr, machinetypeName, zone = None, processors = None):
# Store values from api-specific calling function
self.name = name
self.spaceName = spaceName
self.state = state
self.ip = ip
self.updatedTime = updatedTime
self.uuidStr = uuidStr
self.machinetypeName = machinetypeName
self.zone = zone
if createdTime:
self.createdTime = createdTime
else:
try:
# Try to recreate from created file
self.createdTime = int(open('/var/lib/vcycle/machines/' + name + '/created', 'r').readline())
except:
pass
if startedTime:
self.startedTime = startedTime
else:
try:
# Try to recreate from started file
self.startedTime = int(open('/var/lib/vcycle/machines/' + name + '/started', 'r').readline())
except:
if self.state == MachineState.running:
# If startedTime not recorded, then must just have started
self.startedTime = int(time.time())
self.updatedTime = self.createdTime
else:
self.startedTime = None
if not self.updatedTime:
try:
# Try to recreate from updated file
self.updatedTime = int(open('/var/lib/vcycle/machines/' + name + '/updated', 'r').readline())
except:
pass
if not self.machinetypeName:
# Get machinetype name saved when we requested the machine
try:
f = open('/var/lib/vcycle/machines/' + name + '/machinetype_name', 'r')
except:
pass
else:
self.machinetypeName = f.read().strip()
f.close()
if self.machinetypeName not in spaces[self.spaceName].machinetypes:
self.machinetypeName = None
# if not zone:
# # Try to get zone name saved when we requested the machine
# try:
# f = open('/var/lib/vcycle/machines/' + name + '/zone', 'r')
# except:
# pass
# else:
# self.machinetypeName = f.read().strip()
# f.close()
if processors:
self.processors = processors
else:
try:
self.processors = int(open('/var/lib/vcycle/machines/' + name + '/jobfeatures/allocated_cpu', 'r').read().strip())
except:
try:
self.processors = spaces[self.spaceName].machinetypes[self.machinetypeName].min_processors
except:
self.processors = 1
try:
self.hs06 = float(open('/var/lib/vcycle/machines/' + name + '/jobfeatures/hs06_job', 'r').read().strip())
hs06Weight = self.hs06
except:
self.hs06 = None
hs06Weight = float(self.processors)
spaces[self.spaceName].totalMachines += 1
spaces[self.spaceName].totalProcessors += self.processors
try:
spaces[self.spaceName].machinetypes[self.machinetypeName].totalMachines += 1
spaces[self.spaceName].machinetypes[self.machinetypeName].totalProcessors += self.processors
if spaces[self.spaceName].machinetypes[self.machinetypeName].target_share > 0.0:
spaces[self.spaceName].machinetypes[self.machinetypeName].weightedMachines += (hs06Weight / spaces[self.spaceName].machinetypes[self.machinetypeName].target_share)
except:
pass
if self.state == MachineState.starting:
try:
spaces[self.spaceName].machinetypes[self.machinetypeName].startingProcessors += self.processors
except:
pass
if self.state == MachineState.running:
try:
if not self.startedTime:
self.startedTime = int(time.time())
self.updatedTime = self.startedTime
spaces[self.spaceName].runningMachines += 1
spaces[self.spaceName].runningProcessors += self.processors
try:
spaces[self.spaceName].machinetypes[self.machinetypeName].runningMachines += 1
spaces[self.spaceName].machinetypes[self.machinetypeName].runningProcessors += self.processors
except:
pass
if self.hs06 is not None:
# We check runningHS06 first in case hs06_per_processor removed from machinetype in config
if spaces[self.spacename].runningHS06 is not None:
spaces[self.spacename].runningHS06 += self.hs06
try:
spaces[self.spaceName].machinetypes[self.machinetypeName].runningHS06 += self.hs06
except:
pass
except:
pass
try:
if self.state == MachineState.starting or \
(self.state == MachineState.running and \
((int(time.time()) - startedTime) < spaces[self.spaceName].machinetypes[self.machinetypeName].fizzle_seconds)):
spaces[self.spaceName].machinetypes[self.machinetypeName].notPassedFizzle += 1
except:
pass
if os.path.isdir('/var/lib/vcycle/machines/' + name):
self.managedHere = True
else:
# Not managed by this Vcycle instance
self.managedHere = False
return
# Record when the machine started (rather than just being created)
if self.startedTime and not os.path.isfile('/var/lib/vcycle/machines/' + name + '/started'):
vcycle.vacutils.createFile('/var/lib/vcycle/machines/' + name + '/started', str(self.startedTime), 0600, '/var/lib/vcycle/tmp')
vcycle.vacutils.createFile('/var/lib/vcycle/machines/' + name + '/updated', str(self.updatedTime), 0600, '/var/lib/vcycle/tmp')
try:
self.deletedTime = int(open('/var/lib/vcycle/machines/' + name + '/deleted', 'r').read().strip())
except:
self.deletedTime = None
# Set heartbeat time if available
self.setHeartbeatTime()
# Check if the machine already has a stopped timestamp
try:
self.stoppedTime = int(open('/var/lib/vcycle/machines/' + name + '/stopped', 'r').read())
except:
if self.state == MachineState.shutdown or self.state == MachineState.failed or self.state == MachineState.deleting:
# Record that we have seen the machine in a stopped state for the first time
# If updateTime has the last transition time, presumably it is to being stopped.
# This is certainly a better estimate than using time.time() if available (ie OpenStack)
if not self.updatedTime:
self.updatedTime = int(time.time())
vcycle.vacutils.createFile('/var/lib/vcycle/machines/' + name + '/updated', str(self.updatedTime), 0600, '/var/lib/vcycle/tmp')
self.stoppedTime = self.updatedTime
vcycle.vacutils.createFile('/var/lib/vcycle/machines/' + name + '/stopped', str(self.stoppedTime), 0600, '/var/lib/vcycle/tmp')
# Record the shutdown message if available
self.setShutdownMessage()
if self.shutdownMessage:
vcycle.vacutils.logLine('Machine ' + name + ' shuts down with message "' + self.shutdownMessage + '"')
try:
shutdownCode = int(self.shutdownMessage.split(' ')[0])
except:
shutdownCode = None
else:
shutdownCode = None
if self.machinetypeName:
# Store last abort time for stopped machines, based on shutdown message code
if shutdownCode and \
(shutdownCode >= 300) and \
(shutdownCode <= 699) and \
(self.stoppedTime > spaces[self.spaceName].machinetypes[self.machinetypeName].lastAbortTime):
vcycle.vacutils.logLine('Set ' + self.spaceName + ' ' + self.machinetypeName + ' lastAbortTime ' + str(self.stoppedTime) +
' due to ' + name + ' shutdown message')
spaces[self.spaceName].machinetypes[self.machinetypeName].setLastAbortTime(self.stoppedTime)
elif self.startedTime and \
(self.stoppedTime > spaces[self.spaceName].machinetypes[self.machinetypeName].lastAbortTime) and \
((self.stoppedTime - self.startedTime) < spaces[self.spaceName].machinetypes[self.machinetypeName].fizzle_seconds):
# Store last abort time for stopped machines, based on fizzle_seconds
vcycle.vacutils.logLine('Set ' + self.spaceName + ' ' + self.machinetypeName + ' lastAbortTime ' + str(self.stoppedTime) +
' due to ' + name + ' fizzle')
spaces[self.spaceName].machinetypes[self.machinetypeName].setLastAbortTime(self.stoppedTime)
if self.startedTime and shutdownCode and (shutdownCode / 100) == 3:
vcycle.vacutils.logLine('For ' + self.spaceName + ':' + self.machinetypeName + ' minimum fizzle_seconds=' +
str(self.stoppedTime - self.startedTime) + ' ?')
# Machine finished messages for APEL and VacMon
self.writeApel()
self.sendMachineMessage()
else:
self.stoppedTime = None
if self.startedTime:
logStartedTimeStr = str(self.startedTime - self.createdTime) + 's'
else:
logStartedTimeStr = '-'
if self.updatedTime:
logUpdatedTimeStr = str(self.updatedTime - self.createdTime) + 's'
else:
logUpdatedTimeStr = '-'
if self.stoppedTime:
logStoppedTimeStr = str(self.stoppedTime - self.createdTime) + 's'
else:
logStoppedTimeStr = '-'
if self.heartbeatTime:
logHeartbeatTimeStr = str(int(time.time()) - self.heartbeatTime) + 's'
else:
logHeartbeatTimeStr = '-'
vcycle.vacutils.logLine('= ' + name + ' in ' +
str(self.spaceName) + ':' +
(self.zone if self.zone else '') + ':' +
str(self.machinetypeName) + ' ' +
str(self.processors) + ' ' + self.ip + ' ' +
self.state + ' ' +
time.strftime("%b %d %H:%M:%S ", time.localtime(self.createdTime)) +
logStartedTimeStr + ':' +
logUpdatedTimeStr + ':' +
logStoppedTimeStr + ':' +
logHeartbeatTimeStr
)
def getFileContents(self, fileName):
# Get the contents of a file for this machine
try:
return open('/var/lib/vcycle/machines/' + self.name + '/' + fileName, 'r').read().strip()
except:
return None
def setFileContents(self, fileName, contents):
# Set the contents of a file for the given machine
open('/var/lib/vcycle/machines/' + self.name + '/' + fileName, 'w').write(contents)
def writeApel(self):
# If the VM just ran for fizzle_seconds, then we don't log it
try:
if (self.stoppedTime - self.startedTime) < spaces[self.spaceName].machinetypes[self.machinetypeName].fizzle_seconds:
return
except:
return
nowTime = time.localtime()
userDN = ''
for component in self.spaceName.split('.'):
userDN = '/DC=' + component + userDN
if hasattr(spaces[self.spaceName].machinetypes[self.machinetypeName], 'accounting_fqan'):
userFQANField = 'FQAN: ' + spaces[self.spaceName].machinetypes[self.machinetypeName].accounting_fqan + '\n'
else:
userFQANField = ''
try:
kb = int(self.getFileContents('jobfeatures/max_rss_bytes')) / 1024
except:
memoryField = ''
else:
memoryField = 'MemoryReal: ' + str(kb) + '\nMemoryVirtual: ' + str(kb) + '\n'
try:
processors = int(self.getFileContents('jobfeatures/allocated_cpu'))
except:
processorsField = ''
else:
processorsField = 'Processors: ' + str(processors) + '\n'
if spaces[self.spaceName].gocdb_sitename:
tmpGocdbSitename = spaces[self.spaceName].gocdb_sitename
else:
tmpGocdbSitename = '.'.join(self.spaceName.split('.')[1:]) if '.' in self.spaceName else self.spaceName
mesg = ('APEL-individual-job-message: v0.3\n' +
'Site: ' + tmpGocdbSitename + '\n' +
'SubmitHost: ' + self.spaceName + '/vcycle-' + os.uname()[1] + '\n' +
'LocalJobId: ' + self.uuidStr + '\n' +
'LocalUserId: ' + self.name + '\n' +
'Queue: ' + self.machinetypeName + '\n' +
'GlobalUserName: ' + userDN + '\n' +
userFQANField +
'WallDuration: ' + str(self.stoppedTime - self.startedTime) + '\n' +
# Can we do better for CpuDuration???
'CpuDuration: ' + str(self.stoppedTime - self.startedTime) + '\n' +
processorsField +
'NodeCount: 1\n' +
'InfrastructureDescription: APEL-VCYCLE\n' +
'InfrastructureType: grid\n' +
'StartTime: ' + str(self.startedTime) + '\n' +
'EndTime: ' + str(self.stoppedTime) + '\n' +
memoryField +
'ServiceLevelType: HEPSPEC\n' +
'ServiceLevel: ' + str(self.hs06 if self.hs06 else 1.0) + '\n' +
'%%\n')
fileName = time.strftime('%H%M%S', nowTime) + str(time.time() % 1)[2:][:8]
try:
os.makedirs(time.strftime('/var/lib/vcycle/apel-archive/%Y%m%d', nowTime), stat.S_IRUSR|stat.S_IWUSR|stat.S_IXUSR|stat.S_IRGRP|stat.S_IXGRP|stat.S_IROTH|stat.S_IXOTH)
except:
pass
try:
vcycle.vacutils.createFile(time.strftime('/var/lib/vcycle/apel-archive/%Y%m%d/', nowTime) + fileName, mesg, stat.S_IRUSR|stat.S_IWUSR|stat.S_IRGRP|stat.S_IROTH, '/var/lib/vcycle/tmp')
except:
vcycle.vacutils.logLine('Failed creating ' + time.strftime('/var/lib/vcycle/apel-archive/%Y%m%d/', nowTime) + fileName)
return
if spaces[self.spaceName].gocdb_sitename:
# We only write to apel-outgoing if gocdb_sitename is set
try:
os.makedirs(time.strftime('/var/lib/vcycle/apel-outgoing/%Y%m%d', nowTime), stat.S_IRUSR|stat.S_IWUSR|stat.S_IXUSR|stat.S_IRGRP|stat.S_IXGRP|stat.S_IROTH|stat.S_IXOTH)
except:
pass
try:
vcycle.vacutils.createFile(time.strftime('/var/lib/vcycle/apel-outgoing/%Y%m%d/', nowTime) + fileName, mesg, stat.S_IRUSR|stat.S_IWUSR|stat.S_IRGRP|stat.S_IROTH, '/var/lib/vcycle/tmp')
except:
vcycle.vacutils.logLine('Failed creating ' + time.strftime('/var/lib/vcycle/apel-outgoing/%Y%m%d/', nowTime) + fileName)
return
def sendMachineMessage(self, cookie = '0'):
if not spaces[self.spaceName].vacmons:
return
timeNow = int(time.time())
if spaces[self.spaceName].gocdb_sitename:
tmpGocdbSitename = spaces[self.spaceName].gocdb_sitename
else:
tmpGocdbSitename = '.'.join(self.spaceName.split('.')[1:]) if '.' in self.spaceName else self.spaceName
if not self.startedTime:
cpuSeconds = 0
elif self.stoppedTime:
cpuSeconds = self.stoppedTime - self.startedTime
elif self.state == MachineState.running:
cpuSeconds = timeNow - self.startedTime
else:
cpuSeconds = 0
messageDict = {
'message_type' : 'machine_status',
'daemon_version' : 'Vcycle ' + vcycleVersion + ' vcycled',
'vacquery_version' : 'VacQuery ' + vacQueryVersion,
'cookie' : cookie,
'space' : self.spaceName,
'site' : tmpGocdbSitename,
'factory' : os.uname()[1],
'num_machines' : 1,
'time_sent' : timeNow,
'machine' : self.name,
'state' : self.state,
'uuid' : self.uuidStr,
'created_time' : self.createdTime,
'started_time' : self.startedTime,
'heartbeat_time' : self.heartbeatTime,
'num_processors' : self.processors,
'cpu_seconds' : cpuSeconds,
'cpu_percentage' : 100.0,
'machinetype' : self.machinetypeName
}
if self.hs06:
messageDict['hs06'] = self.hs06
try:
messageDict['fqan'] = spaces[self.spaceName].machinetypes[machinetypeName].accounting_fqan
except:
pass
try:
messageDict['shutdown_message'] = self.shutdownMessage
except:
pass
try:
messageDict['shutdown_time'] = self.shutdownMessageTime
except:
pass
messageJSON = json.dumps(messageDict)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for vacmonHostPort in spaces[self.spaceName].vacmons:
(vacmonHost, vacmonPort) = vacmonHostPort.split(':')
vcycle.vacutils.logLine('Sending VacMon machine finished message to %s:%s' % (vacmonHost, vacmonPort))
sock.sendto(messageJSON, (vacmonHost,int(vacmonPort)))
sock.close()
def setShutdownMessage(self):
self.shutdownMessage = None
self.shutdownMessageTime = None
# Easy if a local file rather than remote
if not self.machinetypeName or not spaces[self.spaceName].machinetypes[self.machinetypeName].remote_joboutputs_url:
try:
self.shutdownMessage = open('/var/lib/vcycle/machines/' + self.name + '/joboutputs/shutdown_message', 'r').read().strip()
self.shutdownMessageTime = int(os.stat('/var/lib/vcycle/machines/' + self.name + '/joboutputs/shutdown_message').st_ctime)
except:
pass
return
# Remote URL must be https://
if spaces[self.spaceName].machinetypes[self.machinetypeName].remote_joboutputs_url[0:8] == 'https://':
buffer = StringIO.StringIO()
url = str(spaces[self.spaceName].machinetypes[self.machinetypeName].remote_joboutputs_url + self.name + '/shutdown_message')
spaces[self.spaceName].curl.unsetopt(pycurl.CUSTOMREQUEST)
try:
if spaces[self.spaceName].machinetypes[self.machinetypeName].remote_joboutputs_cert[0] == '/':
spaces[self.spaceName].curl.setopt(pycurl.SSLCERT, spaces[self.spaceName].machinetypes[self.machinetypeName].remote_joboutputs_cert)
else:
spaces[self.spaceName].curl.setopt(pycurl.SSLCERT, '/var/lib/vcycle/spaces/' + self.spaceName + '/machinetypes/' + self.machinetypeName + '/files/' + spaces[self.spaceName].machinetypes[self.machinetypeName].remote_joboutputs_cert)
except:
spaces[self.spaceName].curl.setopt(pycurl.SSLCERT, '')
try:
if spaces[self.spaceName].machinetypes[self.machinetypeName].remote_joboutputs_key[0] == '/':
spaces[self.spaceName].curl.setopt(pycurl.SSLKEY, spaces[self.spaceName].machinetypes[self.machinetypeName].remote_joboutputs_key)
else:
spaces[self.spaceName].curl.setopt(pycurl.SSLKEY, '/var/lib/vcycle/spaces/' + self.spaceName + '/machinetypes/' + self.machinetypeName + '/files/' + spaces[self.spaceName].machinetypes[self.machinetypeName].remote_joboutputs_key)
except:
spaces[self.spaceName].curl.setopt(pycurl.SSLKEY, '')
spaces[self.spaceName].curl.setopt(pycurl.URL, url)
spaces[self.spaceName].curl.setopt(pycurl.NOBODY, 0)
spaces[self.spaceName].curl.setopt(pycurl.WRITEFUNCTION, buffer.write)
spaces[self.spaceName].curl.setopt(pycurl.USERAGENT, 'Vcycle ' + vcycleVersion)
spaces[self.spaceName].curl.setopt(pycurl.TIMEOUT, 30)
spaces[self.spaceName].curl.setopt(pycurl.FOLLOWLOCATION, True)
spaces[self.spaceName].curl.setopt(pycurl.SSL_VERIFYPEER, 1)
spaces[self.spaceName].curl.setopt(pycurl.SSL_VERIFYHOST, 2)
if os.path.isdir('/etc/grid-security/certificates'):
spaces[self.spaceName].curl.setopt(pycurl.CAPATH, '/etc/grid-security/certificates')
else:
vcycle.vacutils.logLine('/etc/grid-security/certificates directory does not exist - relying on curl bundle of commercial CAs')
try:
spaces[self.spaceName].curl.perform()
except Exception as e:
vcycle.vacutils.logLine('Failed to read ' + self.remote_joboutputs_url + self.name + '/shutdown_message (' + str(e) + ')')
self.shutdownMessage = None
return
try:
self.shutdownMessage = buffer.getvalue().strip()
if self.shutdownMessage == '':
self.shutdownMessage = None
except:
self.shutdownMessage = None
return
vcycle.vacutils.logLine('Problem with remote_joboutputs_url = ' + self.remote_joboutputs_url)
def setHeartbeatTime(self):
# No valid machinetype (probably removed from configuration)
if not self.machinetypeName:
self.heartbeatTime = None
return
# Easy if a local file rather than remote
if not spaces[self.spaceName].machinetypes[self.machinetypeName].remote_joboutputs_url:
try:
self.heartbeatTime = int(os.stat('/var/lib/vcycle/machines/' + self.name + '/joboutputs/' + spaces[self.spaceName].machinetypes[self.machinetypeName].heartbeat_file).st_ctime)
except:
self.heartbeatTime = None
return
# Remote URL must be https://
if spaces[self.spaceName].machinetypes[self.machinetypeName].remote_joboutputs_url[0:8] != 'https://':
vcycle.vacutils.logLine('Problem with remote_joboutputs_url = ' + self.remote_joboutputs_url)
else:
buffer = StringIO.StringIO()
url = str(spaces[self.spaceName].machinetypes[self.machinetypeName].remote_joboutputs_url + self.name + '/' + spaces[self.spaceName].machinetypes[self.machinetypeName].heartbeat_file)
spaces[self.spaceName].curl.unsetopt(pycurl.CUSTOMREQUEST)
try:
if spaces[self.spaceName].machinetypes[self.machinetypeName].remote_joboutputs_cert[0] == '/':
spaces[self.spaceName].curl.setopt(pycurl.SSLCERT, spaces[self.spaceName].machinetypes[self.machinetypeName].remote_joboutputs_cert)
else:
spaces[self.spaceName].curl.setopt(pycurl.SSLCERT, '/var/lib/vcycle/spaces/' + self.spaceName + '/machinetypes/' + self.machinetypeName + '/files/' + spaces[self.spaceName].machinetypes[self.machinetypeName].remote_joboutputs_cert)
except:
spaces[self.spaceName].curl.setopt(pycurl.SSLCERT, '')
try:
if spaces[self.spaceName].machinetypes[self.machinetypeName].remote_joboutputs_key[0] == '/':
spaces[self.spaceName].curl.setopt(pycurl.SSLKEY, spaces[self.spaceName].machinetypes[self.machinetypeName].remote_joboutputs_key)
else:
spaces[self.spaceName].curl.setopt(pycurl.SSLKEY, '/var/lib/vcycle/spaces/' + self.spaceName + '/machinetypes/' + self.machinetypeName + '/files/' + spaces[self.spaceName].machinetypes[self.machinetypeName].remote_joboutputs_key)
except:
spaces[self.spaceName].curl.setopt(pycurl.SSLKEY, '')
spaces[self.spaceName].curl.setopt(pycurl.URL, url)
spaces[self.spaceName].curl.setopt(pycurl.NOBODY, 1)
spaces[self.spaceName].curl.setopt(pycurl.WRITEFUNCTION, buffer.write)
spaces[self.spaceName].curl.setopt(pycurl.USERAGENT, 'Vcycle ' + vcycleVersion)
spaces[self.spaceName].curl.setopt(pycurl.TIMEOUT, 30)
spaces[self.spaceName].curl.setopt(pycurl.FOLLOWLOCATION, True)
spaces[self.spaceName].curl.setopt(pycurl.SSL_VERIFYPEER, 1)
spaces[self.spaceName].curl.setopt(pycurl.SSL_VERIFYHOST, 2)
spaces[self.spaceName].curl.setopt(pycurl.OPT_FILETIME, 1)
if os.path.isdir('/etc/grid-security/certificates'):
spaces[self.spaceName].curl.setopt(pycurl.CAPATH, '/etc/grid-security/certificates')
else:
vcycle.vacutils.logLine('/etc/grid-security/certificates directory does not exist - relying on curl bundle of commercial CAs')
try:
spaces[self.spaceName].curl.perform()
except Exception as e:
vcycle.vacutils.logLine('Failed to read ' + url + ' (' + str(e) + ')')
else:
if spaces[self.spaceName].curl.getinfo(pycurl.RESPONSE_CODE) == 200:
try:
heartbeatTime = float(spaces[self.spaceName].curl.getinfo(pycurl.INFO_FILETIME))
if heartbeatTime > 0.0:
# Save the time we got from the remote webserver
try:
open('/var/lib/vcycle/machines/' + self.name + '/vm-heartbeat', 'a')
os.utime('/var/lib/vcycle/machines/' + self.name + '/vm-heartbeat', (time.time(), heartbeatTime))
except:
pass
except:
pass
elif spaces[self.spaceName].curl.getinfo(pycurl.RESPONSE_CODE) == 0:
vcycle.vacutils.logLine('Fetching ' + url + ' fails with curl error ' + str(spaces[self.spaceName].curl.errstr()))
elif spaces[self.spaceName].curl.getinfo(pycurl.RESPONSE_CODE) != 404:
vcycle.vacutils.logLine('Fetching ' + url + ' fails with HTTP response code ' + str(spaces[self.spaceName].curl.getinfo(pycurl.RESPONSE_CODE)))
try:
# Use the last saved time, possibly from a previous call to this method
self.heartbeatTime = int(os.stat('/var/lib/vcycle/machines/' + self.name + '/vm-heartbeat').st_mtime)
except:
self.heartbeatTime = None
class Machinetype:
def __init__(self, spaceName, spaceFlavorNames, machinetypeName, parser, machinetypeSectionName):
global maxWallclockSeconds
self.spaceName = spaceName
self.machinetypeName = machinetypeName
# Recreate lastAbortTime (must be set/updated with setLastAbortTime() to create file)
try:
f = open('/var/lib/vcycle/spaces/' + self.spaceName + '/machinetypes/' + self.machinetypeName + '/last_abort_time', 'r')
except:
self.lastAbortTime = 0
else:
self.lastAbortTime = int(f.read().strip())
f.close()
# Always set machinetype_path, saved in vacuum pipe processing or default using machinetype name
try:
self.machinetype_path = parser.get(machinetypeSectionName, 'machinetype_path')
except:
self.machinetype_path = '/var/lib/vcycle/spaces/' + self.spaceName + '/machinetypes/' + self.machinetypeName
try:
self.root_image = parser.get(machinetypeSectionName, 'root_image')
except:
self.root_image = None
try:
self.cernvm_signing_dn = parser.get(machinetypeSectionName, 'cernvm_signing_dn')
except:
self.cernvm_signing_dn = None
if parser.has_option(machinetypeSectionName, 'flavor_name'):
vcycle.vacutils.logLine('Option flavor_name is deprecated, please use flavor_names!')
try:
self.flavor_names = parser.get(machinetypeSectionName, 'flavor_name').strip().split()
except:
self.flavor_names = spaceFlavorNames
else:
try:
self.flavor_names = parser.get(machinetypeSectionName, 'flavor_names').strip().split()
except:
self.flavor_names = spaceFlavorNames
try:
self.min_processors = int(parser.get(machinetypeSectionName, 'cpu_per_machine'))
except:
pass
else:
vcycle.vacutils.logLine('cpu_per_machine is deprecated - please use min_processors')
try:
self.min_processors = int(parser.get(machinetypeSectionName, 'processors_per_machine'))
except:
pass
else:
vcycle.vacutils.logLine('processors_per_machine is deprecated - please use min_processors')
try:
self.min_processors = int(parser.get(machinetypeSectionName, 'min_processors'))
except Exception as e:
self.min_processors = 1
try:
self.max_processors = int(parser.get(machinetypeSectionName, 'max_processors'))
except Exception as e:
self.max_processors = None
if self.max_processors is not None and self.max_processors < self.min_processors:
raise VcycleError('max_processors cannot be less than min_processors!')
try:
self.disk_gb_per_processor = int(parser.get(machinetypeSectionName, 'disk_gb_per_processor'))
except Exception as e:
self.disk_gb_per_processor = None
try:
self.root_public_key = parser.get(machinetypeSectionName, 'root_public_key')
except:
self.root_public_key = None
try:
if parser.has_option(machinetypeSectionName, 'processors_limit'):
self.processors_limit = int(parser.get(machinetypeSectionName, 'processors_limit'))
else:
self.processors_limit = None
except Exception as e:
raise VcycleError('Failed to parse processors_limit in [' + machinetypeSectionName + '] (' + str(e) + ')')
if parser.has_option(machinetypeSectionName, 'max_starting_processors'):
try:
self.max_starting_processors = int(parser.get(machinetypeSectionName, 'max_starting_processors'))
except Exception as e:
raise VcycleError('Failed to parse max_starting_processors in [' + machinetypeSectionName + '] (' + str(e) + ')')
else:
self.max_starting_processors = self.processors_limit
try:
self.backoff_seconds = int(parser.get(machinetypeSectionName, 'backoff_seconds'))
except Exception as e:
raise VcycleError('backoff_seconds is required in [' + machinetypeSectionName + '] (' + str(e) + ')')
try:
self.fizzle_seconds = int(parser.get(machinetypeSectionName, 'fizzle_seconds'))
except Exception as e:
raise VcycleError('fizzle_seconds is required in [' + machinetypeSectionName + '] (' + str(e) + ')')
try:
if parser.has_option(machinetypeSectionName, 'max_wallclock_seconds'):
self.max_wallclock_seconds = int(parser.get(machinetypeSectionName, 'max_wallclock_seconds'))
else:
self.max_wallclock_seconds = 86400
if self.max_wallclock_seconds > maxWallclockSeconds:
maxWallclockSeconds = self.max_wallclock_seconds
except Exception as e:
raise VcycleError('max_wallclock_seconds is required in [' + machinetypeSectionName + '] (' + str(e) + ')')
try:
self.x509dn = parser.get(machinetypeSectionName, 'x509dn')
except:
self.x509dn = None
# The heartbeat and joboutputs options should cause errors if x509dn isn't given!
try:
self.heartbeat_file = parser.get(machinetypeSectionName, 'heartbeat_file')
except:
self.heartbeat_file = None
try:
if parser.has_option(machinetypeSectionName, 'heartbeat_seconds'):
self.heartbeat_seconds = int(parser.get(machinetypeSectionName, 'heartbeat_seconds'))
else:
self.heartbeat_seconds = None
except Exception as e:
raise VcycleError('Failed to parse heartbeat_seconds in [' + machinetypeSectionName + '] (' + str(e) + ')')
try:
s = parser.get(machinetypeSectionName, 'cvmfs_proxy_machinetype')
except:
self.cvmfsProxyMachinetype = None
self.cvmfsProxyMachinetypePort = None
else:
if ':' in s:
try:
self.cvmfsProxyMachinetype = s.split(':')[0]
self.cvmfsProxyMachinetypePort = int(s.split(':')[1])
except:
raise VcycleError('Failed to parse cmvfs_proxy_machinetype = ' + s + ' in [' + machinetypeSectionName + '] (' + str(e) + ')')
else:
self.cvmfsProxyMachinetype = s
self.cvmfsProxyMachinetypePort = 280
if parser.has_option(machinetypeSectionName, 'log_machineoutputs') and \
parser.get(machinetypeSectionName, 'log_machineoutputs').lower() == 'true':
self.log_joboutputs = True
vcycle.vacutils.logLine('log_machineoutputs is deprecated. Please use log_joboutputs')
elif parser.has_option(machinetypeSectionName, 'log_joboutputs') and \
parser.get(machinetypeSectionName, 'log_joboutputs').lower() == 'true':
self.log_joboutputs = True
else:
self.log_joboutputs = False
if parser.has_option(machinetypeSectionName, 'machineoutputs_days'):
vcycle.vacutils.logLine('machineoutputs_days is deprecated. Please use joboutputs_days')
try:
if parser.has_option(machinetypeSectionName, 'joboutputs_days'):
self.joboutputs_days = float(parser.get(machinetypeSectionName, 'joboutputs_days'))
else:
self.joboutputs_days = 3.0
except Exception as e:
raise VcycleError('Failed to parse joboutputs_days in [' + machinetypeSectionName + '] (' + str(e) + ')')
try:
self.remote_joboutputs_url = parser.get(machinetypeSectionName, 'remote_joboutputs_url').rstrip('/') + '/'
except:
self.remote_joboutputs_url = None
if parser.has_option(machinetypeSectionName, 'remote_joboutputs_cert') and \
not parser.has_option(machinetypeSectionName, 'remote_joboutputs_key') :
raise VcycleError('remote_joboutputs_cert given but remote_joboutputs_key missing (they can point to the same file if necessary)')
elif not parser.has_option(machinetypeSectionName, 'remote_joboutputs_cert') and \
parser.has_option(machinetypeSectionName, 'remote_joboutputs_key') :
raise VcycleError('remote_joboutputs_key given but remote_joboutputs_cert missing (they can point to the same file if necessary)')
elif parser.has_option(machinetypeSectionName, 'remote_joboutputs_cert') and \
parser.has_option(machinetypeSectionName, 'remote_joboutputs_key') :
self.remote_joboutputs_cert = parser.get(machinetypeSectionName, 'remote_joboutputs_cert')
self.remote_joboutputs_key = parser.get(machinetypeSectionName, 'remote_joboutputs_key')
else:
self.remote_joboutputs_cert = None
self.remote_joboutputs_key = None
if parser.has_option(machinetypeSectionName, 'accounting_fqan'):
self.accounting_fqan = parser.get(machinetypeSectionName, 'accounting_fqan')
try:
self.rss_bytes_per_processor = 1048576 * int(parser.get(machinetypeSectionName, 'mb_per_processor'))
except:
# If not set explicitly, defaults to 2048 MB per processor
self.rss_bytes_per_processor = 2147483648
if parser.has_option(machinetypeSectionName, 'hs06_per_processor'):
try:
self.hs06_per_processor = float(parser.get(machinetypeSectionName, 'hs06_per_processor'))
except Exception as e:
VcycleError('Failed to parse hs06_per_processor in [' + machinetypeSectionName + '] (' + str(e) + ')')
else:
self.runningHS06 = 0.0
else:
self.hs06_per_processor = None
self.runningHS06 = None
try:
self.user_data = parser.get(machinetypeSectionName, 'user_data')
except Exception as e:
raise VcycleError('user_data is required in [' + machinetypeSectionName + '] (' + str(e) + ')')
try:
if parser.has_option(machinetypeSectionName, 'target_share'):
self.target_share = float(parser.get(machinetypeSectionName, 'target_share'))
else:
self.target_share = 0.0
except Exception as e:
raise VcycleError('Failed to parse target_share in [' + machinetypeSectionName + '] (' + str(e) + ')')
# self.options will be passed to vacutils.createUserData()
self.options = {}
for (oneOption, oneValue) in parser.items(machinetypeSectionName):
if (oneOption[0:17] == 'user_data_option_') or (oneOption[0:15] == 'user_data_file_'):
if string.translate(oneOption, None, '0123456789abcdefghijklmnopqrstuvwxyz_') != '':
raise VcycleError('Name of user_data_xxx (' + oneOption + ') must only contain a-z 0-9 and _')
else:
self.options[oneOption] = oneValue
if parser.has_option(machinetypeSectionName, 'user_data_proxy_cert') or \
parser.has_option(machinetypeSectionName, 'user_data_proxy_key') :
vcycle.vacutils.logLine('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(machinetypeSectionName, 'user_data_proxy') and \
parser.get(machinetypeSectionName,'user_data_proxy').lower() == 'true':
self.options['user_data_proxy'] = True
else:
self.options['user_data_proxy'] = False
if parser.has_option(machinetypeSectionName, 'legacy_proxy') and \
parser.get(machinetypeSectionName, 'legacy_proxy').lower() == 'true':
self.options['legacy_proxy'] = True
else:
self.options['legacy_proxy'] = False
# Just for this instance, so Total for this machinetype in one space
self.totalMachines = 0
self.totalProcessors = 0
self.startingProcessors = 0
self.runningMachines = 0
self.runningProcessors = 0
self.weightedMachines = 0.0
self.notPassedFizzle = 0
def setLastAbortTime(self, abortTime):
if abortTime > self.lastAbortTime:
self.lastAbortTime = abortTime
try:
os.makedirs('/var/lib/vcycle/spaces/' + self.spaceName + '/machinetypes/' + self.machinetypeName,
stat.S_IWUSR + stat.S_IXUSR + stat.S_IRUSR + stat.S_IXGRP + stat.S_IRGRP + stat.S_IXOTH + stat.S_IROTH)
except:
pass
vcycle.vacutils.createFile('/var/lib/vcycle/spaces/' + self.spaceName + '/machinetypes/' + self.machinetypeName + '/last_abort_time',
str(abortTime), tmpDir = '/var/lib/vcycle/tmp')
def makeMachineName(self):
"""Construct a machine name including the machinetype"""
while True:
machineName = 'vcycle-' + self.machinetypeName + '-' + ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(10))
if not os.path.exists('/var/lib/vcycle/machines/' + machineName):
break
vcycle.vacutils.logLine('New random machine name ' + machineName + ' already exists! Trying another name ...')
return machineName
class BaseSpace(object):
def __init__(self, api, apiVersion, spaceName, parser, spaceSectionName, updatePipes):
self.api = api
self.apiVersion = apiVersion
self.spaceName = spaceName
self.processors_limit = None
self.totalMachines = 0
# totalProcessors includes ones Vcycle doesn't manage
self.totalProcessors = 0
self.runningMachines = 0
self.runningProcessors = 0
self.runningHS06 = None
self.zones = None
self.maxStartingSeconds = 3600
self.shutdownTime = None
if parser.has_option(spaceSectionName, 'max_processors'):
vcycle.vacutils.logLine('max_processors (in space ' + spaceName + ') is deprecated - please use processors_limit')
try:
self.processors_limit = int(parser.get(spaceSectionName, 'max_processors'))
except:
raise VcycleError('Failed to parse max_processors in [space ' + spaceName + '] (' + str(e) + ')')
elif parser.has_option(spaceSectionName, 'processors_limit'):
try:
self.processors_limit = int(parser.get(spaceSectionName, 'processors_limit'))
except Exception as e:
raise VcycleError('Failed to parse processors_limit in [space ' + spaceName + '] (' + str(e) + ')')
try:
self.flavor_names = parser.get(spaceSectionName, 'flavor_names').strip().split()
except:
self.flavor_names = []
if parser.has_option(spaceSectionName, 'shutdown_time'):
try:
self.shutdownTime = int(parser.get(spaceSectionName,
'shutdown_time'))
except Exception as e:
raise VcycleError('Failed to check parse shutdown_time in ['
+ spaceSectionName + '] (' + str(e) + ')')
# First go through the vacuum_pipe sections for this space, creating
# machinetype sections in the configuration on the fly
for vacuumPipeSectionName in parser.sections():
try:
(sectionType, spaceTemp, machinetypeNamePrefix) = vacuumPipeSectionName.lower().split(None,2)
except: