-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathviab-cgi
executable file
·1780 lines (1372 loc) · 68.5 KB
/
viab-cgi
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
#
# viabcgi - Vac-in-a-Box CGI script
#
# Andrew McNab, University of Manchester.
# Copyright (c) 2015-6. 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: Andrew.McNab@cern.ch http://www.gridpp.ac.uk/vac/
#
import os
import re
import sys
import cgi
import stat
import time
import shutil
import hashlib
import tempfile
import inspect
import MySQLdb
import textwrap
db = None
cur = None
# viab_cgi_conf.py must define these variables:
#
# mysqlUser = 'username'
# mysqlPassword = 'PAsSWoRd'
# adminDNs = [ '/DC=com/DC=example/CN=name' ]
# formHashSalt = '1234567890'
#
import viab_cgi_conf
def oddEven(n):
return 'even' if n % 2 == 0 else 'odd'
def htmlFormCookie(userDN):
timeForm = str(int(time.time()))
print ('<input type="hidden" name="formcookie" value="' +
timeForm + ':' +
hashlib.sha256(timeForm + userDN + viab_cgi_conf.formHashSalt).hexdigest()
+ '">')
def htmlHeader(title):
print 'Content-Type: text/html'
print
print '<html><head><title>' + title + '</title>'
print open('/var/lib/viab/www/header.html', 'r').read().replace('/docs/VERSION/','/docs/' + prodVersion + '/')
def htmlFooter(userDN):
if userDN:
print open('/var/lib/viab/www/footer.html', 'r').read().replace('<!--##YOUARE##-->','You are ' + userDN)
else:
print open('/var/lib/viab/www/footer.html', 'r').read()
print '</html>'
def errorPage(requestURI, userDN, title, message):
htmlHeader(title)
print '<h1>' + title + '</h1>'
print '<p>' + message
print '<p style="text-align: center"><button type="button" onclick="location.href=\'' + requestURI + '\';">Continue</button>'
htmlFooter(userDN)
# errorPage(requestURI, userDN, 'Some sort of problem ...', 'There was some sort of problem with the value(s) you gave!') ; return
def deleteOrphans():
global cur
cur.execute('DELETE FROM sshkeys WHERE siteid NOT IN (SELECT t.siteid FROM sites t)')
cur.execute('DELETE FROM sshfirewall WHERE siteid NOT IN (SELECT t.siteid FROM sites t)')
cur.execute('DELETE FROM siteadmins WHERE siteid NOT IN (SELECT t.siteid FROM sites t)')
cur.execute('DELETE FROM spaces WHERE siteid NOT IN (SELECT t.siteid FROM sites t)')
cur.execute('DELETE FROM subnets WHERE spaceid NOT IN (SELECT s.spaceid FROM spaces s)')
cur.execute('DELETE FROM factories WHERE spaceid NOT IN (SELECT s.spaceid FROM spaces s)')
cur.execute('DELETE FROM machinetypes WHERE spaceid NOT IN (SELECT s.spaceid FROM spaces s)')
cur.execute('DELETE FROM machinetypeopts WHERE machinetypeid NOT IN (SELECT m.machinetypeid FROM machinetypes m)')
def oneMachinetype(requestURI, userDN, cgiForm, siteName, siteID, spaceName, spaceID, machinetypeName, machinetypeID):
global cur
# All values here must be presented as strings!
machinetypePresets = {
'example' : { 'machine_model' : 'cernvm3',
'user_data' : 'https://repo.gridpp.ac.uk/vacproject/example/user_data',
'root_image' : 'https://repo.gridpp.ac.uk/vacproject/example/cernvm3.iso',
'backoff_seconds' : '600',
'fizzle_seconds' : '600',
'max_wallclock_seconds' : '900',
'target_share' : '1.0',
'root_public_key' : '/root/.ssh/id_rsa.pub',
'user_data_option_cvmfs_proxy' : 'http://169.254.169.254:3128/'
},
'GridPP' : { 'machine_model' : 'cernvm3',
'user_data' : 'https://repo.gridpp.ac.uk/vacproject/gridpp/user_data',
'root_image' : 'https://repo.gridpp.ac.uk/vacproject/gridpp/cernvm3.iso',
'backoff_seconds' : '3600',
'fizzle_seconds' : '600',
'max_wallclock_seconds' : '100000',
'target_share' : '1.0',
'root_public_key' : '/root/.ssh/id_rsa.pub',
'heartbeat_file' : 'vm-heartbeat',
'heartbeat_seconds' : '600',
'accounting_fqan' : '/gridpp/Role=NULL/Capability=NULL',
'user_data_option_dirac_site' : 'CHANGEME',
'user_data_option_vo' : 'gridpp',
'user_data_file_hostcert' : 'hostcert.pem',
'user_data_file_hostkey' : 'hostkey.pem',
'user_data_option_cvmfs_proxy' : 'http://169.254.169.254:3128/'
},
'ATLAS' : { 'machine_model' : 'cernvm3',
'user_data' : 'https://repo.gridpp.ac.uk/vacproject/atlas/user_data',
'root_image' : 'https://repo.gridpp.ac.uk/vacproject/atlas/cernvm3.iso',
'backoff_seconds' : '3600',
'fizzle_seconds' : '600',
'max_wallclock_seconds' : '172800',
'target_share' : '1.0',
'root_public_key' : '/root/.ssh/id_rsa.pub',
'heartbeat_file' : 'heartbeat',
'heartbeat_seconds' : '600',
'accounting_fqan' : '/atlas/Role=NULL/Capability=NULL',
'user_data_option_queue' : 'CHANGEME',
'user_data_file_hostcert' : 'hostcert.pem',
'user_data_file_hostkey' : 'hostkey.pem',
'user_data_option_cvmfs_proxy' : 'http://169.254.169.254:3128/'
},
'CMS' : { 'machine_model' : 'cernvm3',
'user_data' : 'https://repo.gridpp.ac.uk/vacproject/cms/user_data',
'root_image' : 'https://repo.gridpp.ac.uk/vacproject/cms/cernvm3.iso',
'backoff_seconds' : '3600',
'fizzle_seconds' : '1800',
'max_wallclock_seconds' : '172800',
'target_share' : '1.0',
'root_public_key' : '/root/.ssh/id_rsa.pub',
'heartbeat_file' : 'vm-heartbeat',
'heartbeat_seconds' : '600',
'accounting_fqan' : '/cms/Role=NULL/Capability=NULL',
'user_data_option_entry' : 'CHANGEME',
'user_data_option_checksum' : 'CHANGEME',
'user_data_option_version' : 'CHANGEME',
'user_data_file_hostcert' : 'hostcert.pem',
'user_data_file_hostkey' : 'hostkey.pem',
'user_data_option_cvmfs_proxy' : 'http://169.254.169.254:3128/'
},
'LHCb' : { 'machine_model' : 'cernvm3',
'user_data' : 'https://lhcbproject.web.cern.ch/lhcbproject/Operations/VM/user_data',
'root_image' : 'https://lhcbproject.web.cern.ch/lhcbproject/Operations/VM/cernvm3.iso',
'backoff_seconds' : '3600',
'fizzle_seconds' : '600',
'max_wallclock_seconds' : '172800',
'target_share' : '1.0',
'root_public_key' : '/root/.ssh/id_rsa.pub',
'heartbeat_file' : 'vm-heartbeat',
'heartbeat_seconds' : '600',
'accounting_fqan' : '/lhcb/Role=NULL/Capability=NULL',
'user_data_option_dirac_site' : 'CHANGEME',
'user_data_file_hostcert' : 'hostcert.pem',
'user_data_file_hostkey' : 'hostkey.pem',
'user_data_option_cvmfs_proxy' : 'http://169.254.169.254:3128/'
}
}
try:
if cgiForm.getfirst('action') == 'uploadp12':
cur.execute('UPDATE machinetypes SET p12=%s,p12updated=NOW() WHERE machinetypeid=%s', (cgiForm.getfirst('p12file'), machinetypeID) )
print 'Status: 302 Found ' + str(inspect.currentframe().f_lineno)
print 'Location: https://viab.gridpp.ac.uk' + requestURI
print
return
except:
pass
try:
if cgiForm['action'].value == 'clonemachinetype' and cgiForm['clonename']:
cloneName = cgiForm['clonename'].value.strip()
if cloneName.translate(None, 'abcdefghijklmnopqrstuvwxyz01234567890.-') != '':
print 'Content-Type: text/html'
print
print 'machinetype names are limited to lowercase letters numbers -'
return
# Exclude any reserved /etc/vac.d/*.conf filenames here
if cloneName == 'settings':
print 'Content-Type: text/html'
print
print 'machinetypes cannot be called settings'
return
cur.execute('SELECT p12,p12updated FROM machinetypes WHERE machinetypeid=%s', machinetypeID)
rows = cur.fetchall()
cur.execute('INSERT INTO machinetypes SET spaceid=%s,machinetypename=%s,p12=%s,p12updated=%s',
(spaceID, cloneName, rows[0]['p12'], rows[0]['p12updated']))
cur.execute('INSERT INTO machinetypeopts (machinetypeid,optname,value) SELECT %s,optname,value FROM machinetypeopts WHERE machinetypeid=%s',
(cur.lastrowid, machinetypeID) )
print 'Status: 302 Found ' + str(inspect.currentframe().f_lineno)
print 'Location: https://viab.gridpp.ac.uk/dashboard/' + siteName + '/' + spaceName + '/machinetypes/' + cloneName + '/'
print
return
except:
pass
try:
if cgiForm['action'].value == 'movemachinetype' and cgiForm['newspaceid']:
newSpaceID = int(cgiForm['newspaceid'].value.strip())
cur.execute('UPDATE machinetypes SET spaceid=%s WHERE machinetypeid=%s', (newSpaceID, machinetypeID))
print 'Status: 302 Found ' + str(inspect.currentframe().f_lineno)
print 'Location: https://viab.gridpp.ac.uk' + requestURI
print
return
except:
pass
try:
if cgiForm['action'].value == 'addpresets' and cgiForm['submit']:
presetmachinetypeName = cgiForm['submit'].value.strip()
if presetmachinetypeName in machinetypePresets:
for presetOptName in machinetypePresets[presetmachinetypeName]:
cur.execute('INSERT INTO machinetypeopts SET machinetypeid=%s,optname=%s,value=%s',
(machinetypeID,
presetOptName,
machinetypePresets[presetmachinetypeName][presetOptName]))
else:
print 'Content-Type: text/html'
print
print 'machinetype presets not found!'
return
print 'Status: 302 Found ' + str(inspect.currentframe().f_lineno)
print 'Location: https://viab.gridpp.ac.uk' + requestURI
print
return
except:
pass
try:
if cgiForm['action'].value == 'addoption' and cgiForm['optname'] and cgiForm['value']:
cur.execute('INSERT INTO machinetypeopts SET machinetypeid=%s,optname=%s,value=%s',
(machinetypeID, cgiForm['optname'].value, cgiForm['value'].value.strip()))
print 'Status: 302 Found ' + str(inspect.currentframe().f_lineno)
print 'Location: https://viab.gridpp.ac.uk' + requestURI
print
return
except:
pass
try:
if cgiForm['action'].value == 'updateoption' and cgiForm['optname']:
try:
value = cgiForm['value'].value.strip()
except:
value = None
else:
if value == '':
value = None
if value is None:
cur.execute('DELETE FROM machinetypeopts WHERE machinetypeid=%s AND optname=%s',
(machinetypeID, cgiForm['optname'].value))
else:
try:
cur.execute('UPDATE machinetypeopts SET value=%s WHERE machinetypeid=%s AND optname=%s',
(value, machinetypeID, cgiForm['optname'].value))
except:
pass
print 'Status: 302 Found ' + str(inspect.currentframe().f_lineno)
print 'Location: https://viab.gridpp.ac.uk' + requestURI
print
return
except:
pass
htmlHeader('machinetype ' + machinetypeName)
print ('<div class="breadcrumbs"><a href="/dashboard/">Dashboard</a> ' +
'/ <a href="/dashboard/' + siteName + '/">' + siteName + '</a> ' +
'/ <a href="/dashboard/' + siteName + '/' + spaceName + '/">' + spaceName + '</a> ' +
'/ ' + machinetypeName + '</div>')
print '<h1>machinetype ' + machinetypeName + '</h1>'
print '<h2>Options</h2>'
cur.execute('SELECT machinetypeoptid,optname,value FROM machinetypeopts WHERE machinetypeid=%s', machinetypeID)
rows = cur.fetchall()
if len(rows) > 0:
print '<p>To remove an option, set its value blank and update it'
print '<p><table class="center">'
print '<tr><th class="oddeven">Option</th><th class="oddeven"> </th><th class="oddeven">Value</th></tr>'
n=0
for row in rows:
print '<tr><td class="' + oddEven(n) + '">' + row['optname'] + '</td>'
print '<td class="' + oddEven(n) + '"> = </td><td class="' + oddEven(n) + '">'
print '<form method="post" action="' + requestURI + '">'
print '<input type="hidden" name="action" value="updateoption">'
print '<input type="hidden" name="optname" value="' + row['optname'] + '">'
print '<input type="text" name="value" value="' + row['value'] + '" size="40">'
htmlFormCookie(userDN)
print '<input type="submit" value="Update option">'
print '</form>'
print '</td></tr>\n'
n += 1
print '</table>'
print '<h3>Add option</h3>'
print '<form method="post" action="' + requestURI + '">'
print '<input type="text" name="optname"> = <input type="text" name="value">'
htmlFormCookie(userDN)
print '<input type="submit" value="Add option"> <input type="hidden" name="action" value="addoption">'
print '</form>'
print '<h3>Pre-set options</h3>'
print '<p>You can use the buttons below to add a group of preset options to this '
print 'machinetype if they do not already exist. Some options will still need '
print "to be edited in line with the machinetype's own instructions and these "
print 'have the default value CHANGEME.'
print '<form method="post" action="' + requestURI + '">'
print '<p style="text-align: center">machinetype name: '
htmlFormCookie(userDN)
print '<input type="hidden" name="action" value="addpresets">'
for presetName in sorted(machinetypePresets):
print '<input type="submit" name="submit" value="' + presetName + '">'
print '</form>'
print '<h2>Clone machinetype</h2>'
print '<form method="post" action="' + requestURI + '">'
print 'New machinetype name: <input type="text" name="clonename">'
htmlFormCookie(userDN)
print '<input type="submit" value="Clone machinetype"><input type="hidden" name="action" value="clonemachinetype">'
print '</form>'
cur.execute('SELECT spaces.spaceid,spacename FROM spaces LEFT JOIN machinetypes ON machinetypes.spaceid=spaces.spaceid AND machinetypes.machinetypename=%s WHERE siteid=%s AND spaces.spaceid<>%s AND machinetypes.machinetypeid IS NULL ORDER BY spacename',
(machinetypeName, siteID, spaceID) )
spaceRows = cur.fetchall()
print '<h2>Move machinetype to another space</h2>'
if len(spaceRows) > 0:
print '<p>You can use this form to move this machinetype to another space at this site. Only spaces which do not already have a machinetype with the name "' + machinetypeName + '" are shown. '
print '<form method="post" action="' + requestURI + '">'
print 'New space: <select name="newspaceid">'
for spaceRow in spaceRows:
print '<option value="' + str(spaceRow['spaceid']) + '">' + spaceRow['spacename'] + '</option>'
print '</select>'
print '<input type="submit" value="Move machinetype"><input type="hidden" name="action" value="movemachinetype">'
htmlFormCookie(userDN)
print '</form>'
else:
print '<p>There are no spaces at this site which you can move this machinetype to, either because there are no other spaces, or because they already have a machinetype with the name "' + machinetypeName + '".'
print '<h2>Certificate/key .p12 file</h2>'
cur.execute('SELECT LENGTH(p12) AS p12len,p12,p12updated FROM machinetypes WHERE machinetypeid=%s', machinetypeID)
rows = cur.fetchall()
print '<p>.p12 file ' + str(rows[0]['p12len']) + ' bytes, updated ' + str(rows[0]['p12updated'])
print '<h3>Upload .p12 file</h3>'
print '<form method="post" action="' + requestURI + '" enctype="multipart/form-data">'
print '<input type="file" name="p12file">'
htmlFormCookie(userDN)
print '<br><input type="submit" value="Upload .p12 file"> <input type="hidden" name="action" value="uploadp12">'
print '</form>'
htmlFooter(userDN)
def oneFactory(requestURI, userDN, cgiForm, siteName, siteID, spaceName, spaceID, factoryName, factoryID):
global cur
try:
if cgiForm['action'].value == 'updatefactory' and cgiForm['ip'] and cgiForm['mac']:
try:
mbPerCpu = int(cgiForm['mb_per_cpu'].value)
except:
mbPerCpu = 0
try:
udpTimeoutSeconds = float(cgiForm['udp_timeout_seconds'].value)
except:
udpTimeoutSeconds = 0.0
try:
cpuPerMachine = int(cgiForm['cpu_per_machine'].value)
except:
cpuPerMachine = 0
try:
hs06PerCpu = float(cgiForm['hs06_per_cpu'].value)
except:
hs06PerCpu = 0.0
try:
draining = int(cgiForm['draining'].value)
except:
draining = 0
cur.execute('UPDATE factories SET ip=%s,mac=%s,mb_per_cpu=%s,udp_timeout_seconds=%s,' +
'cpu_per_machine=%s,hs06_per_cpu=%s,draining=%s,updated=NOW() ' +
'WHERE factoryid=%s AND spaceid=%s',
( cgiForm['ip'].value, cgiForm['mac'].value, mbPerCpu, udpTimeoutSeconds,
cpuPerMachine, hs06PerCpu, draining,
factoryID, spaceID) )
print 'Status: 302 Found ' + str(inspect.currentframe().f_lineno)
print 'Location: https://viab.gridpp.ac.uk' + requestURI
print
return
except:
pass
htmlHeader('Factory ' + factoryName)
cur.execute('SELECT * FROM factories LEFT JOIN factoryversions ON factory=factoryname AND space=%s AND site=%s WHERE factoryID=%s', [spaceName, siteName, factoryID])
rows = cur.fetchall()
try:
viab_version = re.search('\(ViaB ([^)]*)\)', rows[0]['os_issue']).group(1)
except:
viab_version = '???'
try:
vac_version = rows[0]['vac_version'].split()[1]
except:
vac_version = '???'
print ('<div class="breadcrumbs"><a href="/dashboard/">Dashboard</a> ' +
'/ <a href="/dashboard/' + siteName + '/">' + siteName + '</a> ' +
'/ <a href="/dashboard/' + siteName + '/' + spaceName + '/">' + spaceName + '</a> ' +
'/ ' + factoryName + '</div>')
print '<h1>Factory ' + factoryName + '</h1>'
print '<form method="post" action="' + requestURI + '">'
print '<table class="center">'
print '<tr><td>Hostname:</td><td>' + factoryName + '</td></tr>'
print '<tr><td>IP:</td><td><input type="text" name="ip" value="' + rows[0]['ip'] + '"></td></tr>'
print '<tr><td>MAC:</td><td><input type="text" name="mac" value="' + rows[0]['mac'] + '"></td></tr>'
print '<tr><td>mb_per_cpu:</td><td><input type="text" name="mb_per_cpu" value="' + str(rows[0]['mb_per_cpu']) + '"></td></tr>'
print '<tr><td>udp_timeout_seconds:</td><td><input type="text" name="udp_timeout_seconds" value="' + str(rows[0]['udp_timeout_seconds']) + '"></td></tr>'
print '<tr><td>cpu_per_machine:</td><td><input type="text" name="cpu_per_machine" value="' + str(rows[0]['cpu_per_machine']) + '"></td></tr>'
print '<tr><td>hs06_per_cpu:</td><td><input type="text" name="hs06_per_cpu" value="' + str(rows[0]['hs06_per_cpu']) + '"></td></tr>'
print '<tr><td>Draining:</td><td> Yes<input type="radio" name="draining" value="1" ' + ('checked' if rows[0]['draining'] == 1 else '') + \
'> No<input type="radio" name="draining" value="0" ' + ('checked' if rows[0]['draining'] != 1 else '') + '> </td></tr>'
print '<tr><td colspan=2 style="text-align: center"><input type="submit" value="Update factory"></td></tr>'
htmlFormCookie(userDN)
print '<input type="hidden" name="action" value="updatefactory">'
print '<tr><td colspan=2>Remember that changes will only take effect once you have republished the configuration RPM and the factory has done its hourly automatic yum update!<p></td></tr>'
print '<tr><td colspan=2 style="text-align: center"><b><big>Information from last Vac-in-a-Box heartbeat</big></b></td></tr>'
print '<tr><td>Vac-in-a-Box heartbeat:</td><td>' + str(rows[0]['time_received']) + '</td></tr>'
print '<tr><td>Vac-in-a-Box version:</td><td>' + viab_version + '</td></tr>'
print '<tr><td>Vac version:</td><td>' + vac_version + '</td></tr>'
print '<tr><td>Kernel version:</td><td>' + str(rows[0]['kernel_version']) + '</td></tr>'
print '<tr><td>Boot time:</td><td>' + str(rows[0]['boot_time']) + '</td></tr>'
print '<tr><td>Total CPUs:</td><td>' + str(rows[0]['total_cpus']) + '</td></tr>'
print '<tr><td>Running CPUs:</td><td>' + str(rows[0]['running_cpus']) + '</td></tr>'
print '<tr><td>Machine slots:</td><td>' + str(rows[0]['total_machines']) + '</td></tr>'
print '<tr><td>Total HS06 in use:</td><td>' + str(rows[0]['total_hs06']) + '</td></tr>'
print '<tr><td>Free disk (KB):</td><td>' + str(rows[0]['root_disk_avail_kb']) + '</td></tr>'
print '<tr><td>Load average:</td><td>' + str(rows[0]['load_average']) + '</td></tr>'
print '<tr><td>OS issue:</td><td>' + str(rows[0]['os_issue']) + '</td></tr>'
print '<tr><td>Factory heartbeat:</td><td>' + str(rows[0]['factory_heartbeat_time']) + '</td></tr>'
print '<tr><td>Responder heartbeat:</td><td>' + str(rows[0]['responder_heartbeat_time']) + '</td></tr>'
print '<tr><td>httpd-mjf heartbeat:</td><td>' + str(rows[0]['mjf_heartbeat_time']) + '</td></tr>'
print '<tr><td>httpd-metadata heartbeat:</td><td>' + str(rows[0]['metadata_heartbeat_time']) + '</td></tr>'
print '<tr><td>Swap used (KB):</td><td>' + str(rows[0]['swap_used_kb']) + '</td></tr>'
print '<tr><td>Swap free (KB):</td><td>' + str(rows[0]['swap_free_kb']) + '</td></tr>'
print '<tr><td>Mem used (KB):</td><td>' + str(rows[0]['mem_used_kb']) + '</td></tr>'
print '<tr><td>Mem total (KB):</td><td>' + str(rows[0]['mem_total_kb']) + '</td></tr>'
print '</table>'
print '</form>'
htmlFooter(userDN)
def secondsToString(timeStamp):
if timeStamp is None or timeStamp == 0:
return ' - '
seconds = int(time.time() - timeStamp)
if seconds < 120:
return str(seconds) + 's'
elif seconds < 7200:
return '%dm' % (seconds / 60)
elif seconds < 172800:
return '%dh' % (seconds / 3600)
else:
return '%dd' % (seconds / 86400)
def publishSpace(requestURI, userDN, siteName, siteID, spaceName, spaceID, spaceVersion):
# Set up the temporary directory tree
try:
tempDir = tempfile.mkdtemp(prefix='viab-cgi-')
except:
return None
# Run the viab-publish script on our temporary directory
try:
f = os.popen('/var/lib/viab/etc/' + spaceVersion + '/viab-publish ' + tempDir + ' ' + siteName + ' ' + spaceName + ' ' + spaceVersion + ' 2>&1', 'r')
commandOutput = f.read()
retCode = f.close()
except:
return None
if retCode is None:
retCode = 0
commandOutput += '\n(Return code of viab-publish = ' + str(retCode) + ')\n'
# Clean up our temporary directory tree
shutil.rmtree(tempDir)
if retCode == 0:
cur.execute('UPDATE spaces SET published=NOW(),publishlog=%s WHERE spaceID=%s', (str(commandOutput), str(spaceID)))
else:
cur.execute('UPDATE spaces SET publishlog=%s WHERE spaceID=%s', (str(commandOutput), str(spaceID)))
print 'Status: 302 Found ' + str(inspect.currentframe().f_lineno)
print 'Location: https://viab.gridpp.ac.uk' + requestURI
print
return
def oneSpace(requestURI, userDN, cgiForm, siteName, siteID, spaceName, spaceID, published, spaceVersion):
global cur
try:
if cgiForm['action'].value == 'publish':
publishSpace(requestURI, userDN, siteName, siteID, spaceName, spaceID, spaceVersion)
return
except:
pass
try:
if cgiForm['action'].value == 'changeversion' and cgiForm['version'].value:
newSpaceVersion = cgiForm['version'].value.strip()
if '/' in newSpaceVersion or not os.path.isdir('/var/lib/viab/etc/' + newSpaceVersion):
print 'Content-Type: text/html'
print
print 'Version ' + newSpaceVersion + ' does not exist!'
return
cur.execute('UPDATE spaces SET version=%s WHERE spaceid=%s', (newSpaceVersion, spaceID))
print 'Status: 302 Found ' + str(inspect.currentframe().f_lineno)
print 'Location: https://viab.gridpp.ac.uk' + requestURI
print
return
except:
pass
try:
if cgiForm['action'].value == 'addsubnet' and cgiForm['subnet'].value:
subnet = cgiForm['subnet'].value.strip()
netmask = cgiForm['netmask'].value.strip()
router = cgiForm['router'].value.strip()
nameservers = cgiForm['nameservers'].value.strip()
ntpservers = cgiForm['ntpservers'].value.strip().lower()
if not nameservers or nameservers.translate(None, '01234567890. ') != '':
print 'Content-Type: text/html'
print
print 'Name servers must be one or more IP addresses, separated by spaces!'
return
if not ntpservers or ntpservers.translate(None, 'abcdefghijklmnopqrstuvwxyz01234567890.- ') != '':
print 'Content-Type: text/html'
print
print 'NTP servers must be one or more DNS names or IP addresses, separated by spaces!'
return
cur.execute('INSERT INTO subnets SET spaceid=%s,subnet=%s,netmask=%s,router=%s,nameservers=%s,ntpservers=%s',
(spaceID, subnet, netmask, router, nameservers, ntpservers))
print 'Status: 302 Found ' + str(inspect.currentframe().f_lineno)
print 'Location: https://viab.gridpp.ac.uk' + requestURI
print
return
except:
pass
try:
if cgiForm['action'].value == 'deletesubnets' and cgiForm['deletelist'].value:
deleteList = cgiForm.getlist('deletelist')
for deleteSubnet in deleteList:
cur.execute('DELETE FROM subnets WHERE spaceid=%s AND subnetid=%s',
[ spaceID, deleteSubnet] )
deleteOrphans()
print 'Status: 302 Found ' + str(inspect.currentframe().f_lineno)
print 'Location: https://viab.gridpp.ac.uk' + requestURI
print
return
except:
pass
try:
if cgiForm['action'].value == 'addfactory' and cgiForm['factoryname'].value and cgiForm['ip'] and cgiForm['mac']:
factoryName = cgiForm['factoryname'].value.strip()
if factoryName.translate(None, 'abcdefghijklmnopqrstuvwxyz01234567890.-') != '':
print 'Content-Type: text/html'
print
print 'Host names are limited to lowercase letters numbers . -'
return
ip = cgiForm['ip'].value.strip()
if ip.translate(None, '01234567890.') != '' or ip.count('.') != 3:
print 'Content-Type: text/html'
print
print 'IP addreses are limited to digits and .'
return
mac = cgiForm['mac'].value.strip().lower()
if mac.translate(None, 'abcdef01234567890:') != '' or len(mac) != 17:
print 'Content-Type: text/html'
print
print 'MAC addreses are limited to hexadecimal digits and :'
return
cur.execute('INSERT INTO factories SET siteid=%s,spaceid=%s,factoryname=%s,ip=%s,mac=%s,' +
'mb_per_cpu=%s,udp_timeout_seconds=%s,' +
'cpu_per_machine=%s,hs06_per_cpu=%s,' +
'updated=NOW()',
( siteID, spaceID, factoryName, ip, mac,
int(cgiForm['mb_per_cpu'].value), float(cgiForm['udp_timeout_seconds'].value),
int(cgiForm['cpu_per_machine'].value), float(cgiForm['hs06_per_cpu'].value)
)
)
print 'Status: 302 Found ' + str(inspect.currentframe().f_lineno)
print 'Location: https://viab.gridpp.ac.uk' + requestURI
print
return
except:
pass
if 'action' in cgiForm and cgiForm['action'].value == 'addfactories':
try:
factories = cgiForm['factories'].value.split('\n')
except:
factories = None
if not factories:
errorPage(requestURI, userDN, 'No factories given', 'You need to list some factories in the text box!')
return
try:
mb_per_cpu = int(cgiForm['mb_per_cpu'].value)
udp_timeout_seconds = float(cgiForm['udp_timeout_seconds'].value)
cpu_per_machine = int(cgiForm['cpu_per_machine'].value)
hs06_per_cpu = float(cgiForm['hs06_per_cpu'].value)
except:
errorPage(requestURI, userDN, 'Missing value(s)', 'You need to give a value for each of the factory parameters!')
return
sqlTriplets = []
for factoryLine in factories:
if factoryLine.strip() == '':
continue
try:
(mac, factoryName, ip) = factoryLine.lower().strip().split()
except:
errorPage(requestURI, userDN, 'Bad factory line', 'This line is not properly formatted: "' + factoryLine + '"')
return
if mac.translate(None, 'abcdef01234567890:') != '' or len(mac) != 17:
errorPage(requestURI, userDN, 'Bad factory MAC address', 'The MAC address is in the wrong format in "' + factoryLine + '"')
return
if factoryName.translate(None, 'abcdefghijklmnopqrstuvwxyz01234567890.-') != '':
errorPage(requestURI, userDN, 'Bad factory hostname', 'The hostname is in the wrong format in "' + factoryLine + '"')
return
if ip.translate(None, '01234567890.') != '' or ip.count('.') != 3:
errorPage(requestURI, userDN, 'Bad IP address', 'The IP address is in the wrong format in "' + factoryLine + '"')
return
sqlTriplets.append('mac="%s",factoryname="%s",ip="%s"' % (mac, factoryName, ip))
if len(sqlTriplets) == 0:
errorPage(requestURI, userDN, 'No factories given', 'You need to list some factories in the text box!')
return
outcomes = ''
for sqlTriplet in sqlTriplets:
try:
cur.execute('INSERT INTO factories SET siteid=%s,spaceid=%s,' +
sqlTriplet +
',mb_per_cpu=%s,udp_timeout_seconds=%s,' +
'cpu_per_machine=%s,hs06_per_cpu=%s,' +
'updated=NOW()',
( siteID, spaceID,
mb_per_cpu, udp_timeout_seconds,
cpu_per_machine, hs06_per_cpu
))
except MySQLdb.IntegrityError:
outcomes += 'Failed to add ' + sqlTriplet + ' due to duplicates<br>\n'
except :
outcomes += 'Failed to add ' + sqlTriplet + ' (not a duplication problem)<br>\n'
if outcomes:
errorPage(requestURI, userDN, 'Problem(s) adding new factories', 'The following problem(s) were encountered and these factories were not added:<p>' + outcomes)
return
print 'Status: 302 Found ' + str(inspect.currentframe().f_lineno)
print 'Location: https://viab.gridpp.ac.uk' + requestURI
print
return
try:
if cgiForm['action'].value == 'addmachinetype' and cgiForm['machinetypename'].value:
machinetypeName = cgiForm['machinetypename'].value.strip()
if machinetypeName.translate(None, 'abcdefghijklmnopqrstuvwxyz01234567890.-') != '':
print 'Content-Type: text/html'
print
print 'machinetype names are limited to lowercase letters numbers -'
return
# Exclude any reserved /etc/vac.d/*.conf filenames here
if machinetypeName == 'settings':
print 'Content-Type: text/html'
print
print 'machinetypes cannot be called settings'
return
cur.execute('INSERT INTO machinetypes SET spaceid=%s,machinetypename=%s', (spaceID, machinetypeName))
print 'Status: 302 Found ' + str(inspect.currentframe().f_lineno)
print 'Location: https://viab.gridpp.ac.uk' + requestURI
print
return
except:
pass
try:
if cgiForm['action'].value == 'Delete factories' and cgiForm['actionlist']:
deleteList = cgiForm.getlist('actionlist')
for deleteFactory in deleteList:
cur.execute('DELETE FROM factories WHERE spaceid=%s AND factoryid=%s', ( spaceID, deleteFactory ) )
print 'Status: 302 Found ' + str(inspect.currentframe().f_lineno)
print 'Location: https://viab.gridpp.ac.uk' + requestURI
print
return
except:
pass
try:
if (cgiForm['action'].value == 'Start draining' or cgiForm['action'].value == 'Cancel draining') and cgiForm['actionlist']:
actionList = cgiForm.getlist('actionlist')
for actionFactory in actionList:
cur.execute('UPDATE factories SET draining=%s WHERE spaceid=%s AND factoryid=%s',
(1 if cgiForm['action'].value == 'Start draining' else 0, spaceID, actionFactory ) )
print 'Status: 302 Found ' + str(inspect.currentframe().f_lineno)
print 'Location: https://viab.gridpp.ac.uk' + requestURI
print
return
except:
pass
try:
if cgiForm['action'].value.startswith('Move to ') and cgiForm['actionlist']:
actionList = cgiForm.getlist('actionlist')
for actionFactory in actionList:
cur.execute('UPDATE factories SET spaceid=(SELECT spaceid FROM spaces WHERE spacename=%s) WHERE spaceid=%s AND factoryid=%s',
(cgiForm['action'].value[8:], spaceID, actionFactory ) )
print 'Status: 302 Found ' + str(inspect.currentframe().f_lineno)
print 'Location: https://viab.gridpp.ac.uk' + requestURI
print
return
except:
pass
try:
if cgiForm['action'].value == 'deletemachinetypes' and cgiForm['deletelist']:
deleteList = cgiForm.getlist('deletelist')
for deletemachinetype in deleteList:
cur.execute('DELETE FROM machinetypes WHERE spaceid=%s AND machinetypeid=%s', ( spaceID, int(deletemachinetype) ) )
deleteOrphans()
print 'Status: 302 Found ' + str(inspect.currentframe().f_lineno)
print 'Location: https://viab.gridpp.ac.uk' + requestURI
print
return
except:
pass
htmlHeader('Space ' + spaceName)
cur.execute('SELECT factoryid,factoryname,ip,mac,cpu_per_machine,hs06_per_cpu,os_issue,factoryversions.vac_version,UNIX_TIMESTAMP(factoryversions.boot_time) AS boot_time,UNIX_TIMESTAMP(time_received) AS time_received,draining FROM factories LEFT JOIN factoryversions ON factory=factoryname AND space=%s AND site=%s WHERE spaceid=%s ORDER BY factoryname', [spaceName, siteName, spaceID])
rows = cur.fetchall()
print ('<div class="breadcrumbs"><a href="/dashboard/">Dashboard</a> / ' +
'<a href="/dashboard/' + siteName + '/">' + siteName + '</a> ' +
'/ ' + spaceName + '</div>')
print '<h1>Space ' + spaceName + '</h1>'
print '<form method="post" action="' + requestURI + '">'
if published:
print '<p>The configuration RPM for space ' + spaceName + ' was published on ' + str(published) + '. '
else:
print '<p>The configuration RPM for space ' + spaceName + ' has not been published yet. '
print '<input type="hidden" name="action" value="publish">'
htmlFormCookie(userDN)
print '<input type="submit" value="Publish configuration RPM">'
print '</form>'
if published:
print '<p>If you need to (re)install this space from scratch, boot the first factory using the '
print '<a href="/iso/' + siteName + '/' + spaceName + '/viab-usb.iso">USB .iso image</a>.'
else:
print '<p>Once the RPM has been publihsed, you will be able to download the USB .iso boot image.'
# Change version paragraph
print '<form method="post" action="' + requestURI + '">'
print '<input type="hidden" name="action" value="changeversion">'
print '<p>Vac-in-a-Box version ' + spaceVersion + ' will be installed on factories in this space, '
if prodVersion == spaceVersion:
print ' which is the recommended production version. '
else:
print ' <b>but the recommended production version is now ' + prodVersion + '.</b> '
print '<br><select name="version">\n'
versionsList = os.listdir('/var/lib/viab/etc')
versionsList.sort()
for v in versionsList:
print '<option value="' + v + '" ' + ('selected' if v == spaceVersion else '') + '>Version ' + v + '</option>\n'
print '</select>\n'
htmlFormCookie(userDN)
print '<input type="submit" value="Change Vac-in-a-Box version">'
print '</form>'
print '<h2>Factories in this space</h2>'
if len(rows) > 0:
print '<form method="post" action="' + requestURI + '">'
print '<table class="center">'
print '<tr><th class="oddeven">Host</th><th class="oddeven">IP</th><th class="oddeven">MAC</th><th class="oddeven">ViaB/Vac</th><th class="oddeven">Booted</th><th class="oddeven">Heartbeat</th><th class="oddeven">cpu /<br>machine</th><th class="oddeven">HS06<br>/ cpu</th>'
print '<th class="oddeven"> </th><th class="oddeven"><input type="checkbox" onchange="for (var i = 0; i < this.form.length; ++i) { if (this.form[i].type == \'checkbox\') { form[i].checked = this.checked; } }"></th></tr>'
cur.execute('SELECT spacename,spaceid FROM spaces WHERE siteid=%s ORDER BY spacename', siteID)
spaceRows = cur.fetchall()
n=0
for row in rows:
if row['time_received'] < int(time.time() - 86400):
heartbeatClass = 'alarm'
elif row['time_received'] < int(time.time() - 3659):
heartbeatClass = 'warning'
else:
heartbeatClass = oddEven(n)
try:
viab_version = re.search('\(ViaB ([^)]*)\)', row['os_issue']).group(1)
except:
viab_version = '???'
try:
vac_version = row['vac_version'].split()[1]
except:
vac_version = '???'
print ('<tr><td class="' + oddEven(n) + '" style="white-space: nowrap"><a href="/dashboard/' + siteName + '/' + spaceName + '/factories/' + row['factoryname'] + '/">' + row['factoryname'].split('.')[0] + '</a></td>' +
'<td class="' + oddEven(n) + '">' + row['ip'] + '</td>' +
'<td class="' + oddEven(n) + '">' + row['mac'] + '</td>' +
'<td class="' + oddEven(n) + '">' + viab_version + ' / ' + vac_version + '</td>' +
'<td class="' + oddEven(n) + '">' + secondsToString(row['boot_time']) + '</td>' +
'<td class="' + heartbeatClass + '">' + secondsToString(row['time_received']) + '</td>' +
'<td class="' + oddEven(n) + '">' + str(row['cpu_per_machine']) + '</td>' +
'<td class="' + oddEven(n) + '">' + str(row['hs06_per_cpu']) + '</td>' +
'<td class="' + oddEven(n) + '">' + ('Draining' if row['draining'] == 1 else '') + '</td>' +
'<td class="' + oddEven(n) + '"><input type="checkbox" name="actionlist" value="' + str(row['factoryid']) + '"></td>' +
'</tr>\n')
n += 1
print '<tr><td colspan="10">'
print '<select name="actionselect" onchange="document.getElementById(\'actionsubmit\').value=this.value; document.getElementById(\'actionsubmit\').disabled=false;">'
print '<option selected disabled>Choose action to apply</option>'
print '<option value="Start draining">Start draining</option>'