This repository has been archived by the owner on Sep 23, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 82
/
nimbusconfigure.py
executable file
·1072 lines (875 loc) · 38.5 KB
/
nimbusconfigure.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/env python
import logging
import optparse
import os
import socket
import sys
import traceback
import ConfigParser
from StringIO import StringIO
import readline
import shutil
import string
import time
from random import Random
from nimbusweb.setup import pathutil,javautil,checkssl,gtcontainer,autoca,derbyutil,runutil
from nimbusweb.setup.setuperrors import *
CONFIGSECTION = 'nimbussetup'
DEFAULTCONFIG = """
[nimbussetup]
# relative to base directory
hostcert: var/hostcert.pem
hostkey: var/hostkey.pem
ca.dir: var/ca
ca.trustedcerts.dir: var/ca/trusted-certs
gridmap: services/etc/nimbus/nimbus-grid-mapfile
keystore: var/keystore.jks
keystore.pass: changeit
services.enabled: True
services.wait: 10
web.enabled: False
cumulus.enabled: True
lantorrent.enabled: False
"""
CONFIG_STATE_PATH = 'nimbus-setup.conf'
CONFIG_KEY_CA_DIR="ca.dir"
CONFIG_KEY_HOSTCERT="hostcert"
CONFIG_KEY_HOSTKEY="hostkey"
CONFIG_KEY_KEYSTORE="keystore"
CONFIG_KEY_GRIDMAP="gridmap"
CONFIG_KEY_TRUSTED_CERTS="ca.trustedcerts.dir"
CA_NAME_QUESTION = """
Nimbus uses an internal Certificate Authority (CA) for some services. This CA
is also used to generate host and user certificates if you do not have your own.
This CA will be created in %(ca.dir)s
Please pick a unique, one word CA name or hit ENTER to use a UUID.
For example, if you are installing this on the "Jupiter" cluster, you might use
"JupiterNimbusCA" as the name.
"""
CONFIG_HEADER = """
# Autogenerated at %(time)s
#
# This file contains configuration values used by the nimbus-configure program.
# If you want to change any of these values, you may edit this file, but you
# must run nimbus-configure before the change will take effect.
"""
ENVFILE_BODY = """
# Autogenerated at %(time)s
#
# This file contains environment variables which are necessary to use some of
# the Nimbus internal tools directly
NIMBUS_HOME=%(NIMBUS_HOME)s
export NIMBUS_HOME
GLOBUS_LOCATION=%(GLOBUS_LOCATION)s
export GLOBUS_LOCATION
X509_CERT_DIR=%(X509_CERT_DIR)s
export X509_CERT_DIR
"""
KEYSTORE_MISMATCH_MSG = """
A Java keystore already exists at:
%(keystore)s
However, it does not contain the host certificate and private key which are
being configured.
Certificate: %(hostcert)s
Private key: %(hostkey)s
This may be because you have switched certificates and the keystore contains
the old version. If so, the best solution is to delete (or relocate) the
keystore and rerun nimbus-configure to generate a new one.
"""
def getlog(override=None):
"""Allow developer to replace logging mechanism, e.g. if this
module is incorporated into another program as an API.
Keyword arguments:
* override -- Custom logger (default None, uses global variable)
"""
global _log
if override:
_log = override
try:
_log
except:
_log = logging.getLogger("nimbussetup")
_log.setLevel(logging.DEBUG)
return _log
def configureLogging(level, formatstring=None, logger=None):
"""Configure the logging format and mechanism. Sets global 'log' variable.
Required parameter:
* level -- log level
Keyword arguments:
* formatstring -- Custom logging format (default None, uses time+level+msg)
* logger -- Custom logger (default None)
"""
global log
logger = getlog(override=logger)
if not formatstring:
formatstring = "%(asctime)s (%(filename)s:%(lineno)d): %(message)s"
formatter = logging.Formatter(formatstring)
ch = logging.StreamHandler()
ch.setLevel(level)
ch.setFormatter(formatter)
logger.addHandler(ch)
# set global variable
log = logger
log.debug("debug enabled")
def getconfig(filepath=None):
config = ConfigParser.SafeConfigParser()
fh = StringIO(DEFAULTCONFIG)
config.readfp(fh)
if filepath:
for path in config.read(filepath):
log.debug("Read config from: '%s'" % path)
return config
class ARGS:
"""Class for command-line argument constants"""
BASEDIR_LONG = "--basedir"
BASEDIR = "-b"
BASEDIR_HELP = "Path to base Nimbus directory"
CONFIGPATH_LONG = "--conf"
CONFIGPATH = "-c"
CONFIGPATH_HELP = "Path to configuration file"
DEBUG_LONG = "--debug"
DEBUG = "-d"
DEBUG_HELP = "Log debug messages"
HOSTNAME_LONG = "--hostname"
HOSTNAME = "-H"
HOSTNAME_HELP = "Fully qualified hostname of machine"
CANAME_LONG= "--caname"
CANAME = "-n"
CANAME_HELP = "Unique name to give CA"
HOSTKEY_LONG = "--hostkey"
HOSTKEY = "-k"
HOSTKEY_HELP = "Path to PEM-encoded host private key"
HOSTCERT_LONG = "--hostcert"
HOSTCERT = "-C"
HOSTCERT_HELP = "Path to PEM-encoded host certificate"
AUTOCONFIG_LONG= "--autoconfig"
AUTOCONFIG_HELP = "Run the Nimbus autoconfig tool to test VMM communication"
IMPORTDB_LONG= "--import-db"
IMPORTDB_HELP = "Import a Nimbus accounting database from another install"
IMPORTPREV_LONG= "--import-prev"
IMPORTPREV_HELP = "[Only used programmatically]"
IMPORTVMMS_LONG= "--import-2.5-vmms"
IMPORTVMMS_HELP = "Import VMMs from an old-style 2.5 'vmm-pools' directory"
IMPORTCUMUDB_LONG= "--import-cumulusdb"
IMPORTCUMUDB_HELP = "[Only used programmatically]"
PRINT_HOSTNAME_LONG = "--print-hostname"
PRINT_HOSTNAME = "-Z"
PRINT_HOSTNAME_HELP = "Print chosen hostname or error if none chosen"
PRINT_REPOBUCKET_LONG = "--print-repobucket"
PRINT_REPOBUCKET = "-R"
PRINT_REPOBUCKET_HELP = "Print repo bucket for Cumulus"
def validateargs(opts):
seeh = "see help (-h)"
if not opts.basedir:
raise InvalidInput("%s required, %s." % (ARGS.BASEDIR_LONG, seeh))
if opts.configpath and not os.path.exists(opts.configpath):
raise InvalidInput("%s file specified does not exist: '%s'" %
(ARGS.CONFIGPATH_LONG, opts.configpath))
if opts.hostkey or opts.hostcert:
if not (opts.hostkey and opts.hostcert):
raise InvalidInput(
"You must specify both %s and %s paths, or neither" %
(ARGS.HOSTCERT_LONG, ARGS.HOSTKEY_LONG))
if not os.path.exists(opts.hostkey):
raise InvalidInput("The specified host key does not exist: %s" %
opts.hostkey)
if not os.path.exists(opts.hostcert):
raise InvalidInput("The specified host cert does not exist: %s" %
opts.hostcert)
def parsersetup():
"""Return configured command-line parser."""
ver = "Nimbus setup"
usage = "see help (-h)."
parser = optparse.OptionParser(version=ver, usage=usage)
group = optparse.OptionGroup(parser, "Actions", "-------------")
group.add_option(ARGS.AUTOCONFIG_LONG,
action="store_true", dest="autoconfig",
default=False, help=ARGS.AUTOCONFIG_HELP)
group.add_option(ARGS.IMPORTDB_LONG,
dest="importdb", metavar="PATH", help=ARGS.IMPORTDB_HELP)
group.add_option(ARGS.IMPORTVMMS_LONG,
dest="importvmms", metavar="PATH", help=ARGS.IMPORTVMMS_HELP)
group.add_option(ARGS.IMPORTPREV_LONG,
action="store_true", dest="importprev", default=False,
help=ARGS.IMPORTPREV_HELP)
group.add_option(ARGS.IMPORTCUMUDB_LONG,
action="store_true", dest="importcumulusdb", default=False,
help=ARGS.IMPORTCUMUDB_HELP)
group.add_option(ARGS.PRINT_HOSTNAME, ARGS.PRINT_HOSTNAME_LONG,
action="store_true", dest="print_chosen_hostname",
default=False, help=ARGS.PRINT_HOSTNAME_HELP)
group.add_option(ARGS.PRINT_REPOBUCKET, ARGS.PRINT_REPOBUCKET_LONG,
action="store_true", dest="print_repo_bucket",
default=False, help=ARGS.PRINT_REPOBUCKET_HELP)
parser.add_option_group(group)
group = optparse.OptionGroup(parser, "Misc options", "-------------")
group.add_option(ARGS.DEBUG, ARGS.DEBUG_LONG,
action="store_true", dest="debug", default=False,
help=ARGS.DEBUG_HELP)
group.add_option(ARGS.CONFIGPATH, ARGS.CONFIGPATH_LONG,
dest="configpath", metavar="PATH",
help=ARGS.CONFIGPATH_HELP)
group.add_option(ARGS.BASEDIR, ARGS.BASEDIR_LONG,
dest="basedir", metavar="PATH",
help=ARGS.BASEDIR_HELP)
parser.add_option_group(group)
group = optparse.OptionGroup(parser, "Configuration options",
"-------------")
group.add_option(ARGS.HOSTNAME, ARGS.HOSTNAME_LONG,
dest="hostname", metavar="HOST", help=ARGS.HOSTNAME_HELP)
group.add_option(ARGS.CANAME, ARGS.CANAME_LONG,
dest="ca_name", metavar="NAME", help=ARGS.CANAME_HELP)
group.add_option(ARGS.HOSTKEY, ARGS.HOSTKEY_LONG,
dest="hostkey", metavar="PATH", help=ARGS.HOSTKEY_HELP)
group.add_option(ARGS.HOSTCERT, ARGS.HOSTCERT_LONG,
dest="hostcert", metavar="PATH", help=ARGS.HOSTCERT_HELP)
parser.add_option_group(group)
return parser
def fold_opts_to_config(opts, config):
if opts.hostname:
config.set(CONFIGSECTION, 'hostname', opts.hostname)
if opts.ca_name:
config.set(CONFIGSECTION, 'ca.name', opts.ca_name)
if opts.hostkey:
config.set(CONFIGSECTION, CONFIG_KEY_HOSTKEY, opts.hostkey)
if opts.hostcert:
config.set(CONFIGSECTION, CONFIG_KEY_HOSTCERT, opts.hostcert)
def get_user_input(valuename, default=None, required=True):
answer = None
question = valuename + (default and ("(%s): " % default) or ": ")
while not answer:
value = raw_input(valuename+": ")
if value:
answer = value.strip()
elif default:
answer = default
if not answer:
if required:
print "Invalid input. You must specify a value. Or hit Ctrl-C to give up."
else:
return None
return answer
class NimbusSetup(object):
def __init__(self, basedir, config, interactive=True):
self.basedir = basedir
self.config = config
self.interactive = interactive
self.webdir = self.resolve_path('web/')
self.gtdir = self.resolve_path('services/')
self.cadir = self.resolve_config_path(CONFIG_KEY_CA_DIR)
self.trustedcertsdir = self.resolve_config_path(CONFIG_KEY_TRUSTED_CERTS)
self.hostcert_path = self.resolve_config_path(CONFIG_KEY_HOSTCERT)
self.hostkey_path = self.resolve_config_path(CONFIG_KEY_HOSTKEY)
self.keystore_path = self.resolve_config_path(CONFIG_KEY_KEYSTORE)
self.gridmap_path = self.resolve_config_path(CONFIG_KEY_GRIDMAP)
self.envfile_path = self.resolve_path('libexec/environment.sh')
def __getitem__(self, key):
try:
return self.config.get(CONFIGSECTION, key)
except ConfigParser.NoOptionError:
return None
def __setitem__(self, key, value):
return self.config.set(CONFIGSECTION, key, value)
def validate_environment(self):
if not pathutil.is_absolute_path(self.basedir):
raise IncompatibleEnvironment(
"Base directory setting is not absolute")
pathutil.ensure_dir_exists(self.basedir, "base")
pathutil.ensure_dir_exists(self.webdir, "web")
pathutil.ensure_dir_exists(self.gtdir, "GT container")
# check that we have some java
javautil.check(self.webdir, log)
def resolve_path(self, path):
"""
Resolves a path relative to base directory. If absolute, returns as-is.
If relative, joins with self.basedir and returns.
"""
if os.path.isabs(path):
return path
return os.path.join(self.basedir, path)
def resolve_config_path(self, config):
"""
Resolves a path, like resolve_path(), but from a config key.
"""
path = self[config]
if path:
return self.resolve_path(path)
return None
def is_config_present(self, configkey):
path = self[configkey]
if path:
return True
else:
return False
def is_config_relative(self, configkey):
"""
Resolves if a config is a relative path or not.
"""
path = self[configkey]
if not path:
return False
return not os.path.isabs(path)
def ask_hostname(self):
hostguess = self['hostname']
if not hostguess:
hostguess = socket.getfqdn()
if self.interactive:
print "\nWhat is the fully qualified hostname of this machine?\n"
print "Press ENTER to use the detected value (%s)\n" % hostguess
hostname = get_user_input("Hostname", default=hostguess)
else:
print "Using hostname: '%s'" % hostguess
hostname = hostguess
return hostname
def ask_ca_name(self):
ca_name_config = self['ca.name']
if self.interactive:
print CA_NAME_QUESTION % {CONFIG_KEY_CA_DIR : self.cadir}
ca_name = get_user_input("CA Name", default=ca_name_config,
required=False)
if not ca_name:
ca_name = pathutil.uuidgen()
print "You did not enter a name, using '%s'" % ca_name
else:
ca_name = ca_name_config or pathutil.uuidgen()
print "Creating CA with name: '%s'" % ca_name
return ca_name
def write_env_file(self):
"""Writes an environment file users can source."""
f = None
try:
f = open(self.envfile_path,'w')
text = ENVFILE_BODY % {
'time' : time.strftime('%c'),
'NIMBUS_HOME' : self.basedir,
'GLOBUS_LOCATION' : self.gtdir,
'X509_CERT_DIR' : self.trustedcertsdir
}
f.write(text)
finally:
if f:
f.close()
def write_db_props(self):
"""Writes ant properties file used by db-mgmt.xml
"""
persistdir = os.path.join(self.gtdir, 'var/nimbus')
dbsetupdir = os.path.join(self.gtdir, 'share/nimbus')
dbsetuplibdir = os.path.join(self.gtdir, 'share/nimbus/lib')
derbyhomedir = os.path.join(self.gtdir, 'var')
derbylibdir = os.path.join(self.gtdir, 'lib')
pwgenfile = os.path.join(self.gtdir, 'etc/nimbus/workspace-service/other/shared-secret-suggestion.py')
lines = ['#Autogenerated by nimbus-configure\n',
'#'+time.strftime('%c')+'\n']
lines.append('workspace.dbdir.prop=%s\n' % persistdir)
lines.append('workspace.sqldir.prop=%s\n' % dbsetuplibdir)
lines.append('workspace.notifdir.prop=%s\n' % dbsetuplibdir)
lines.append('derby.system.home.prop=%s\n' % derbyhomedir)
lines.append('derby.relative.dir.prop=nimbus\n')
lines.append('derby.classpath.dir.prop=%s\n' % derbylibdir)
lines.append('pwGen.path.prop=%s\n' % pwgenfile)
db_props_path = os.path.join(dbsetupdir,'workspace.persistence.conf')
f = None
try:
f = open(db_props_path, 'w')
f.writelines(lines)
finally:
if f:
f.close()
def write_cumulus_props(self):
"""Writes cumulus.conf file
"""
if not self['hostname']:
err = "hostname should have been determined already"
raise UnexpectedError(err)
cumulus_authz_db = os.path.join(self.basedir, 'cumulus/etc/authz.db')
repo_bucket = self.get_repobucket_no_asking()
lines = ['#Autogenerated by nimbus-configure\n',
'#'+time.strftime('%c')+'\n']
lines.append("\n")
lines.append("# Generally these settings are auto-generated by nimbus-configure.\n")
lines.append("\n")
lines.append("cumulus.authz.db=%s\n" % cumulus_authz_db)
lines.append("cumulus.repo.dir=%s/cumulus/posixdata\n" % (self.basedir))
lines.append("cumulus.host=%s\n" % self['hostname'])
lines.append("cumulus.repo.bucket=%s\n" % repo_bucket)
lines.append("cumulus.repo.prefix=VMS\n")
lines.append("cumulus.publicuser=CumulusPublicUser\n")
cumulus_conf_path = os.path.join(self.gtdir, 'etc/nimbus/workspace-service/cumulus.conf')
f = None
try:
f = open(cumulus_conf_path, 'w')
f.writelines(lines)
finally:
if f:
f.close()
def write_cumulus_init(self):
cumulus_ini_file = os.path.join(self.basedir, 'cumulus/etc/cumulus.ini')
s = ConfigParser.SafeConfigParser()
try:
s.readfp(open(cumulus_ini_file, "r"))
except:
raise Exception("Could not open %s for parsing" % (cumulus_ini_file))
s.set("https", "enabled", "False")
s.set("https", "key", self.hostkey_path)
s.set("https", "cert", self.hostcert_path)
s.set("cb", "hostname", self['hostname'])
s.write(open(cumulus_ini_file, "w"))
def get_hostname_or_ask(self):
if self['hostname']:
hostname = self['hostname']
log.debug('Using configured hostname: "%s". Run with %s to change.',
hostname, ARGS.HOSTNAME_LONG)
else:
hostname = self.ask_hostname()
self['hostname'] = hostname
return hostname
def get_hostname_no_asking(self):
# could be None
return self['hostname']
def get_repobucket_no_asking(self):
# at least get this to one exact place, can determine dynamically later
return "repo"
def perform_setup(self):
# first, set up CA and host cert/key
ca_name = self["ca.name"]
if not os.path.exists(self.cadir):
ca_name = self.ask_ca_name()
self['ca.name'] = ca_name
autoca.createCA(ca_name, self.webdir, self.cadir, log)
if not ca_name:
raise InvalidConfig("CA name is unknown")
ca_cert = os.path.join(self.cadir, 'ca-certs/%s.pem' % ca_name)
ca_key = os.path.join(self.cadir, 'ca-certs/private-key-%s.pem' % ca_name)
pathutil.ensure_file_exists(ca_cert, "CA certificate")
pathutil.ensure_file_exists(ca_key, "CA private key")
hostname = self.get_hostname_or_ask()
#TODO the hostcert/key creation should be extracted from here
# right now it just does a bunch of redundant checks first
checkssl.run(self.webdir, self.hostcert_path, self.hostkey_path, log,
cadir=self.cadir, hostname=hostname)
password = self['keystore.pass']
if not password:
raise InvalidConfig("Keystore password is unknown")
try:
autoca.ensureKeystore(self.hostcert_path, self.hostkey_path,
self.keystore_path, password, self.webdir, log)
except autoca.KeystoreMismatchError:
raise IncompatibleEnvironment(KEYSTORE_MISMATCH_MSG % {
'keystore' : self.keystore_path,
'hostcert' : self.hostcert_path,
'hostkey' : self.hostkey_path })
pathutil.make_path_rw_private(self.keystore_path)
# then adjust the web config to point to these keys
webconfpath = pathutil.pathjoin(self.webdir, 'nimbusweb.conf')
webconf = ConfigParser.SafeConfigParser()
if not webconf.read(webconfpath):
raise IncompatibleEnvironment(
"nimbus web config does not exist: %s" % webconfpath)
relpath = pathutil.relpath
webconf.set('nimbusweb', 'ssl.cert',
relpath(self.hostcert_path, self.webdir))
webconf.set('nimbusweb', 'ssl.key',
relpath(self.hostkey_path, self.webdir))
webconf.set('nimbusweb', CONFIG_KEY_CA_DIR, relpath(self.cadir, self.webdir))
webconffile = open(webconfpath, 'wb')
try:
webconf.write(webconffile)
finally:
webconffile.close()
# then setup GT container
gtcontainer.adjust_hostname(hostname, self.webdir, self.gtdir, log)
gtcontainer.adjust_secdesc_path(self.webdir, self.gtdir, log)
gtcontainer.adjust_host_cert(self.hostcert_path, self.hostkey_path,
self.webdir, self.gtdir, log)
gtcontainer.adjust_gridmap_file(self.gridmap_path, self.webdir,
self.gtdir, log)
# and context broker
gtcontainer.adjust_broker_config(ca_cert, ca_key, self.keystore_path,
password, self.webdir, self.gtdir, log)
# run the web newconf script, if enabled
if self.config.getboolean(CONFIGSECTION, 'web.enabled'):
ret = os.system(os.path.join(self.webdir, 'sbin/new-conf.sh'))
configured = pathutil.pathjoin(self.webdir, ".nimbusconfigured")
if not os.path.isfile(configured):
open(configured, "a")
# write an enviroment file
self.write_env_file()
# and db properties file
self.write_db_props()
# and cumulus properties file
self.write_cumulus_props()
self.write_cumulus_init()
def generate_password(length=25):
okchars = string.letters + string.digits + "!@^_&*+-"
return ''.join(Random().sample(okchars, length))
def import_db(setup, old_db_path):
derbyrun_path = os.path.join(setup.gtdir, 'lib/derbyrun.jar')
if not os.path.exists(derbyrun_path):
raise IncompatibleEnvironment("derbyrun.jar does not exist: %s" %
derbyrun_path)
ij_path = "java -jar %s ij" % derbyrun_path
new_db_path = os.path.join(setup.gtdir, 'var/nimbus/WorkspaceAccountingDB')
if not os.path.isdir(new_db_path):
raise IncompatibleEnvironment("Could not find current Accounting DB: %s"
% new_db_path)
if not os.path.isdir(old_db_path):
raise InvalidInput("Specified DB does not exist or is not a directory")
if derbyutil.update_db(ij_path, old_db_path, new_db_path) == 1:
raise UnexpectedError("Failed to update Accounting DB")
def copy_accounting_db(setup, old_db_path):
# The one we're about to replace
new_db_path = os.path.join(setup.gtdir, 'var/nimbus/WorkspaceAccountingDB')
if not os.path.isdir(new_db_path):
raise IncompatibleEnvironment("Could not find current Accounting DB: %s"
% new_db_path)
# back this up, just in case this script is used in an odd way
backup_db_path = os.path.join(setup.gtdir, 'var/nimbus/.prev-accountingDB')
print "\nBacking up accounting DB to: %s ... " % backup_db_path
shutil.move(new_db_path, backup_db_path)
print " - Done."
print "\nImporting accounting DB to: %s ... " % new_db_path
shutil.copytree(old_db_path, new_db_path)
print " - Done."
def copy_cumulus_db(setup, old_db_path):
# The one we're about to replace
new_db_path = setup.resolve_path("cumulus/etc/authz.db")
if not os.path.exists(new_db_path):
raise IncompatibleEnvironment("Could not find Cumulus DB to replace: %s"
% new_db_path)
# back this up, just in case this script is used in an odd way
backup_db_path = setup.resolve_path("cumulus/etc/.prev-authz.db")
print "Backing up Cumulus DB to: %s ... " % backup_db_path
shutil.move(new_db_path, backup_db_path)
print " - Done."
print "\nImporting Cumulus DB to: %s ... " % new_db_path
shutil.copy(old_db_path, new_db_path)
print " - Done."
def get_oldsetup(config):
old_nimbus_home = os.getenv("PREVIOUS_NIMBUS_HOME_VALIDATED")
if not old_nimbus_home:
raise IncompatibleEnvironment("Could not find the old Nimbus home environment variable: PREVIOUS_NIMBUS_HOME_VALIDATED")
# Represent the old config in an object:
oldsetup = NimbusSetup(old_nimbus_home, config)
return oldsetup
def import_relatives(setup, config, oldversion):
"""Look for conf paths from a previous config that are relative.
The old nimbus home (where the relative paths are taken from) must be
provided via environment variable currently.
"""
oldsetup = get_oldsetup(config)
acknowledge = "\nAcknowledge (type any key) "
print "CA directory configuration: %s" % setup.cadir
if oldsetup.is_config_relative(CONFIG_KEY_CA_DIR):
print "Importing previous CA directory: %s ... " % oldsetup.cadir
if os.path.isdir(setup.cadir):
raise IncompatibleEnvironment("Directory exists already: %s" % setup.cadir)
shutil.copytree(oldsetup.cadir, setup.cadir, symlinks=True)
print " - Done."
else:
print >>sys.stderr, "* Did not import CA directory, it was an absolute path configuration which is a customization: %s" % oldsetup.cadir
# re-running configure takes care of the X509_CERT_DIR in the
# $NIMBUS_HOME/libexec/environment.sh file.
print "\nTrusted certificate configuration: %s" % setup.trustedcertsdir
if oldsetup.is_config_relative(CONFIG_KEY_TRUSTED_CERTS):
print "Checking trusted certificates exists: %s" % setup.trustedcertsdir
if not os.path.isdir(setup.trustedcertsdir):
print "Does not exist as part of the CA directory, importing: %s ..." % oldsetup.trustedcertsdir
shutil.copytree(oldsetup.trustedcertsdir, setup.trustedcertsdir, symlinks=True)
print " - Done."
else:
print >>sys.stderr, "* Did not import trusted certificate directory, it was an absolute path configuration which is a customization: %s" % oldsetup.trustedcertsdir
print "\nHost certificate configuration: %s" % setup.hostcert_path
if oldsetup.is_config_relative(CONFIG_KEY_HOSTCERT):
print "Importing previous host certificate: %s ... " % oldsetup.hostcert_path
if os.path.exists(setup.hostcert_path):
raise IncompatibleEnvironment("File exists already: %s" % setup.hostcert_path)
shutil.copy(oldsetup.hostcert_path, setup.hostcert_path)
print " - Done."
else:
print >>sys.stderr, "* Did not import host certificate, it was an absolute path configuration which is a customization: %s" % oldsetup.hostcert_path
print "\nHost key configuration: %s" % setup.hostkey_path
if oldsetup.is_config_relative(CONFIG_KEY_HOSTKEY):
print "Importing previous host key: %s ... " % oldsetup.hostkey_path
if os.path.exists(setup.hostkey_path):
raise IncompatibleEnvironment("File exists already: %s" % setup.hostkey_path)
shutil.copy(oldsetup.hostkey_path, setup.hostkey_path)
print " - Done."
else:
print >>sys.stderr, "* Did not import host key, it was an absolute path configuration which is a customization: %s" % oldsetup.hostkey_path
print "\nKeystore configuration: %s" % setup.keystore_path
if oldsetup.is_config_relative(CONFIG_KEY_KEYSTORE):
print "Importing previous keystore: %s ... " % oldsetup.keystore_path
if os.path.exists(setup.keystore_path):
raise IncompatibleEnvironment("File exists already: %s" % setup.keystore_path)
shutil.copy(oldsetup.keystore_path, setup.keystore_path)
print " - Done."
else:
print >>sys.stderr, "* Did not import keystore, it was an absolute path configuration which is a customization: %s" % oldsetup.keystore_path
print "\nGridmap configuration: %s" % setup.gridmap_path
if oldsetup.is_config_relative(CONFIG_KEY_GRIDMAP):
print "Importing previous ACL (gridmap): %s ... " % oldsetup.gridmap_path
shutil.copy(oldsetup.gridmap_path, setup.gridmap_path)
print " - Done."
else:
print >>sys.stderr, "* Did not import ACL (gridmap), it was an absolute path configuration which is a customization: %s" % oldsetup.gridmap_path
def import_authz(setup, config, oldversion):
oldsetup = get_oldsetup(config)
ws_dir = "services/etc/nimbus/workspace-service"
group_authz_dir = setup.resolve_path("%s/group-authz" % ws_dir)
group_authz_backup_dir = setup.resolve_path("%s/.prev-group-authz" % ws_dir)
if not os.path.isdir(group_authz_dir):
raise IncompatibleEnvironment("Not a directory: %s" % group_authz_dir)
old_group_authz = oldsetup.resolve_path("%s/group-authz" % ws_dir)
if not os.path.isdir(old_group_authz):
raise IncompatibleEnvironment("Not a directory: %s" % old_group_authz)
# back this up, just in case this script is used in an odd way
print "\nBacking up group-authz to: %s ... " % group_authz_backup_dir
shutil.move(group_authz_dir, group_authz_backup_dir)
print " - Done."
print "\nImporting previous group-authz ..."
shutil.copytree(old_group_authz, group_authz_dir)
print " - Done."
def import_net(setup, config, oldversion):
oldsetup = get_oldsetup(config)
ws_dir = "services/etc/nimbus/workspace-service"
netpool_dir = setup.resolve_path("%s/network-pools" % ws_dir)
netpool_backup_dir = setup.resolve_path("%s/.prev-network-pools" % ws_dir)
if not os.path.isdir(netpool_dir):
raise IncompatibleEnvironment("Not a directory: %s" % netpool_dir)
old_netpool_dir = oldsetup.resolve_path("%s/network-pools" % ws_dir)
if not os.path.isdir(old_netpool_dir):
raise IncompatibleEnvironment("Not a directory: %s" % old_netpool_dir)
# back this up, just in case this script is used in an odd way
print "\nBacking up old_netpool_dir to: %s ... " % netpool_backup_dir
shutil.move(netpool_dir, netpool_backup_dir)
print " - Done."
print "\nImporting previous network-pools to: %s ..." % netpool_dir
shutil.copytree(old_netpool_dir, netpool_dir)
print " - Done."
def import_accounting(setup, config, oldversion):
oldsetup = get_oldsetup(config)
events_txt_relpath = "services/var/nimbus/accounting-events.txt"
old_events_txt = oldsetup.resolve_path(events_txt_relpath)
events_txt = setup.resolve_path(events_txt_relpath)
print "\nImporting accounting events log: %s ... " % events_txt
if not os.path.exists(old_events_txt):
raise IncompatibleEnvironment("File does not exist: %s" % old_events_txt)
shutil.copy(old_events_txt, events_txt)
print " - Done."
events_db_relpath = "services/var/nimbus/WorkspaceAccountingDB/"
old_db_path = oldsetup.resolve_path(events_db_relpath)
if not os.path.isdir(old_db_path):
raise IncompatibleEnvironment("Not a directory: %s" % old_db_path)
copy_accounting_db(setup, old_db_path)
def import_cumulus(setup, config, oldversion):
oldsetup = get_oldsetup(config)
old_db_path = oldsetup.resolve_path("cumulus/etc/authz.db")
if not os.path.exists(old_db_path):
raise IncompatibleEnvironment("Not a file: %s" % old_db_path)
copy_cumulus_db(setup, old_db_path)
def import_webapp(setup, config, oldversion):
oldsetup = get_oldsetup(config)
webconf_relpath = "web/nimbusweb.conf"
old_webconf = oldsetup.resolve_path(webconf_relpath)
webconf = setup.resolve_path(webconf_relpath)
print "\nImporting webapp configuration to: %s ... " % webconf
if not os.path.exists(old_webconf):
raise IncompatibleEnvironment("File does not exist: %s" % old_webconf)
shutil.copy(old_webconf, webconf)
print " - Done."
def _get_noncomment_lines(fullpath):
"""Return a list of lines from this file that are not comments and not
empty lines"""
f = open(fullpath, 'r')
all_lines = f.readlines()
f.close()
lines = []
for line in all_lines:
stripped = line.strip()
if len(stripped) == 0:
continue
if stripped.startswith("#"):
continue
lines.append(stripped)
return lines
def _one_vmm_file(directory, pool, nodestool):
topr = "\nImporting VMMs from '%s'" % pool
dashes = "-" * (len(topr) - 1)
print topr
print dashes + "\n"
fullpath = os.path.join(directory, pool)
lines = _get_noncomment_lines(fullpath)
for line in lines:
parts = line.split(" ")
if len(parts) < 2:
print " **** Invalid Pool Entry: '%s'" % line
continue
vmm = parts[0]
ram = parts[1]
net = None
if len(parts) > 2:
net = parts[2]
cmd = "%s --add %s --memory %s" % (nodestool, vmm, ram)
if net:
cmd += " --networks '%s'" % net
cmd += " --pool %s" % pool
(exitcode, stdout, stderr) = runutil.runexe(cmd, log, killtime=0)
if exitcode:
err = " **** Problem importing VMM '%s', command was '%s'\n\n" % (vmm, cmd)
err += " %s\n\n" % stdout
err += " %s\n" % stderr
raise UnexpectedError(err)
else:
print stdout
def import_vmms(setup, old_vmmdir):
nodestool = setup.resolve_path("bin/nimbus-nodes")
if not os.path.isdir(old_vmmdir):
raise IncompatibleEnvironment("Directory does not exist: %s" % old_vmmdir)
files = os.listdir(old_vmmdir)
for pool in files:
fullpath = os.path.join(old_vmmdir, pool)
if pool.startswith("."):
print " - Ignoring '%s'" % fullpath
elif os.path.isdir(fullpath):
print " - Ignoring directory '%s'" % fullpath
else:
_one_vmm_file(old_vmmdir, pool, nodestool)
print "Done."
def getoldversion(config):
oldsetup = get_oldsetup(config)
version_tool = oldsetup.resolve_path("bin/nimbus-version")
if not os.path.exists(version_tool):
raise IncompatibleEnvironment("nimbus-version does not exist in the old installation, it must be too old to import: %s" % version_tool)
cmd = "%s --majorminor" % (version_tool)
(exitcode, stdout, stderr) = runutil.runexe(cmd, log, killtime=0)
if exitcode:
err = " **** Problem getting version, command was '%s'\n\n" % cmd
err += " %s\n\n" % stdout
err += " %s\n" % stderr
raise UnexpectedError(err)
return stdout.strip()
def main(argv=None):
if os.name != 'posix':
print >>sys.stderr, "\nERROR: Only runs on POSIX systems."
return 3
if sys.version_info < (2,4):
print >>sys.stderr, "\nERROR: Your system must have Python version 2.4 or later. "
print >>sys.stderr, 'Detected version: "'+sys.version+'"'
return 4
parser = parsersetup()
if argv:
(opts, args) = parser.parse_args(argv[1:])
else:
(opts, args) = parser.parse_args()
global log
log = None
try:
configureLogging(opts.debug and logging.DEBUG or logging.INFO)
validateargs(opts)
basedir = opts.basedir
log.debug("base directory: %s" % basedir)
config_state_path = os.path.join(basedir, CONFIG_STATE_PATH)
paths = [config_state_path]
if opts.configpath:
paths.append(opts.configpath)
config = getconfig(filepath=paths)
#Some command line options are folded into the config object
fold_opts_to_config(opts, config)
setup = NimbusSetup(basedir, config)
setup.validate_environment()
if opts.autoconfig:
cmd = os.path.join(setup.gtdir,
'share/nimbus-autoconfig/autoconfig.sh')
if not (os.path.exists(cmd) and os.access(cmd, os.X_OK)):
print >>sys.stderr, "\nERROR: autoconfig script not found or not executable: " + cmd
return 1
os.system(cmd)
return 0
elif opts.importdb:
import_db(setup, opts.importdb)
return 0
elif opts.importprev:
oldversion = getoldversion(config)
print "Old Nimbus version: %s\n" % oldversion
import_relatives(setup, config, oldversion)
import_authz(setup, config, oldversion)
import_net(setup, config, oldversion)
import_accounting(setup, config, oldversion)
import_webapp(setup, config, oldversion)
return 0
elif opts.importvmms:
import_vmms(setup, opts.importvmms)
print ""
return 0
elif opts.importcumulusdb:
oldversion = getoldversion(config)
print "Old Nimbus version: %s\n" % oldversion
import_cumulus(setup, config, oldversion)
print ""
return 0