-
Notifications
You must be signed in to change notification settings - Fork 2
/
igorSetup.py
executable file
·453 lines (408 loc) · 18.2 KB
/
igorSetup.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
#!/usr/bin/env python3
# Enable coverage if installed and enabled through COVERAGE_PROCESS_START environment var
try:
import coverage
coverage.process_startup()
except ImportError:
pass
import sys
import igor
import os
import os.path
import shutil
import getpass
import tempfile
import argparse
import subprocess
import tempfile
USAGE="""
Usage: %(prog)s [options] command [command-args]
Initialize or modify igor database.
Note: use only on host where igorServer is hosted, and not when it is running.
"""
OPENSSL_COMMAND='openssl req -config "%s" -new -x509 -sha256 -newkey rsa:2048 -nodes -keyout "%s" -days 365 -out "%s"'
OPENSSL_CONF="""
[ req ]
default_bits = 2048
default_keyfile = server-key.pem
req_extensions = req_ext
x509_extensions = x509_ext
string_mask = utf8only
prompt = no
distinguished_name = subject
[ subject ]
%s
# Section x509_ext is used when generating a self-signed certificate. I.e., openssl req -x509 ...
[ x509_ext ]
##subjectKeyIdentifier = hash
##authorityKeyIdentifier = keyid,issuer
# You only need digitalSignature below. *If* you don't allow
# RSA Key transport (i.e., you use ephemeral cipher suites), then
# omit keyEncipherment because that's key transport.
##basicConstraints = CA:FALSE
##keyUsage = digitalSignature, keyEncipherment
subjectAltName = @alternate_names
##nsComment = "OpenSSL Generated Certificate"
# RFC 5280, Section 4.2.1.12 makes EKU optional
# CA/Browser Baseline Requirements, Appendix (B)(3)(G) makes me confused
# In either case, you probably only need serverAuth.
# extendedKeyUsage = serverAuth, clientAuth
# Section req_ext is used when generating a certificate signing request. I.e., openssl req ...
[ req_ext ]
subjectKeyIdentifier = hash
basicConstraints = CA:FALSE
keyUsage = digitalSignature, keyEncipherment
subjectAltName = @alternate_names
nsComment = "OpenSSL Generated Certificate"
# RFC 5280, Section 4.2.1.12 makes EKU optional
# CA/Browser Baseline Requirements, Appendix (B)(3)(G) makes me confused
# In either case, you probably only need serverAuth.
# extendedKeyUsage = serverAuth, clientAuth
[ alternate_names ]
%s
"""
class IgorSetup:
def __init__(self, database=None, progname='igorSetup'):
self.progname = progname
# Find username even when sudoed
self.username = os.environ.get("SUDO_USER", getpass.getuser())
# Igor package source directory
if database:
self.database = database
elif 'IGORSERVER_DIR' in os.environ:
self.database = os.environ['IGORSERVER_DIR']
else:
self.database = os.path.join(os.path.expanduser('~'+self.username), '.igor')
self.igorDir = os.path.abspath(os.path.dirname(igor.__file__))
# Default database directory
self.plugindir = os.path.join(self.database, 'plugins')
self.stdplugindir = os.path.join(self.database, 'std-plugins')
self.runcmds = []
def main(self, cmd=None, args=None):
if not args:
args = ()
self.runcmds = []
if not cmd or cmd == 'help':
ok = self.cmd_help()
elif cmd == 'initialize':
ok = self.cmd_initialize()
elif cmd == 'sandbox':
ok = self.cmd_sandbox()
else:
# For the rest of the commands the Igor database should already exist.
if not os.path.exists(self.database):
print("%s: No Igor database at %s" % (self.progname, self.database), file=sys.stderr)
return False
if not hasattr(self, 'cmd_' + cmd):
print('%s: Unknown command "%s". Use help for help.' % (self.progname, cmd), file=sys.stderr)
return False
handler = getattr(self, 'cmd_' + cmd)
ok = handler(*args)
if not ok:
return False
return True
def postprocess(self, run=False, verbose=False, subprocessArgs={}):
if self.runcmds:
if run:
for cmd in self.runcmds:
if verbose:
print('+', cmd, file=sys.stderr)
subprocess.check_call(cmd, shell=True, **subprocessArgs)
else:
print('# Run the following commands:')
print('(')
for cmd in self.runcmds: print('\t', cmd)
print(')')
self.runcmds = []
def cmd_help(self):
"""help - this message"""
print(USAGE % dict(prog=self.progname), file=sys.stderr)
for name in dir(self):
if not name.startswith('cmd_'): continue
handler = getattr(self, name)
print(handler.__doc__)
return True
def cmd_initialize(self):
"""initialize - create empty igor database"""
src = os.path.join(self.igorDir, 'igorDatabase.empty')
if os.path.exists(self.database):
print('%s: %s already exists!' % (self.progname, self.database), file=sys.stderr)
return False
shutil.copytree(src, self.database)
os.symlink(os.path.join(self.igorDir, 'std-plugins'), os.path.join(self.database, 'std-plugins'))
return True
def cmd_sandbox(self):
"""sandbox - Initialize and run Igor (on port 19333) in a fresh minimal database"""
igorDir = tempfile.mkdtemp(prefix="igor-")
os.rmdir(igorDir)
igorPort = 19333
os.putenv("IGORSERVER_DIR", igorDir)
self.database = igorDir
os.putenv("IGORSERVER_PORT", str(igorPort))
print(f"export IGORSERVER_DIR=\"{igorDir}\"")
print(f"export IGORSERVER_PORT={igorPort}")
# Initialize database
ok = self.cmd_initialize()
if not ok: return ok
# Add standard plugins
ok = self.cmd_addstd("systemHealth","ca","user","device","actions","editData")
if not ok: return ok
# Run igor interactively
try:
subprocess.run(["igorServer"])
except KeyboardInterrupt:
print(f"\nTo run Igor again with the same database:\n")
print(f"export IGORSERVER_DIR=\"{igorDir}\"")
print(f"export IGORSERVER_PORT={igorPort}")
print(f"igorServer")
return True
def cmd_list(self):
"""list - show all installed plugins"""
names = os.listdir(self.plugindir)
names.sort()
for name in names:
if name[0] == '.' or name == 'readme.txt': continue
filename = os.path.join(self.plugindir, name)
if not os.path.isdir(filename):
print(filename, '(error: does not exist, or not a directory)')
elif os.path.islink(filename):
print(filename, '(symlinked)')
else:
print(filename)
return True
def cmd_add(self, *pathnames):
"""add pathname [...] - add plugin (copy) from given pathname"""
if not pathnames:
print("%s: add requires a pathname" % self.progname, file=sys.stderr)
return False
for pluginpath in pathnames:
basedir, pluginname = os.path.split(pluginpath)
if not pluginname:
basedir, pluginname = os.path.split(pluginpath)
ok = self._installplugin(self.database, pluginpath, pluginname, shutil.cptree)
if not ok:
return False
return True
def cmd_addstd(self, *pluginnames):
"""addstd name[=srcname] [...] - add standard plugin srcname (linked) with given name"""
if not pluginnames:
print("%s: addstd requires a plugin name" % self.progname, file=sys.stderr)
return False
for pluginname in pluginnames:
if type(pluginname) == type(()):
pluginname, pluginsrcname = pluginname
elif '=' in pluginname:
pluginname = tuple(pluginname.split('='))
pluginname, pluginsrcname = pluginname
else:
pluginsrcname = pluginname
pluginsrcpath = os.path.join('..', 'std-plugins', pluginsrcname)
ok = self._installplugin(self.database, pluginsrcpath, pluginname, os.symlink)
if not ok:
return False
return True
def cmd_updatestd(self):
"""updatestd - update all standard plugins to newest version (for igor < 0.85)"""
names = os.listdir(self.plugindir)
names.sort()
for name in names:
if name[0] == '.' or name == 'readme.txt': continue
pluginpath = os.path.join(self.plugindir, name)
if os.path.islink(pluginpath):
print('Updating', pluginpath)
os.unlink(pluginpath)
pluginsrcpath = os.path.join('..', 'std-plugins', name)
ok = self._installplugin(self.database, pluginsrcpath, name, os.symlink)
if not ok: return False
return True
def cmd_remove(self, *pluginnames):
"""remove name [...] - remove plugin"""
for pluginname in pluginnames:
pluginpath = os.path.join(self.plugindir, pluginname)
if os.path.islink(pluginpath):
os.unlink(pluginpath)
elif os.path.isdir(pluginpath):
shutil.rmtree(pluginpath)
else:
print("%s: not symlink or directory: %s" % (self.progname, pluginpath), file=sys.stderr)
return False
return True
def cmd_liststd(self):
"""liststd - list all available standard plugins"""
stdplugindir = os.path.join(self.database, 'std-plugins')
names = os.listdir(stdplugindir)
names.sort()
for name in names:
if name[0] == '.' or name == 'readme.txt': continue
print(name)
return True
def cmd_certificate(self, *hostnames):
"""certificate hostname [...] - create https certificate for Igor using Igor as CA"""
if not hostnames:
print("%s: certificate requires all hostnames for igor, for example igor.local localhost 127.0.0.1 ::1" % self.progname, file=sys.stderr)
return False
import igorCA
caName = self.progname + ': ' + 'igorCA'
ca = igorCA.IgorCA(caName, database=self.database)
msg = ca.do_status()
if msg:
# CA Not initialized yet.
ok = ca.cmd_initialize()
if not ok:
return False
ok = ca.cmd_self(hostnames)
return ok
def cmd_certificateSelfsigned(self, subject, *hostnames):
"""certificateSelfSigned subject hostname [...] - create self-signed https certificate for Igor (deprecated)"""
if not len(hostnames):
print("%s: certificateSelfSigned requires DN and all hostnames for igor, for example /C=NL/O=igor/CN=igor.local igor.local localhost 127.0.0.1 ::1" % self.progname, file=sys.stderr)
return False
altnames = ["DNS.%d = %s" % (i_n[0]+1, i_n[1]) for i_n in zip(list(range(len(hostnames))), hostnames)]
altnames = '\n'.join(altnames)
subject = subject.replace('/','\n')
confData = OPENSSL_CONF % (subject, altnames)
confFilename = os.path.join(self.database, 'igor.sslconf')
keyFilename = os.path.join(self.database, 'igor.key')
certFilename = os.path.join(self.database, 'igor.crt')
with open(confFilename, 'w') as fp:
fp.write(confData)
sslCommand = OPENSSL_COMMAND % (confFilename, keyFilename, certFilename)
self.runcmds += [sslCommand]
return True
def cmd_runatboot(self):
"""runatboot - make igorServer run at system boot (Linux or OSX, requires sudo permission)"""
return self._runat('runatboot')
def cmd_runatlogin(self):
"""runatlogin - make igorServer run at user login (OSX only)"""
return self._runat('runatlogin')
def _runat(self, when):
args = dict(
user=self.username,
igorDir=self.igorDir,
database=self.database
)
if sys.platform == 'darwin' and when == 'runatboot':
template = os.path.join(self.igorDir, 'bootScripts', 'nl.cwi.dis.igor.plist')
dest = '/Library/LaunchDaemons/nl.cwi.dis.igor.plist'
self.runcmds += [
"sudo launchctl load %s" % dest,
]
elif sys.platform == 'darwin' and when == 'runatlogin':
template = os.path.join(self.igorDir, 'bootScripts', 'nl.cwi.dis.igor.plist')
dest = os.path.join(os.path.expanduser('~'), 'Library/LaunchAgents/nl.cwi.dis.igor.plist')
self.runcmds += [
"launchctl load %s" % dest,
]
elif sys.platform in ('linux','linux2') and when == 'runatboot':
template = os.path.join(self.igorDir, 'bootScripts', 'initscript-igor')
dest = '/etc/init.d/igor'
self.runcmds += [
"sudo update-rc.d igor defaults",
"sudo service igor start"
]
else:
print("%s: don't know how to enable Igor %s for platform %s" % (self.progname, when, sys.platform), file=sys.stderr)
return False
if os.path.exists(dest):
print("%s: already exists: %s" % (self.progname, dest), file=sys.stderr)
return False
templateData = open(template).read()
bootData = templateData % args
open(dest, 'w').write(bootData)
if sys.platform in ('linux', 'linux2'):
os.chmod(dest, 0o755)
return True
def cmd_start(self):
"""start - start service (using normal OSX or Linux commands)"""
return self._startstop('start')
def cmd_stop(self):
"""stop - stop service (using normal OSX or Linux commands)"""
return self._startstop('stop')
def cmd_rebuild(self):
"""rebuild - stop, rebuild and start the service (must be run in source directory)"""
return self._startstop('rebuild')
def cmd_edit(self):
"""edit - stop, edit the database and restart the service"""
return self._startstop('edit')
def cmd_rebuildedit(self):
"""rebuildedit - stop, edit database, rebuild and start the service (must be run in source directory)"""
return self._startstop('rebuildedit')
def _startstop(self, when):
if sys.platform == 'darwin':
daemonFile = '/Library/LaunchDaemons/nl.cwi.dis.igor.plist'
if not os.path.exists(daemonFile):
daemonFile = os.path.join(os.path.expanduser('~'), 'Library/LaunchAgents/nl.cwi.dis.igor.plist')
elif sys.platform in ('linux', 'linux2'):
daemonFile = '/etc/init.d/igor'
else:
print("%s: don't know about daemon mode on platform %s" % (self.progname, sys.platform), file=sys.stderr)
return False
if not os.path.exists(daemonFile):
print("%s: it seems igor is not configured for runatboot or runatlogin" % self.progname, file=sys.stderr)
return False
if when in ('stop', 'rebuild', 'edit', 'rebuildedit'):
self.runcmds += ["igorControl save"]
if sys.platform == 'darwin':
self.runcmds += ["sudo launchctl unload %s" % daemonFile]
else:
self.runcmds += ["sudo service igor stop"]
if when in ('edit', 'rebuildedit'):
xmlDatabase = os.path.join(self.database, 'database.xml')
self.runcmds += ["$EDITOR %s" % xmlDatabase]
if when in ('rebuild', 'rebuildedit'):
if not os.path.exists("setup.py"):
print("%s: use 'rebuild' option only in an Igor source directory" % self.progname, file=sys.stderr)
self.runcmds += [
"%s setup.py build" % sys.executable,
"sudo %s setup.py install" % sys.executable
]
if when in ('rebuild', 'edit', 'rebuildedit', 'start'):
if sys.platform == 'darwin':
self.runcmds += ["sudo launchctl load %s" % daemonFile]
else:
self.runcmds += ["sudo service igor start"]
return True
def _installplugin(self, database, src, pluginname, cpfunc):
dstdir = os.path.join(database, 'plugins')
dst = os.path.join(dstdir, pluginname)
if os.path.exists(dst):
print("%s: already exists: %s" % (self.progname, dst), file=sys.stderr)
return False
if not os.path.exists(os.path.join(dstdir, src)):
print("%s: does not exist: %s" % (self.progname, src), file=sys.stderr)
return False
cpfunc(src, dst)
# Sometimes (only under travis?) the symlink seems to fail
try:
os.listdir(dst)
except OSError:
print("%s: creation of %s failed" % (self.progname, dst), file=sys.stderr)
return False
xmlfrag = os.path.join(dst, 'database-fragment.xml')
if os.path.exists(xmlfrag):
fp = open(xmlfrag)
fragData = fp.read()
fp.close()
fragData = fragData.replace('{plugin}', pluginname)
fragDest = dst + '.xml'
fp = open(fragDest, 'w')
fp.write(fragData)
fp.close()
print("%s: igor will install %s on the next restart" % (self.progname, fragDest), file=sys.stderr)
return True
def argumentParser():
parser = argparse.ArgumentParser(usage=USAGE)
parser.add_argument("-d", "--database", metavar="DIR", help="Database and scripts are stored in DIR (default: ~/.igor, environment IGORSERVER_DIR)")
parser.add_argument("-r", "--run", action="store_true", help="Run any needed shell commands (default is to print them only)")
parser.add_argument("action", help="Action to perform: help, initialize, ...", default="help")
parser.add_argument("arguments", help="Arguments to the action", nargs="*")
return parser
def main():
parser = argumentParser()
args = parser.parse_args()
m = IgorSetup(database=args.database, progname=sys.argv[0])
if not m.main(args.action, args.arguments):
sys.exit(1)
m.postprocess(args.run, verbose=True)
if __name__ == '__main__':
main()