Skip to content

Commit 5206410

Browse files
committed
Deployment script
Factor some bits out of redeploy.py, so that they can be used in a deployment script suitable for riot.im/app.
1 parent 641a5c2 commit 5206410

2 files changed

Lines changed: 182 additions & 83 deletions

File tree

‎scripts/deploy.py‎

Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
#!/usr/bin/env python
2+
#
3+
# download and unpack a riot-web tarball.
4+
#
5+
# Allows `bundles` to be extracted to a common directory, and a link to
6+
# config.json to be added.
7+
8+
from __future__ import print_function
9+
10+
import argparse
11+
import os
12+
import os.path
13+
import tarfile
14+
import urllib
15+
16+
class DeployException(Exception):
17+
pass
18+
19+
def create_relative_symlink(linkname, target):
20+
relpath = os.path.relpath(target, os.path.dirname(linkname))
21+
print ("Symlink %s -> %s" % (linkname, relpath))
22+
os.symlink(relpath, linkname)
23+
24+
25+
def move_bundles(source, dest):
26+
"""Move the contents of the 'bundles' directory to a common dir
27+
28+
We check that we will not be overwriting anything before we proceed.
29+
30+
Args:
31+
source (str): path to 'bundles' within the extracted tarball
32+
dest (str): target common directory
33+
"""
34+
35+
if not os.path.isdir(dest):
36+
os.mkdir(dest)
37+
38+
# build a map from source to destination, checking for non-existence as we go.
39+
renames = {}
40+
for f in os.listdir(source):
41+
dst = os.path.join(dest, f)
42+
if os.path.exists(dst):
43+
raise DeployException(
44+
"Not deploying. The bundle includes '%s' which we have previously deployed."
45+
% f
46+
)
47+
renames[os.path.join(source, f)] = dst
48+
49+
for (src, dst) in renames.iteritems():
50+
print ("Move %s -> %s" % (src, dst))
51+
os.rename(src, dst)
52+
53+
class Deployer:
54+
def __init__(self):
55+
self.packages_path = "."
56+
self.bundles_path = None
57+
self.should_clean = False
58+
self.config_location = None
59+
60+
def deploy(self, tarball, extract_path):
61+
"""Download a tarball if necessary, and unpack it
62+
63+
Returns:
64+
(str) the path to the unpacked deployment
65+
"""
66+
print("Deploying %s to %s" % (tarball, extract_path))
67+
68+
downloaded = False
69+
if tarball.startswith("http://") or tarball.startswith("https://"):
70+
tarball = self.download_file(tarball)
71+
print("Downloaded file: %s" % tarball)
72+
downloaded = True
73+
74+
try:
75+
with tarfile.open(tarball) as tar:
76+
tar.extractall(extract_path)
77+
finally:
78+
if self.should_clean and downloaded:
79+
os.remove(tarball)
80+
81+
name_str = os.path.basename(tarball).replace(".tar.gz", "")
82+
extracted_dir = os.path.join(extract_path, name_str)
83+
print ("Extracted into: %s" % extracted_dir)
84+
85+
if self.config_location:
86+
create_relative_symlink(
87+
target=self.config_location,
88+
linkname=os.path.join(extracted_dir, 'config.json')
89+
)
90+
91+
if self.bundles_path:
92+
extracted_bundles = os.path.join(extracted_dir, 'bundles')
93+
move_bundles(source=extracted_bundles, dest=self.bundles_path)
94+
95+
# replace the (hopefully now empty) extracted_bundles dir with a
96+
# symlink to the common dir.
97+
os.rmdir(extracted_bundles)
98+
create_relative_symlink(
99+
target=self.bundles_path,
100+
linkname=extracted_bundles,
101+
)
102+
return extracted_dir
103+
104+
def download_file(self, url):
105+
if not os.path.isdir(self.packages_path):
106+
os.mkdir(self.packages_path)
107+
local_filename = os.path.join(self.packages_path,
108+
url.split('/')[-1])
109+
urllib.urlretrieve(url, local_filename)
110+
return local_filename
111+
112+
if __name__ == "__main__":
113+
parser = argparse.ArgumentParser("Deploy a Riot build on a web server.")
114+
parser.add_argument(
115+
"-p", "--packages-dir", default="./packages", help=(
116+
"The directory to download the tarball into. (Default: '%(default)s')"
117+
)
118+
)
119+
parser.add_argument(
120+
"-e", "--extract-path", default="./deploys", help=(
121+
"The location to extract .tar.gz files to. (Default: '%(default)s')"
122+
)
123+
)
124+
parser.add_argument(
125+
"-b", "--bundles-dir", nargs='?', default="./bundles", help=(
126+
"A directory to move the contents of the 'bundles' directory to. A \
127+
symlink to the bundles directory will also be written inside the \
128+
extracted tarball. Example: './bundles'. \
129+
(Default: '%(default)s')"
130+
)
131+
)
132+
parser.add_argument(
133+
"-c", "--clean", action="store_true", default=False, help=(
134+
"Remove .tar.gz files after they have been downloaded and extracted. \
135+
(Default: %(default)s)"
136+
)
137+
)
138+
parser.add_argument(
139+
"--config", nargs='?', default='./config.json', help=(
140+
"Write a symlink at config.json in the extracted tarball to this \
141+
location. (Default: '%(default)s')"
142+
)
143+
)
144+
parser.add_argument(
145+
"tarball", help=(
146+
"filename of tarball, or URL to download."
147+
),
148+
)
149+
150+
args = parser.parse_args()
151+
152+
deployer = Deployer()
153+
deployer.packages_path = args.packages_dir
154+
deployer.bundles_path = args.bundles_dir
155+
deployer.should_clean = args.clean
156+
deployer.config_location = args.config
157+
158+
deployer.deploy(args.tarball, args.extract_path)

