This repository has been archived by the owner on Apr 20, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
minislate
executable file
·593 lines (523 loc) · 22 KB
/
minislate
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
#!/usr/bin/env python
import pathlib
import shutil
import time
from typing import Optional, Dict, List, Any
from random import randint
from enum import Enum
import subprocess
import argparse
import sys
import os
class ProviderType(Enum):
"""
Enum class to define virtualization provider types
"""
DOCKER = 0
PODMAN = 1
class VirtProvider:
"""
Class to handle virtualization provider usage
"""
def __init__(self):
"""
Initialize object
"""
self.provider_type, self.provider_compose_path, self.provider_path = self.get_provider()
@staticmethod
def get_provider() -> (ProviderType, pathlib.Path, pathlib.Path):
"""
Get virtualization provider and binary location
:return: tuple with provider type and path to provider binary
"""
if shutil.which('docker-compose'):
return ProviderType.DOCKER, \
pathlib.Path(shutil.which('docker-compose')), \
pathlib.Path(shutil.which('docker'))
elif shutil.which('podman-compose'):
return ProviderType.PODMAN, \
pathlib.Path(shutil.which('podman-compose')), \
pathlib.Path(shutil.which('podman'))
else:
raise Exception("Can't get virtualization provider type")
def compose(self, args) -> Optional[str]:
"""
Run a given compose command
:param args: arguments to compose command
:return: Output of compose command or None if any error occurred
"""
try:
# run returns bytes or str and that confuses type checking
# print([str(self.provider_compose_path)] + args)
return subprocess.run([str(self.provider_compose_path)] + args, # type: ignore
stdout=subprocess.PIPE,
check=True,
text=True).stdout
except subprocess.CalledProcessError:
sys.stderr.write(f"Can't run {self.provider_compose_path} with given args\n")
return None
def run(self, args) -> Optional[str]:
"""
Run podman or docker build with given arguments
:param args: args to pass to podman or docker
:return: Output of compose command or None if any error occurred
"""
try:
# print([self.provider_path] + args)
return subprocess.run([self.provider_path] + args, # type: ignore
stdout=subprocess.PIPE,
check=True,
text=True).stdout
except subprocess.CalledProcessError:
sys.stderr.write(f"Can't run {self.provider_path} with given args\n")
return None
def interactive(self, container: str) -> None:
"""
Run inside specified container interactively
:param container: container name (e.g. slate)
:return: None
"""
if self.provider_type == ProviderType.DOCKER:
subprocess.call([self.provider_compose_path, 'exec', container, '/bin/sh'])
elif self.provider_type == ProviderType.PODMAN:
container_info = self.get_status()
container_id = [x['CONTAINER_ID'] for x in container_info if container in x['IMAGE']]
if len(container_id) == 0:
sys.stderr.write(f"Can't find specified container: {container}\n")
sys.exit(1)
subprocess.call([self.provider_path, 'exec', '-it', container_id[0], '/bin/sh'])
def exec(self, container: str, args: List[Any]) -> int:
"""
Run a command inside specified container
:param container: container name (e.g. slate)
:param args: arguments to pass to command in container
:return: None
"""
if self.provider_type == ProviderType.DOCKER:
# print([self.provider_compose_path, 'exec', container] + args)
subprocess.call([self.provider_compose_path, 'exec', container] + args)
elif self.provider_type == ProviderType.PODMAN:
container_info = self.get_status()
container_id = [x['CONTAINER_ID'] for x in container_info if container in x['IMAGE']]
if len(container_id) == 0:
sys.stderr.write(f"Can't find specified container: {container}\n")
sys.exit(1)
return subprocess.call([self.provider_path, 'exec', container_id[0]] + args)
@staticmethod
def split_fields_podman(line: str, header_line: str) -> Optional[Dict[str, str]]:
"""
Split output from ps command output into list
:param line: line of output from docker or podman ps
:param header_line: line with column names from ps output
:return: list with line split into components
"""
field_indices = []
if line == header_line:
return None
# get the indices associated with each field
field_names = ['CONTAINER ID', 'IMAGE', 'COMMAND', 'CREATED', 'STATUS', 'PORTS', 'NAMES']
for col in field_names:
cur_idx = header_line.find(col)
if cur_idx == -1:
return None
field_indices.append(cur_idx)
field_indices.append(-1)
if len(line) < field_indices[-2]:
# invalid line since it's length is less than we expect
return None
fields = {}
field_names[0] = 'CONTAINER_ID'
# use the field indices to process the input line
for index in range(len(field_names)):
field = line[field_indices[index]:field_indices[index + 1]].strip()
fields[field_names[index]] = field
return fields
@staticmethod
def split_fields_docker(line: str, header_line: str) -> Optional[Dict[str, str]]:
"""
Split output from ps command output into list
:param line: line of output from docker or podman ps
:param header_line: line with column names from ps output
:return: dict with line split into components
"""
if line == header_line:
return None
# docker-compose centers some field names but not others
# so assume fields are separated by a double empty space
fields = [x.strip() for x in line.split(' ') if x != '']
if len(fields) != 4:
return None
fields = {'CONTAINER_ID': fields[0],
'COMMAND': fields[1],
'STATUS': fields[2],
'PORTS': fields[3]}
return fields
def get_status(self) -> List[Dict[str, str]]:
"""
Return list with information on containers that minislate has created
:return: List with Dictionary containing container info
"""
output = self.compose(['ps'])
if not output:
return []
if self.provider_type == ProviderType.PODMAN:
header_line = [x for x in output.split("\n") if x.startswith('CONTAINER')][0]
container_info = [self.split_fields_podman(x, header_line) for x in output.split("\n")]
elif self.provider_type == ProviderType.DOCKER:
header_line = [x for x in output.split("\n") if 'Name' in x][0]
container_info = [self.split_fields_docker(x, header_line) for x in output.split("\n")]
else:
sys.stderr.write(f"Provider {self.provider_type} not supported\n")
sys.exit(1)
return [x for x in container_info if x] # filter out entries with None
def exception_handler(exception_type, exception, traceback):
print(exception)
def init_check(initerr='MiniSLATE is not initialized. Run: `./minislate init`') -> bool:
if not os.path.isfile('docker-compose.yml'):
raise EnvironmentError(initerr)
return True
def ready_check(provider: VirtProvider, ready_error: str = None) -> None:
"""
Check to make sure all slate containers are up and ready
:param ready_error: error message to print
:param provider: Provider object with information on system to use
:return:
"""
if not ready_error:
ready_error = 'MiniSLATE has non-ready containers. Is the environment paused?'
output = provider.get_status()
non_ready = [x for x in output if not x['STATUS'].lower().startswith('up')]
if len(non_ready) != 0:
raise EnvironmentError(ready_error)
def kill_test(provider: VirtProvider) -> None:
"""
Kill test containers
:param provider: Provider object with information on system to use
:return: None
"""
if provider.provider_type == ProviderType.DOCKER:
provider.compose(['-f', 'docker-compose-test.yml', 'kill', '-s', 'SIGKILL', 'test'])
provider.compose(['-f', 'docker-compose-test.yml', 'down', '-v'])
elif provider.provider_type == ProviderType.PODMAN:
provider.compose(['-f', 'docker-compose-test.yml', 'stop', 'test'])
provider.compose(['-f', 'docker-compose-test.yml', 'down'])
try:
os.remove('docker-compose.yml')
except OSError:
pass
def init_slate(args: argparse.Namespace, provider: VirtProvider) -> None:
"""
Initialize minislate cluster
:param args: parsed arguments
:param provider: Provider object with information on system to use
:return: None
"""
if os.path.isfile('docker-compose.yml'):
raise EnvironmentError('MiniSLATE is already initialized. Run '
'`./minislate destroy && ./minislate init` to reset your environment.')
ports = []
volumes = []
if args.ports:
for item in args.ports:
ports.append(' - ' + item)
if args.volumes:
for item in args.volumes:
if ':' not in item:
item = item + ':/mnt/' + os.path.basename(item)
volumes.append(' - ' + item)
ports = '\n'.join(ports)
volumes = '\n'.join(volumes)
with open('docker-compose.yml.tmpl', 'r') as file:
contents = file.read()
contents = contents.replace('# {PORTS}', ports)
contents = contents.replace('# {VOLUMES}', volumes)
contents = contents.replace('{IMAGE}', dockerimage)
if args.selenium:
contents = contents.replace('tty: true', 'tty: false')
contents = contents.replace('stdin_open: true', 'stdin_open: false')
with open('docker-compose.yml', 'w') as file:
file.write(contents)
file.flush()
os.fsync(file)
if provider.compose(['up', '-d']) is not None:
print("Initializing slate components, this may take a while...")
if provider.compose(['exec', '-T', 'slate', './init.sh']) is not None:
if volumes:
print('\033[1m' + "Volume Mounts:" + '\033[0m' + '\n' + volumes)
print('\n' + '\033[1m' + "DONE! MiniSLATE is now initialized." + '\033[0m')
def pause_minislate(provider: VirtProvider) -> None:
"""
Pause the minislate instance
:param provider: Provider object with information on system to use
:return: None
"""
if provider.provider_type == ProviderType.PODMAN:
provider.run(['pods', 'pause', 'minislate'])
elif provider.provider_type == ProviderType.DOCKER:
container_info = provider.get_status()
container_ids = [x['CONTAINER_ID'] for x in container_info]
for container_id in container_ids:
provider.run(['pause', container_id])
def unpause_minislate(provider: VirtProvider) -> None:
"""
Unpause the minislate instance
:param provider: Provider object with information on system to use
:return: None
"""
container_info = provider.get_status()
paused = [x['CONTAINER_ID'] for x in container_info if x['STATUS'].lower() == 'paused'] # type: ignore # noqa: E501
if len(paused) == 0:
raise EnvironmentError('MiniSLATE is not paused.')
if provider.provider_type == ProviderType.PODMAN:
provider.run(['pods', 'unpause', 'minislate'])
elif provider.provider_type == ProviderType.DOCKER:
for container_id in paused:
provider.run(['unpause', container_id])
def destroy_minislate(args: argparse.Namespace, provider: VirtProvider) -> None:
"""
Destroy the minislate instance
:param args: parsed args
:param provider: Provider object with information on system to use
:return: None
"""
yes = {'yes', 'y', 'ye'}
choice = ''
if not args.confirm:
print("Are you sure you'd like to completely destroy your MiniSLATE environment? (y/N) ",
end='')
choice = input().lower()
if choice in yes or args.confirm:
if provider.provider_type == ProviderType.PODMAN:
provider.run(['pod', 'down', 'minislate'])
sys.stdout.write("Waiting for minislate pod to stop")
time.sleep(10)
provider.run(['pod', 'kill', 'minislate'])
elif provider.provider_type == ProviderType.DOCKER:
provider.compose(['stop', 'kube'])
if args.rmi:
provider.compose(['down', '-v', '--rmi', 'all'])
else:
provider.compose(['down', '-v'])
try:
os.remove('docker-compose.yml')
except OSError:
pass
def build_minislate(args: argparse.Namespace, provider: VirtProvider) -> None:
"""
Build minislate images for use
:param args: parsed arguments
:param provider: Provider object with information on system to use
:return: None
"""
tagoption = "--tag={}".format(dockerimage)
buildargs = "portalbranch={}".format(portalbranch)
print('WARNING Building locally can take more than 15 minutes')
print('It is recommended to use hosted images by running `./minislate init` instead.')
print('Building the slate container...')
provider.run(['build', '--file=slate/Dockerfile', tagoption, '--build-arg', buildargs, './slate'])
print('MiniSLATE build complete run `./minislate init` to initialize locally built image')
def test_minislate(args: argparse.Namespace, provider: VirtProvider) -> None:
"""
Test and validate minislate instanace
:param args: parsed arguments
:param provider: Provider object with information on system to use
:return: None
"""
if args.kill:
kill_test(provider)
else:
if os.path.isfile('docker-compose.yml'):
raise EnvironmentError("Can not run tests on existing environment. "
"Please destroy your environment to run tests.")
provider.compose(['-f', 'docker-compose-test.yml', 'up', '-d', '--build'])
provider.compose(['-f',
'docker-compose-test.yml',
'exec',
'test',
'/minislate/minislate',
'init'])
result = provider.compose(['-f',
'docker-compose-test.yml',
'exec',
'test',
'/minislate/test/test'])
if args.debug:
print('Entering debug mode...')
print('Exiting this shell will destroy the test environment')
provider.compose(['-f', 'docker-compose-test.yml', 'exec', 'test', '/bin/sh'])
kill_test(provider)
sys.exit(result)
def create_arg_parsers() -> argparse.ArgumentParser:
"""
Create and setup argument parsers
:return: argument parser that can be used to parse minislate commands
"""
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(title="commands", dest="command")
init = subparsers.add_parser('init', help='initialize minislate containers')
init.add_argument('-p', '--port',
'--publish',
dest='ports',
action='append',
nargs='?',
metavar='hostPort or hostPort:containerPort',
help='Example: `./minislate init -p 3000`')
init.add_argument('-v', '--volume',
dest='volumes',
action='append',
nargs='?',
metavar='hostDir or hostDir:containerDir',
help='Example: `./minislate init -v ~/workdir`')
init.add_argument('-s', '--selenium', dest='selenium', action='store_true',
help='Runs minislate without TTY, for use with Selenium test infrastructure')
subparsers.add_parser('pause', help='pause minislate containers')
subparsers.add_parser('unpause', help='unpause minislate containers')
destroy = subparsers.add_parser('destroy', help='completely destroy environment')
destroy.add_argument('--rmi', dest='rmi',
action='store_true',
help='Example: `./minislate destroy --rmi`')
destroy.add_argument('-y',
dest='confirm',
action='store_true',
help='Example: `./minislate destroy -y`')
subparsers.add_parser('status', help='view status of minislate containers')
test = subparsers.add_parser('test', help='run test of the minislate environment')
test.add_argument('--debug',
dest='debug',
action='store_true',
help='Example: `./minislate test --debug`')
test.add_argument('--kill',
dest='kill',
action='store_true',
help='Example: `./minislate test --kill`')
build = subparsers.add_parser('build', help='build/rebuild container images')
build.add_argument('subcommand', metavar='container', nargs='?', choices=[
'kube', 'slate', 'db', 'nfs'], help='Example: `./minislate build slate`')
shell = subparsers.add_parser('shell', help='open a shell in a minislate container')
shell.add_argument('subcommand', metavar='container', choices=[
'kube', 'slate', 'db', 'nfs'], help='Example: `./minislate shell slate`')
slate = subparsers.add_parser('slate', help='run a slate command')
slate.add_argument('subcommand', metavar='command', nargs=argparse.REMAINDER,
help='Example: `./minislate slate group list`')
kubectl = subparsers.add_parser('kubectl', help='run a kubectl command')
kubectl.add_argument('subcommand', metavar='command', nargs=argparse.REMAINDER,
help='Example: `./minislate kubectl get po --all-namespaces`')
exec_ = subparsers.add_parser('exec', help='wrapper of "docker-compose exec"')
exec_.add_argument('subcommand', metavar='command', nargs=argparse.REMAINDER,
help='Example: `./minislate exec kube ip addr`')
subparsers.add_parser('reload-catalog', help='reload production slate catalog')
proxy = subparsers.add_parser('proxy', help='proxy an internal socket address to the host')
proxygroup = proxy.add_mutually_exclusive_group()
proxygroup.add_argument('--list',
dest='list',
action='store_true',
help='Example: `./minislate proxy list`')
proxygroup.add_argument('--rm', metavar='pid', dest='pid', nargs='?',
help='remove a proxy already in place by its PID')
proxygroup.add_argument('address', metavar='address', nargs='?',
help='socket address in kube container, likely a load balancer')
# gui = subparsers.add_parser('portal', help='open the slate web interface for minislate')
return parser
def run_main():
parser = create_arg_parsers()
args = parser.parse_args()
provider = VirtProvider()
if args.command not in ["init", "build", "test"]:
# test for initialization if we're running a command
# some commands need to run before init, hence the check above
init_check()
if args.command == 'init':
init_slate(args, provider)
elif args.command == 'pause':
ready_check(provider, ready_error='It appears MiniSLATE is already paused.')
pause_minislate(provider)
elif args.command == 'unpause':
unpause_minislate(provider)
elif args.command == 'destroy':
destroy_minislate(args, provider)
elif args.command == 'build':
# don't want init
build_minislate(args, provider)
elif args.command == 'shell':
ready_check(provider)
provider.interactive(args.subcommand)
elif args.command == 'status':
output = provider.compose(['ps'])
if not output:
print("Could not get status")
sys.exit(1)
output = [x for x in output.split("\n") if len(x) > 70]
print("\n".join(output))
elif args.command == 'test':
# don't want init
test_minislate(args, provider)
elif args.command == 'slate':
ready_check(provider)
provider.exec('slate', ['slate'] + args.subcommand)
elif args.command == 'kubectl':
ready_check(provider)
provider.exec('k3s', ['kubectl'] + args.subcommand)
elif args.command == 'exec':
ready_check(provider)
provider.exec(args.subcommand[0], args.subcommand[1:])
elif args.command == 'reload-catalog':
ready_check(provider)
retcode = provider.exec('slate', ['sh',
'-c',
'curl --fail -X POST '
'$(cat ~/.slate/endpoint)/v1alpha3/update_apps?token=$(cat ~/.slate/token)']) # noqa: E501
if retcode == 0:
print("SLATE Catalog has been reloaded.")
else:
print("SLATE Catalog reload failed.")
elif args.command == 'proxy':
if args.pid:
provider.exec('k3s', ['kube', 'kill', args.pid])
elif args.list:
listing = "No proxies found"
try:
listing = subprocess.check_output(['docker-compose',
'exec',
'kube',
'/bin/sh',
'-c',
'"ps --headers a o pid,cmd | '
'grep -E \'socat|PID\' | '
'grep -E \'while|PID\' | '
'grep -v grep"'])
except subprocess.CalledProcessError:
pass
print(listing)
else:
ready_check(provider)
exitcode = 0
port = 0
while exitcode < 1:
port = str(randint(30100, 30201))
exitcode = provider.run('docker-compose exec kube lsof -i :' + port)
provider.run(f'docker-compose exec -d kube /bin/sh -c "while true; do socat '
f'TCP-LISTEN:{port} TCP:{args.address}; done"')
print(f'{args.address} is now accessible at localhost:{port} on your host')
elif args.command == 'portal':
dashboardurl = "http://localhost:5050/slate_portal"
success = False
for launcher in ["xdg-open", "open"]:
try:
result = subprocess.call([launcher, dashboardurl])
if result == 0:
success = True
break
except OSError:
pass # let loop continue
if not success:
print("Unable to open the dashboard automatically.")
print(f"You can open {dashboardurl} in your web browser manually.")
else:
if args.command == '' or args.command is None:
sys.stderr.write("No argument given\n")
else:
sys.stderr.write(f"Invalid argument: {args.command}\n")
if __name__ == "__main__":
from config import *
sys.excepthook = exception_handler
run_main()