-
Notifications
You must be signed in to change notification settings - Fork 16
/
docker-entrypoint.py
304 lines (241 loc) · 8.62 KB
/
docker-entrypoint.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
import os
import subprocess
import sys
import time
from typing import Any, List, Literal, Optional
from urllib import request
from urllib.parse import urlencode
ROOT = "/var/www/webtrees"
CONFIG_FILE = os.path.join(ROOT, "data", "config.ini.php")
os.chdir(ROOT)
def print2(msg: Any) -> None:
"""
Print a message to stdout.
"""
print(f"[NV_INIT] {msg}", file=sys.stderr)
def truish(value: Optional[str]) -> bool:
"""
Check if a value is close enough to true
"""
if value is None:
return False
return value.lower().strip() in ["true", "yes", "1"]
def get_env(
key: str, default: Optional[Any] = None, alternates: Optional[List[str]] = None
) -> Optional[Any]:
"""
Try to find the value of an environment variable.
"""
key = key.upper()
# try to find variable in env
if key in os.environ:
value = os.environ[key]
print(f"{key} found in environment variables: {value}")
return value
# try to find file version of variable
file_key = f"{key}_FILE"
if file_key in os.environ:
# file name does not exist
if not os.path.isfile(os.environ[file_key]):
print(f"WARNING: {file_key} is not a file: {os.environ[file_key]}")
return None
# read data from file
with open(os.environ[file_key], "r") as f:
value = f.read().strip()
print(f"{file_key} found in environment variables: {value}")
return value
# try to find alternate variable
if alternates is not None:
for a in alternates:
if get_env(a) is not None:
return a
# return default value
return default
def replace_line(filepath: str, src: str, replacement: str) -> None:
"""
In a given file, find a line starting with the given src, and replace the line
with the replacement.
"""
print2(f"Replacing line starting with '{src}' with '{replacement}' in {filepath}")
if not os.path.isfile(filepath):
print2(f"WARNING: {filepath} does not exist")
return
# read file
with open(filepath, "r") as fp:
lines = fp.readlines()
# replace matching line
for i, line in enumerate(lines):
if line.startswith(src):
if line == replacement:
print2(f"{filepath} already contains the correct line")
return
lines[i] = replacement
break
# write new contents
with open(filepath, "w") as fp:
fp.writelines(lines)
def enable_apache_site(
enable_sites: List[Literal["webtrees", "webtrees-redir", "webtrees-ssl"]]
) -> None:
"""
Enable an Apache site.
"""
all_sites = ["webtrees", "webtrees-redir", "webtrees-ssl"]
# disable the other sites
for s in all_sites:
if s not in enable_sites:
print2(f"Disabling site {s}")
subprocess.check_call(["a2dissite", s])
# enable the desired sites
for s in enable_sites:
print2(f"Enabling site {s}")
subprocess.check_call(["a2ensite", s])
def perms():
# set up folder permissions
print2("Setting up folder permissions for uploads")
subprocess.check_call(["chown", "-R", "www-data:www-data", "data"])
subprocess.check_call(["chmod", "-R", "755", "data"])
subprocess.check_call(["chown", "-R", "www-data:www-data", "media"])
subprocess.check_call(["chmod", "-R", "755", "media"])
def setup_wizard():
print2("Attempting to automate setup wizard")
# values with defaults
lang = get_env("LANG", "en-US")
db_type = get_env("DB_TYPE", "mysql")
db_port = get_env("DB_PORT", "3306")
db_user = get_env("DB_USER", "webtrees", alternates=["MYSQL_USER", "MARIADB_USER"])
db_name = get_env(
"DB_NAME", "webtrees", alternates=["MYSQL_DATABASE", "MARIADB_DATABASE"]
)
table_prefix = get_env("DB_PREFIX", "wt_")
# values without defaults
db_host = get_env("DB_HOST")
db_pass = get_env("DB_PASS", alternates=["MYSQL_PASSWORD", "MARIADB_PASSWORD"])
base_url = get_env("BASE_URL")
wt_name = get_env("WT_NAME")
wt_user = get_env("WT_USER")
wt_pass = get_env("WT_PASS")
wt_email = get_env("WT_EMAIL")
if os.path.isfile(CONFIG_FILE):
print2("Config file already exists")
# make sure all the variables we need are set
if not all([db_host, db_port, db_user, db_pass, db_name, base_url]):
print2("WARNING: Not all required variables were found for config update")
return
print2("Updating config file")
replace_line(CONFIG_FILE, "dbhost=", f"dbhost={db_host}")
replace_line(CONFIG_FILE, "dbport=", f"dbport={db_port}")
replace_line(CONFIG_FILE, "dbuser=", f"dbuser={db_user}")
replace_line(CONFIG_FILE, "dbpass=", f"dbpass={db_pass}")
replace_line(CONFIG_FILE, "dbname=", f"dbname={db_name}")
replace_line(CONFIG_FILE, "tblpfx=", f"tblpfx={table_prefix}")
replace_line(CONFIG_FILE, "base_url=", f"base_url={base_url}")
else:
print2("Config file does NOT exist")
# make sure all the variables we need are set
if not all(
[
lang,
db_type,
db_host,
db_port,
db_user,
db_pass,
db_name,
base_url,
wt_name,
wt_user,
wt_pass,
wt_email,
]
):
print2("WARNING: Not all required variables were found for setup wizard")
return
print2("Automating setup wizard")
print2("Starting Apache in background")
# set us up to a known HTTP state
enable_apache_site(["webtrees"])
# run apache in the background
apache_proc = subprocess.Popen(["apache2-foreground"])
# wait until database is ready
if db_type == "mysql":
while (
subprocess.run(
["mysqladmin", "ping", f"-h{db_host}", "--silent"]
).returncode
!= 0
):
print2("Waiting for MySQL server to be ready")
time.sleep(1)
elif db_type != "sqlite":
print2("Waiting 10 seconds arbitrarily for database server to be ready")
time.sleep(10)
else:
# let Apache start up
time.sleep(2)
# send it
print2("Sending setup wizard request")
resp = request.urlopen(
"http://127.0.0.1:80/",
urlencode(
{
"lang": lang,
"dbtype": db_type,
"dbhost": db_host,
"dbport": db_port,
"dbuser": db_user,
"dbpass": db_pass,
"dbname": db_name,
"tblpfx": table_prefix,
"baseurl": base_url,
"wtname": wt_name,
"wtuser": wt_user,
"wtpass": wt_pass,
"wtemail": wt_email,
"step": "6",
}
).encode("ascii"),
)
assert resp.status == 200
print2("Stopping Apache")
apache_proc.terminate()
def pretty_urls():
print2("Configuring pretty URLs")
# can't do anything if file does not exist
if not os.path.isfile(CONFIG_FILE):
print2(f"WARNING: {CONFIG_FILE} does not exist")
return
replacement = str(int(truish(get_env("PRETTY_URLS"))))
replace_line(CONFIG_FILE, "rewrite_urls=", f"rewrite_urls={replacement}")
def https():
print2("Configuring HTTPS")
# no https
if not truish(get_env("HTTPS", alternates=["SSL"])):
print2("Removing HTTPS")
enable_apache_site(["webtrees"])
# https with redirect
elif truish(get_env("HTTPS_REDIRECT", alternates=["SSL_REDIRECT"])):
print2("Adding HTTPS, with HTTPS redirect")
enable_apache_site(["webtrees-ssl", "webtrees-redir"])
# https no redirect
else:
print2("Adding HTTPS, removing HTTPS redirect")
enable_apache_site(["webtrees", "webtrees-ssl"])
def htaccess():
htaccess_file = os.path.join(ROOT, "data", ".htaccess")
if os.path.isfile(htaccess_file):
return
print2(f"WARNING: {htaccess_file} does not exist")
with open(htaccess_file, "w") as fp:
fp.writelines(["order allow,deny", "deny from all"])
print2(f"Created {htaccess_file}")
def main():
perms()
setup_wizard()
pretty_urls()
https()
htaccess()
print2("Starting Apache")
subprocess.run(["apache2-foreground"])
if __name__ == "__main__":
main()