‎scripts/redeploy.py‎

Lines changed: 24 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -14,32 +14,17 @@
1414
import json, requests, tarfile, argparse, os, errno
1515
import time
1616
from urlparse import urljoin
17+
1718
from flask import Flask, jsonify, request, abort
1819

20+
from deploy import Deployer, DeployException
21+
1922
app = Flask(__name__)
2023

2124
arg_jenkins_url = None
25+
deployer = None
2226
arg_extract_path = None
23-
arg_bundles_path = None
24-
arg_should_clean = None
2527
arg_symlink = None
26-
arg_config_location = None
27-
28-
class DeployException(Exception):
29-
pass
30-
31-
def download_file(url):
32-
local_filename = url.split('/')[-1]
33-
r = requests.get(url, stream=True)
34-
with open(local_filename, 'wb') as f:
35-
for chunk in r.iter_content(chunk_size=1024):
36-
if chunk: # filter out keep-alive new chunks
37-
f.write(chunk)
38-
return local_filename
39-
40-
def untar_to(tarball, dest):
41-
with tarfile.open(tarball) as tar:
42-
tar.extractall(dest)
4328

4429
def create_symlink(source, linkname):
4530
try:
@@ -137,17 +122,20 @@ def fetch_jenkins_build(job_name, build_num):
137122
# see half-written files.
138123
build_dir = os.path.join(arg_extract_path, "%s-#%s" % (job_name, build_num))
139124
try:
140-
deploy_tarball(tar_gz_url, build_dir)
125+
extracted_dir = deploy_tarball(tar_gz_url, build_dir)
141126
except DeployException as e:
142127
abort(400, e.message)
143128

129+
create_symlink(source=extracted_dir, linkname=arg_symlink)
130+
144131
return jsonify({})
145132

