11#!/usr/bin/env python
2+ #
3+ # auto-deploy script for https://riot.im/develop
4+ #
5+ # Listens for HTTP hits. When it gets one, downloads the artifact from jenkins
6+ # and deploys it as the new version.
7+ #
8+ # Requires the following python packages:
9+ #
10+ # - requests
11+ # - flask
12+ #
213from __future__ import print_function
314import json , requests , tarfile , argparse , os , errno
15+ import time
416from urlparse import urljoin
517from flask import Flask , jsonify , request , abort
18+
619app = Flask (__name__ )
720
8- arg_jenkins_url , arg_extract_path , arg_should_clean , arg_symlink , arg_config_location = (
9- None , None , None , None , None
10- )
21+ arg_jenkins_url = None
22+ arg_extract_path = None
23+ arg_bundles_path = None
24+ arg_should_clean = None
25+ arg_symlink = None
26+ arg_config_location = None
27+
28+ class DeployException (Exception ):
29+ pass
1130
1231def download_file (url ):
1332 local_filename = url .split ('/' )[- 1 ]
@@ -57,6 +76,9 @@ def on_receive_jenkins_poke():
5776 abort (400 , "Missing or bad build number" )
5877 return
5978
79+ return fetch_jenkins_build (job_name , build_num )
80+
81+ def fetch_jenkins_build (job_name , build_num ):
6082 artifact_url = urljoin (
6183 arg_jenkins_url , "job/%s/%s/api/json" % (job_name , build_num )
6284 )
@@ -106,27 +128,38 @@ def on_receive_jenkins_poke():
106128 arg_jenkins_url , "job/%s/%s/artifact/%s" % (job_name , build_num , tar_gz_path )
107129 )
108130
109- print ("Retrieving .tar.gz file: %s" % tar_gz_url )
131+ # we extract into a directory based on the build number. This avoids the
132+ # problem of multiple builds building the same git version and thus having
133+ # the same tarball name. That would lead to two potential problems:
134+ # (a) sometimes jenkins serves corrupted artifacts; we would replace
135+ # a good deploy with a bad one
136+ # (b) we'll be overwriting the live deployment, which means people might
137+ # see half-written files.
138+ build_dir = os .path .join (arg_extract_path , "%s-#%s" % (job_name , build_num ))
139+ try :
140+ deploy_tarball (tar_gz_url , build_dir )
141+ except DeployException as e :
142+ abort (400 , e .message )
143+
144+ return jsonify ({})
145+
146+ 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 ))
150+
151+ if os .path .exists (build_dir ):
152+ raise DeployException (
153+ "Not deploying. We have previously deployed this build."
154+ )
155+ os .mkdir (build_dir )
110156
111157 # we rely on the fact that flask only serves one request at a time to
112158 # ensure that we do not overwrite a tarball from a concurrent request.
113159 filename = download_file (tar_gz_url )
114160 print ("Downloaded file: %s" % filename )
115161
116162 try :
117- # we extract into a directory based on the build number. This avoids the
118- # problem of multiple builds building the same git version and thus having
119- # the same tarball name. That would lead to two potential problems:
120- # (a) sometimes jenkins serves corrupted artifacts; we would replace
121- # a good deploy with a bad one
122- # (b) we'll be overwriting the live deployment, which means people might
123- # see half-written files.
124- build_dir = os .path .join (arg_extract_path , "%s-#%s" % (job_name , build_num ))
125- if os .path .exists (build_dir ):
126- abort (400 , "Not deploying. We have previously deployed this build." )
127- return
128- os .mkdir (build_dir )
129-
130163 untar_to (filename , build_dir )
131164 print ("Extracted to: %s" % build_dir )
132165 finally :
@@ -139,9 +172,47 @@ def on_receive_jenkins_poke():
139172 if arg_config_location :
140173 create_symlink (source = arg_config_location , linkname = os .path .join (extracted_dir , 'config.json' ))
141174
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+
142186 create_symlink (source = extracted_dir , linkname = arg_symlink )
143187
144- return jsonify ({})
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 )
215+
145216
146217if __name__ == "__main__" :
147218 parser = argparse .ArgumentParser ("Runs a Vector redeployment server." )
@@ -161,6 +232,13 @@ def on_receive_jenkins_poke():
161232 "The location to extract .tar.gz files to."
162233 )
163234 )
235+ parser .add_argument (
236+ "-b" , "--bundles-dir" , dest = "bundles_dir" , help = (
237+ "A directory to move the contents of the 'bundles' directory to. A \
238+ symlink to the bundles directory will also be written inside the \
239+ extracted tarball. Example: './bundles'."
240+ )
241+ )
164242 parser .add_argument (
165243 "-c" , "--clean" , dest = "clean" , action = "store_true" , default = False , help = (
166244 "Remove .tar.gz files after they have been downloaded and extracted."
@@ -179,18 +257,34 @@ def on_receive_jenkins_poke():
179257 To this location."
180258 )
181259 )
260+ parser .add_argument (
261+ "--test" , dest = "tarball_uri" , help = (
262+ "Don't start an HTTP listener. Instead download a build from Jenkins \
263+ immediately."
264+ ),
265+ )
266+
182267 args = parser .parse_args ()
183268 if args .jenkins .endswith ("/" ): # important for urljoin
184269 arg_jenkins_url = args .jenkins
185270 else :
186271 arg_jenkins_url = args .jenkins + "/"
187272 arg_extract_path = args .extract
273+ arg_bundles_path = args .bundles_dir
188274 arg_should_clean = args .clean
189275 arg_symlink = args .symlink
190276 arg_config_location = args .config
191- print (
192- "Listening on port %s. Extracting to %s%s. Symlinking to %s. Jenkins URL: %s. Config location: %s" %
193- (args .port , arg_extract_path ,
194- " (clean after)" if arg_should_clean else "" , arg_symlink , arg_jenkins_url , arg_config_location )
195- )
196- app .run (host = "0.0.0.0" , port = args .port , debug = True )
277+
278+ if not os .path .isdir (arg_extract_path ):
279+ os .mkdir (arg_extract_path )
280+
281+ if args .tarball_uri is not None :
282+ build_dir = os .path .join (arg_extract_path , "test-%i" % (time .time ()))
283+ deploy_tarball (args .tarball_uri , build_dir )
284+ else :
285+ print (
286+ "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 )
289+ )
290+ app .run (host = "0.0.0.0" , port = args .port , debug = True )
0 commit comments