-
Notifications
You must be signed in to change notification settings - Fork 16
/
wis2box-ctl.py
executable file
·231 lines (198 loc) · 7.87 KB
/
wis2box-ctl.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
#!/usr/bin/env python3
###############################################################################
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
###############################################################################
import argparse
import os
import subprocess
if subprocess.call(['docker', 'compose'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) > 0:
DOCKER_COMPOSE_COMMAND = 'docker-compose'
else:
DOCKER_COMPOSE_COMMAND = 'docker compose'
DOCKER_COMPOSE_ARGS = """
--file docker-compose.yml
--file docker-compose.override.yml
--file docker-compose.monitoring.yml
--env-file wis2box.env
--project-name wis2box_project
"""
parser = argparse.ArgumentParser(
description='manage a compposition of docker containers to implement a wis 2 box',
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument(
'--ssl',
dest='ssl',
action='store_true',
help='run wis2box with SSL enabled')
parser.add_argument(
'--simulate',
dest='simulate',
action='store_true',
help='simulate execution by printing action rather than executing')
commands = [
'build',
'config',
'down',
'execute',
'lint',
'logs',
'login',
'prune',
'restart',
'start',
'start-dev',
'status',
'stop',
'up',
'update',
]
parser.add_argument('command',
choices=commands,
help="""
- config: validate and view Docker configuration
- build [containers]: build all services
- start [containers]: start system
- start-dev [containers]: start system in local development mode
- login [container]: login to the container (default: wis2box-management)
- login-root [container]: login to the container as root
- stop: stop [container] system
- update: update Docker images
- prune: cleanup dangling containers and images
- restart [containers]: restart one or all containers
- status [containers|-a]: view status of wis2box containers
- lint: run PEP8 checks against local Python code
""")
parser.add_argument('args', nargs=argparse.REMAINDER)
args = parser.parse_args()
def split(value: str) -> list:
"""
Splits string and returns as list
:param value: required, string. bash command.
:returns: list. List of separated arguments.
"""
return value.split()
def find_files(path: str, extension: str) -> list:
"""
Walks directory path collecting all files of a given extention.
:param path: `str` of directory path
:param extension: `str` of file extension
:returns: `list` of Python filepaths
"""
file_list = []
for root, _, files in os.walk(path, topdown=False):
for name in files:
if name.endswith(extension):
file_list.append(os.path.join(root, name))
return file_list
def run(cmd, silence_stderr=False) -> None:
if not silence_stderr:
subprocess.run(cmd)
else:
subprocess.run(cmd, stderr=subprocess.DEVNULL)
return None
def make(args) -> None:
"""
Serves as pseudo Makefile using Python subprocesses.
:param command: required, string. Make command.
:returns: None.
"""
if not os.path.exists('wis2box.env'):
print("ERROR: wis2box.env file does not exist. Please create one manually or by running `python3 wis2box-create-config.py`")
exit(1)
# check if WIS2BOX_SSL_KEY and WIS2BOX_SSL_CERT are set
ssl_key = None
ssl_cert = None
with open('wis2box.env', 'r') as f:
for line in f:
if 'WIS2BOX_SSL_KEY' in line:
ssl_key = line.split('=')[1].strip()
if 'WIS2BOX_SSL_CERT' in line:
ssl_cert = line.split('=')[1].strip()
docker_compose_args = DOCKER_COMPOSE_ARGS
if args.ssl or (ssl_key and ssl_cert):
docker_compose_args +=" --file docker-compose.ssl.yml"
if args.ssl and not (ssl_key and ssl_cert):
print("ERROR: SSL is enabled but WIS2BOX_SSL_KEY and WIS2BOX_SSL_CERT are not set in wis2box.env")
exit(1)
# if you selected a bunch of them, default to all
containers = "" if not args.args else ' '.join(args.args)
# if there can be only one, default to wisbox
container = "wis2box-management" if not args.args else ' '.join(args.args)
if args.command == "config":
run(split(f'{DOCKER_COMPOSE_COMMAND} {docker_compose_args} config'))
elif args.command == "build":
run(split(
f'{DOCKER_COMPOSE_COMMAND} {docker_compose_args} build {containers}'))
elif args.command in ["up", "start", "start-dev"]:
run(split(
'docker plugin install grafana/loki-docker-driver:latest --alias loki --grant-all-permissions'),
silence_stderr=True)
run(split('docker plugin enable loki'), silence_stderr=True)
if containers:
run(split(f"{DOCKER_COMPOSE_COMMAND} {docker_compose_args} start {containers}"))
else:
if args.command == 'start-dev':
run(split(f'{DOCKER_COMPOSE_COMMAND} {docker_compose_args} --file docker-compose.dev.yml up -d'))
else:
run(split(f'{DOCKER_COMPOSE_COMMAND} {docker_compose_args} up -d'))
elif args.command == "execute":
run(['docker', 'exec', '-i', 'wis2box-management', 'sh', '-c', containers])
elif args.command == "login":
run(split(f'docker exec -it {container} /bin/bash'))
elif args.command == "login-root":
run(split(f'docker exec -u -0 -it {container} /bin/bash'))
elif args.command == "logs":
run(split(
f'{DOCKER_COMPOSE_COMMAND} {docker_compose_args} logs --follow {containers}'))
elif args.command in ["stop", "down"]:
if containers:
run(split(f"{DOCKER_COMPOSE_COMMAND} {docker_compose_args} {containers}"))
else:
run(split(
f'{DOCKER_COMPOSE_COMMAND} {docker_compose_args} down --remove-orphans {containers}'))
elif args.command == "update":
run(split(f'{DOCKER_COMPOSE_COMMAND} {docker_compose_args} pull'))
elif args.command == "prune":
run(split('docker builder prune -f'))
run(split('docker container prune -f'))
run( split('docker volume prune -f'))
_ = run(split('docker images --filter dangling=true -q --no-trunc'))
run(split(f'docker rmi {_}'))
_ = run(split('docker ps -a -q'))
run(split(f'docker rm {_}'))
elif args.command == "restart":
if containers:
run(split(
f'{DOCKER_COMPOSE_COMMAND} {docker_compose_args} stop {containers}'))
run(split(
f'{DOCKER_COMPOSE_COMMAND} {docker_compose_args} start {containers}'))
else:
run(split(
f'{DOCKER_COMPOSE_COMMAND} {docker_compose_args} down --remove-orphans'))
run(split(
f'{DOCKER_COMPOSE_COMMAND} {docker_compose_args} up -d'))
elif args.command == "status":
run(split(
f'{DOCKER_COMPOSE_COMMAND} {docker_compose_args} ps {containers}'))
elif args.command == "lint":
files = find_files(".", '.py')
run(('python3', '-m', 'flake8', *files))
if __name__ == "__main__":
make(args)