146133
def deploy_tarball(tar_gz_url, build_dir):
147-
"""Download a tarball from jenkins and deploy it as the new version
148-
"""
149-
print("Deploying %s to %s" % (tar_gz_url, build_dir))
134+
"""Download a tarball from jenkins and unpack it
150135
136+
Returns:
137+
(str) the path to the unpacked deployment
138+
"""
151139
if os.path.exists(build_dir):
152140
raise DeployException(
153141
"Not deploying. We have previously deployed this build."
@@ -156,62 +144,8 @@ def deploy_tarball(tar_gz_url, build_dir):
156144

157145
# we rely on the fact that flask only serves one request at a time to
158146
# ensure that we do not overwrite a tarball from a concurrent request.
159-
filename = download_file(tar_gz_url)
160-
print("Downloaded file: %s" % filename)
161-
162-
try:
163-
untar_to(filename, build_dir)
164-
print("Extracted to: %s" % build_dir)
165-
finally:
166-
if arg_should_clean:
167-
os.remove(filename)
168-
169-
name_str = filename.replace(".tar.gz", "")
170-
extracted_dir = os.path.join(build_dir, name_str)
171-
172-
if arg_config_location:
173-
create_symlink(source=arg_config_location, linkname=os.path.join(extracted_dir, 'config.json'))
174147

175-
if arg_bundles_path:
176-
extracted_bundles = os.path.join(extracted_dir, 'bundles')
177-
move_bundles(source=extracted_bundles, dest=arg_bundles_path)
178-
179-
# replace the (hopefully now empty) extracted_bundles dir with a
180-
# symlink to the common dir.
181-
relpath = os.path.relpath(arg_bundles_path, extracted_dir)
182-
os.rmdir(extracted_bundles)
183-
print ("Symlink %s -> %s" % (extracted_bundles, relpath))
184-
os.symlink(relpath, extracted_bundles)
185-
186-
create_symlink(source=extracted_dir, linkname=arg_symlink)
187-
188-
def move_bundles(source, dest):
189-
"""Move the contents of the 'bundles' directory to a common dir
190-
191-
We check that we will not be overwriting anything before we proceed.
192-
193-
Args:
194-
source (str): path to 'bundles' within the extracted tarball
195-
dest (str): target common directory
196-
"""
197-
198-
if not os.path.isdir(dest):
199-
os.mkdir(dest)
200-
201-
# build a map from source to destination, checking for non-existence as we go.
202-
renames = {}
203-
for f in os.listdir(source):
204-
dst = os.path.join(dest, f)
205-
if os.path.exists(dst):
206-
raise DeployException(
207-
"Not deploying. The bundle includes '%s' which we have previously deployed."
208-
% f
209-
)
210-
renames[os.path.join(source, f)] = dst
211-
212-
for (src, dst) in renames.iteritems():
213-
print ("Move %s -> %s" % (src, dst))
214-
os.rename(src, dst)
148+
return deployer.deploy(tar_gz_url, build_dir)
215149

216150

217151
if __name__ == "__main__":
@@ -270,21 +204,28 @@ def move_bundles(source, dest):
270204
else:
271205
arg_jenkins_url = args.jenkins + "/"
272206
arg_extract_path = args.extract
273-
arg_bundles_path = args.bundles_dir
274-
arg_should_clean = args.clean
275207
arg_symlink = args.symlink
276-
arg_config_location = args.config
277208

278209
if not os.path.isdir(arg_extract_path):
279210
os.mkdir(arg_extract_path)
280211

212+
deployer = Deployer()
213+
deployer.bundles_path = args.bundles_dir
214+
deployer.should_clean = args.clean
215+
deployer.config_location = args.config
216+
281217
if args.tarball_uri is not None:
282218
build_dir = os.path.join(arg_extract_path, "test-%i" % (time.time()))
283219
deploy_tarball(args.tarball_uri, build_dir)
284220
else:
285221
print(
286222
"Listening on port %s. Extracting to %s%s. Symlinking to %s. Jenkins URL: %s. Config location: %s" %
287-
(args.port, arg_extract_path,
288-
" (clean after)" if arg_should_clean else "", arg_symlink, arg_jenkins_url, arg_config_location)
223+
(args.port,
224+
arg_extract_path,
225+
" (clean after)" if deployer.should_clean else "",
226+
arg_symlink,
227+
arg_jenkins_url,
228+
deployer.config_location,
229+
)
289230
)
290231
app.run(host="0.0.0.0", port=args.port, debug=True)

0 commit comments

Comments
 (0)