22#
33# auto-deploy script for https://riot.im/develop
44#
5- # Listens for HTTP hits. When it gets one, downloads the artifact from jenkins
5+ # Listens for HTTP hits. When it gets one, downloads the artifact from buildkite
66# and deploys it as the new version.
77#
88# Requires the following python packages:
1616import traceback
1717from urlparse import urljoin
1818import glob
19+ import re
20+ import shutil
1921
2022from flask import Flask , jsonify , request , abort
2123
2224from deploy import Deployer , DeployException
2325
2426app = Flask (__name__ )
2527
26- arg_jenkins_url = None
2728deployer = None
2829arg_extract_path = None
2930arg_symlink = None
31+ arg_webbook_token = None
32+ arg_api_token = None
3033
3134def create_symlink (source , linkname ):
3235 try :
@@ -39,81 +42,98 @@ def create_symlink(source, linkname):
3942 else :
4043 raise e
4144
45+ def req_headers ():
46+ return {
47+ "Authorization" : "Bearer %s" % (arg_api_token ,),
48+ }
49+
4250@app .route ("/" , methods = ["POST" ])
43- def on_receive_jenkins_poke ():
44- # {
45- # "name": "VectorWebDevelop",
46- # "build": {
47- # "number": 8
48- # }
49- # }
51+ def on_receive_buildkite_poke ():
52+ got_webhook_token = request .headers .get ('X-Buildkite-Token' )
53+ if got_webhook_token != arg_webbook_token :
54+ print ("Denying request with incorrect webhook token: %s" % (got_webhook_token ,))
55+ abort (400 , "Incorrect webhook token" )
56+ return
57+
58+ required_api_prefix = None
59+ if arg_buildkit_org is not None :
60+ required_api_prefix = 'https://api.buildkite.com/v2/organizations/%s' % (arg_buildkit_org ,)
61+
5062 incoming_json = request .get_json ()
5163 if not incoming_json :
5264 abort (400 , "No JSON provided!" )
5365 return
5466 print ("Incoming JSON: %s" % (incoming_json ,))
5567
56- job_name = incoming_json .get ("name " )
57- if not isinstance ( job_name , basestring ) :
58- abort (400 , "Bad job name: %s" % ( job_name ,) )
68+ event = incoming_json .get ("event " )
69+ if event is None :
70+ abort (400 , "No 'event' specified" )
5971 return
6072
61- build_num = incoming_json .get ("build" , {}).get ("number" , 0 )
62- if not build_num or build_num <= 0 or not isinstance (build_num , int ):
63- abort (400 , "Missing or bad build number" )
73+ if event == 'ping' :
74+ print ("Got ping request - responding" )
75+ return jsonify ({'response' : 'pong!' })
76+
77+ if event != 'build.finished' :
78+ print ("Rejecting '%s' event" )
79+ abort (400 , "Unrecognised event" )
6480 return
6581
66- return fetch_jenkins_build (job_name , build_num )
82+ build_obj = incoming_json .get ("build" )
83+ if build_obj is None :
84+ abort (400 , "No 'build' object" )
85+ return
6786
68- def fetch_jenkins_build (job_name , build_num ):
69- artifact_url = urljoin (
70- arg_jenkins_url , "job/%s/%s/api/json" % (job_name , build_num )
71- )
72- artifact_response = requests .get (artifact_url ).json ()
73-
74- # {
75- # "actions": [],
76- # "artifacts": [
77- # {
78- # "displayPath": "vector-043f6991a4ed-react-20f77d1224ef-js-0a7efe3e8bd5.tar.gz",
79- # "fileName": "vector-043f6991a4ed-react-20f77d1224ef-js-0a7efe3e8bd5.tar.gz",
80- # "relativePath": "vector-043f6991a4ed-react-20f77d1224ef-js-0a7efe3e8bd5.tar.gz"
81- # }
82- # ],
83- # "building": false,
84- # "description": null,
85- # "displayName": "#11",
86- # "duration": 137976,
87- # "estimatedDuration": 132008,
88- # "executor": null,
89- # "fullDisplayName": "VectorWebDevelop #11",
90- # "id": "11",
91- # "keepLog": false,
92- # "number": 11,
93- # "queueId": 12254,
94- # "result": "SUCCESS",
95- # "timestamp": 1454432640079,
96- # "url": "http://matrix.org/jenkins/job/VectorWebDevelop/11/",
97- # "builtOn": "",
98- # "changeSet": {},
99- # "culprits": []
100- # }
101- if artifact_response .get ("result" ) != "SUCCESS" :
102- abort (404 , "Not deploying. Build was not marked as SUCCESS." )
87+ build_url = build_obj .get ('url' )
88+ if build_url is None :
89+ abort (400 , "build has no url" )
10390 return
10491
105- if len (artifact_response .get ("artifacts" , [])) != 1 :
106- abort (404 , "Not deploying. Build has an unexpected number of artifacts." )
92+ if required_api_prefix is not None and not build_url .startswith (required_api_prefix ):
93+ print ("Denying poke for build url with incorrect prefix: %s" % (build_url ,))
94+ abort (400 , "Invalid build url" )
10795 return
10896
109- tar_gz_path = artifact_response [ "artifacts" ][ 0 ][ "relativePath" ]
110- if not tar_gz_path . endswith ( ".tar.gz" ) :
111- abort (404 , "Not deploying. Artifact is not a .tar.gz file " )
97+ build_num = build_obj . get ( 'number' )
98+ if build_num is None :
99+ abort (400 , "build has no number " )
112100 return
113101
114- tar_gz_url = urljoin (
115- arg_jenkins_url , "job/%s/%s/artifact/%s" % (job_name , build_num , tar_gz_path )
116- )
102+ pipeline_obj = incoming_json .get ("pipeline" )
103+ if pipeline_obj is None :
104+ abort (400 , "No 'pipeline' object" )
105+ return
106+
107+ pipeline_name = pipeline_obj .get ('name' )
108+ if pipeline_name is None :
109+ abort (400 , "pipeline has no name" )
110+ return
111+
112+ artifacts_url = build_url + "/artifacts"
113+ artifacts_resp = requests .get (artifacts_url , headers = req_headers ())
114+ artifacts_resp .raise_for_status ()
115+ artifacts_array = artifacts_resp .json ()
116+
117+ for artifact in artifacts_array :
118+ artifact_to_deploy = None
119+ if re .match (r"dist/.*.tar.gz" , artifact ['path' ]):
120+ artifact_to_deploy = artifact
121+ if artifact_to_deploy is None :
122+ print ("No suitable artifacts found" )
123+ return jsonify ({})
124+
125+ # double paranoia check: make sure the artifact is on the right org too
126+ if required_api_prefix is not None and not artifact_to_deploy ['url' ].startswith (required_api_prefix ):
127+ print ("Denying poke for build url with incorrect prefix: %s" % (artifact_to_deploy ['url' ],))
128+ abort (400 , "Refusing to deploy artifact from URL %s" , artifact_to_deploy ['url' ])
129+ return
130+
131+ return deploy_buildkite_artifact (artifact_to_deploy , pipeline_name , build_num )
132+
133+ def deploy_buildkite_artifact (artifact , pipeline_name , build_num ):
134+ artifact_response = requests .get (artifact ['url' ], headers = req_headers ())
135+ artifact_response .raise_for_status ()
136+ artifact_obj = artifact_response .json ()
117137
118138 # we extract into a directory based on the build number. This avoids the
119139 # problem of multiple builds building the same git version and thus having
@@ -122,9 +142,9 @@ def fetch_jenkins_build(job_name, build_num):
122142 # a good deploy with a bad one
123143 # (b) we'll be overwriting the live deployment, which means people might
124144 # see half-written files.
125- build_dir = os .path .join (arg_extract_path , "%s-#%s" % (job_name , build_num ))
145+ build_dir = os .path .join (arg_extract_path , "%s-#%s" % (pipeline_name , build_num ))
126146 try :
127- extracted_dir = deploy_tarball (tar_gz_url , build_dir )
147+ extracted_dir = deploy_tarball (artifact_obj , build_dir )
128148 except DeployException as e :
129149 traceback .print_exc ()
130150 abort (400 , e .message )
@@ -133,7 +153,7 @@ def fetch_jenkins_build(job_name, build_num):
133153
134154 return jsonify ({})
135155
136- def deploy_tarball (tar_gz_url , build_dir ):
156+ def deploy_tarball (artifact , build_dir ):
137157 """Download a tarball from jenkins and unpack it
138158
139159 Returns:
@@ -145,20 +165,22 @@ def deploy_tarball(tar_gz_url, build_dir):
145165 )
146166 os .mkdir (build_dir )
147167
168+ # Download the tarball here as buildkite needs auth to do this
169+ # we don't pgp-sign buildkite artifacts, relying on HTTPS and buildkite
170+ # not being evil. If that's not good enough for you, don't use riot.im/develop.
171+ resp = requests .get (artifact ['download_url' ], stream = True , headers = req_headers ())
172+ resp .raise_for_status ()
173+ with open (artifact ['filename' ], 'wb' ) as ofp :
174+ shutil .copyfileobj (resp .raw , ofp )
175+
148176 # we rely on the fact that flask only serves one request at a time to
149177 # ensure that we do not overwrite a tarball from a concurrent request.
150178
151- return deployer .deploy (tar_gz_url , build_dir )
179+ return deployer .deploy (artifact [ 'filename' ] , build_dir )
152180
153181
154182if __name__ == "__main__" :
155183 parser = argparse .ArgumentParser ("Runs a Vector redeployment server." )
156- parser .add_argument (
157- "-j" , "--jenkins" , dest = "jenkins" , default = "https://matrix.org/jenkins/" , help = (
158- "The base URL of the Jenkins web server. This will be hit to get the\
159- built artifacts (the .gz file) for redeploying."
160- )
161- )
162184 parser .add_argument (
163185 "-p" , "--port" , dest = "port" , default = 4000 , type = int , help = (
164186 "The port to listen on for requests from Jenkins."
@@ -204,13 +226,33 @@ def deploy_tarball(tar_gz_url, build_dir):
204226 ),
205227 )
206228
229+ parser .add_argument (
230+ "--webhook-token" , dest = "webhook_token" , help = (
231+ "Only accept pokes with this buildkite token."
232+ ), required = True ,
233+ )
234+
235+ parser .add_argument (
236+ "--api-token" , dest = "api_token" , help = (
237+ "API access token for buildkite. Require read_artifacts scope."
238+ ), required = True ,
239+ )
240+
241+ # We require a matching webhook token, but because we take everything else
242+ # about what to deploy from the poke body, we can be a little more paranoid
243+ # and only accept builds / artifacts from a specific buildkite org
244+ parser .add_argument (
245+ "--org" , dest = "buildkit_org" , help = (
246+ "Lock down to this buildkite org"
247+ )
248+ )
249+
207250 args = parser .parse_args ()
208- if args .jenkins .endswith ("/" ): # important for urljoin
209- arg_jenkins_url = args .jenkins
210- else :
211- arg_jenkins_url = args .jenkins + "/"
212251 arg_extract_path = args .extract
213252 arg_symlink = args .symlink
253+ arg_webbook_token = args .webhook_token
254+ arg_api_token = args .api_token
255+ arg_buildkit_org = args .buildkit_org
214256
215257 if not os .path .isdir (arg_extract_path ):
216258 os .mkdir (arg_extract_path )
@@ -222,25 +264,17 @@ def deploy_tarball(tar_gz_url, build_dir):
222264 for include in args .include :
223265 deployer .symlink_paths .update ({ os .path .basename (pth ): pth for pth in glob .iglob (include ) })
224266
225-
226- # we don't pgp-sign jenkins artifacts; instead we rely on HTTPS access to
227- # the jenkins server (and the jenkins server not being compromised and/or
228- # github not serving it compromised source). If that's not good enough for
229- # you, don't use riot.im/develop.
230- deployer .verify_signature = False
231-
232267 if args .tarball_uri is not None :
233268 build_dir = os .path .join (arg_extract_path , "test-%i" % (time .time ()))
234269 deploy_tarball (args .tarball_uri , build_dir )
235270 else :
236271 print (
237- "Listening on port %s. Extracting to %s%s. Symlinking to %s. Jenkins URL: %s. Include files: %s" %
272+ "Listening on port %s. Extracting to %s%s. Symlinking to %s. Include files: %s" %
238273 (args .port ,
239274 arg_extract_path ,
240275 " (clean after)" if deployer .should_clean else "" ,
241276 arg_symlink ,
242- arg_jenkins_url ,
243277 deployer .symlink_paths ,
244278 )
245279 )
246- app .run (host = "0.0.0.0" , port = args .port , debug = True )
280+ app .run (port = args .port , debug = False )
0 commit comments