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 buildkite webhook pokes (https://buildkite.com/docs/apis/webhooks)
6+ # When it gets one, downloads the artifact from buildkite
67# and deploys it as the new version.
78#
89# Requires the following python packages:
1617import traceback
1718from urlparse import urljoin
1819import glob
20+ import re
21+ import shutil
1922
2023from flask import Flask , jsonify , request , abort
2124
2225from deploy import Deployer , DeployException
2326
2427app = Flask (__name__ )
2528
26- arg_jenkins_url = None
2729deployer = None
2830arg_extract_path = None
2931arg_symlink = None
32+ arg_webhook_token = None
33+ arg_api_token = None
3034
3135def create_symlink (source , linkname ):
3236 try :
@@ -39,81 +43,98 @@ def create_symlink(source, linkname):
3943 else :
4044 raise e
4145
46+ def req_headers ():
47+ return {
48+ "Authorization" : "Bearer %s" % (arg_api_token ,),
49+ }
50+
4251@app .route ("/" , methods = ["POST" ])
43- def on_receive_jenkins_poke ():
44- # {
45- # "name": "VectorWebDevelop",
46- # "build": {
47- # "number": 8
48- # }
49- # }
52+ def on_receive_buildkite_poke ():
53+ got_webhook_token = request .headers .get ('X-Buildkite-Token' )
54+ if got_webhook_token != arg_webbook_token :
55+ print ("Denying request with incorrect webhook token: %s" % (got_webhook_token ,))
56+ abort (400 , "Incorrect webhook token" )
57+ return
58+
59+ required_api_prefix = None
60+ if arg_buildkit_org is not None :
61+ required_api_prefix = 'https://api.buildkite.com/v2/organizations/%s' % (arg_buildkit_org ,)
62+
5063 incoming_json = request .get_json ()
5164 if not incoming_json :
5265 abort (400 , "No JSON provided!" )
5366 return
5467 print ("Incoming JSON: %s" % (incoming_json ,))
5568
56- job_name = incoming_json .get ("name " )
57- if not isinstance ( job_name , basestring ) :
58- abort (400 , "Bad job name: %s" % ( job_name ,) )
69+ event = incoming_json .get ("event " )
70+ if event is None :
71+ abort (400 , "No 'event' specified" )
5972 return
6073
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" )
74+ if event == 'ping' :
75+ print ("Got ping request - responding" )
76+ return jsonify ({'response' : 'pong!' })
77+
78+ if event != 'build.finished' :
79+ print ("Rejecting '%s' event" )
80+ abort (400 , "Unrecognised event" )
6481 return
6582
66- return fetch_jenkins_build (job_name , build_num )
83+ build_obj = incoming_json .get ("build" )
84+ if build_obj is None :
85+ abort (400 , "No 'build' object" )
86+ return
6787
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." )
88+ build_url = build_obj .get ('url' )
89+ if build_url is None :
90+ abort (400 , "build has no url" )
10391 return
10492
105- if len (artifact_response .get ("artifacts" , [])) != 1 :
106- abort (404 , "Not deploying. Build has an unexpected number of artifacts." )
93+ if required_api_prefix is not None and not build_url .startswith (required_api_prefix ):
94+ print ("Denying poke for build url with incorrect prefix: %s" % (build_url ,))
95+ abort (400 , "Invalid build url" )
10796 return
10897
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 " )
98+ build_num = build_obj . get ( 'number' )
99+ if build_num is None :
100+ abort (400 , "build has no number " )
112101 return
113102
114- tar_gz_url = urljoin (
115- arg_jenkins_url , "job/%s/%s/artifact/%s" % (job_name , build_num , tar_gz_path )
116- )
103+ pipeline_obj = incoming_json .get ("pipeline" )
104+ if pipeline_obj is None :
105+ abort (400 , "No 'pipeline' object" )
106+ return
107+
108+ pipeline_name = pipeline_obj .get ('name' )
109+ if pipeline_name is None :
110+ abort (400 , "pipeline has no name" )
111+ return
112+
113+ artifacts_url = build_url + "/artifacts"
114+ artifacts_resp = requests .get (artifacts_url , headers = req_headers ())
115+ artifacts_resp .raise_for_status ()
116+ artifacts_array = artifacts_resp .json ()
117+
118+ for artifact in artifacts_array :
119+ artifact_to_deploy = None
120+ if re .match (r"dist/.*.tar.gz" , artifact ['path' ]):
121+ artifact_to_deploy = artifact
122+ if artifact_to_deploy is None :
123+ print ("No suitable artifacts found" )
124+ return jsonify ({})
125+
126+ # double paranoia check: make sure the artifact is on the right org too
127+ if required_api_prefix is not None and not artifact_to_deploy ['url' ].startswith (required_api_prefix ):
128+ print ("Denying poke for build url with incorrect prefix: %s" % (artifact_to_deploy ['url' ],))
129+ abort (400 , "Refusing to deploy artifact from URL %s" , artifact_to_deploy ['url' ])
130+ return
131+
132+ return deploy_buildkite_artifact (artifact_to_deploy , pipeline_name , build_num )
133+
134+ def deploy_buildkite_artifact (artifact , pipeline_name , build_num ):
135+ artifact_response = requests .get (artifact ['url' ], headers = req_headers ())
136+ artifact_response .raise_for_status ()
137+ artifact_obj = artifact_response .json ()
117138
118139 # we extract into a directory based on the build number. This avoids the
119140 # problem of multiple builds building the same git version and thus having
@@ -122,9 +143,9 @@ def fetch_jenkins_build(job_name, build_num):
122143 # a good deploy with a bad one
123144 # (b) we'll be overwriting the live deployment, which means people might
124145 # see half-written files.
125- build_dir = os .path .join (arg_extract_path , "%s-#%s" % (job_name , build_num ))
146+ build_dir = os .path .join (arg_extract_path , "%s-#%s" % (pipeline_name , build_num ))
126147 try :
127- extracted_dir = deploy_tarball (tar_gz_url , build_dir )
148+ extracted_dir = deploy_tarball (artifact_obj , build_dir )
128149 except DeployException as e :
129150 traceback .print_exc ()
130151 abort (400 , e .message )
@@ -133,7 +154,7 @@ def fetch_jenkins_build(job_name, build_num):
133154
134155 return jsonify ({})
135156
136- def deploy_tarball (tar_gz_url , build_dir ):
157+ def deploy_tarball (artifact , build_dir ):
137158 """Download a tarball from jenkins and unpack it
138159
139160 Returns:
@@ -145,20 +166,22 @@ def deploy_tarball(tar_gz_url, build_dir):
145166 )
146167 os .mkdir (build_dir )
147168
169+ # Download the tarball here as buildkite needs auth to do this
170+ # we don't pgp-sign buildkite artifacts, relying on HTTPS and buildkite
171+ # not being evil. If that's not good enough for you, don't use riot.im/develop.
172+ resp = requests .get (artifact ['download_url' ], stream = True , headers = req_headers ())
173+ resp .raise_for_status ()
174+ with open (artifact ['filename' ], 'wb' ) as ofp :
175+ shutil .copyfileobj (resp .raw , ofp )
176+
148177 # we rely on the fact that flask only serves one request at a time to
149178 # ensure that we do not overwrite a tarball from a concurrent request.
150179
151- return deployer .deploy (tar_gz_url , build_dir )
180+ return deployer .deploy (artifact [ 'filename' ] , build_dir )
152181
153182
154183if __name__ == "__main__" :
155184 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- )
162185 parser .add_argument (
163186 "-p" , "--port" , dest = "port" , default = 4000 , type = int , help = (
164187 "The port to listen on for requests from Jenkins."
@@ -204,13 +227,33 @@ def deploy_tarball(tar_gz_url, build_dir):
204227 ),
205228 )
206229
230+ parser .add_argument (
231+ "--webhook-token" , dest = "webhook_token" , help = (
232+ "Only accept pokes with this buildkite token."
233+ ), required = True ,
234+ )
235+
236+ parser .add_argument (
237+ "--api-token" , dest = "api_token" , help = (
238+ "API access token for buildkite. Require read_artifacts scope."
239+ ), required = True ,
240+ )
241+
242+ # We require a matching webhook token, but because we take everything else
243+ # about what to deploy from the poke body, we can be a little more paranoid
244+ # and only accept builds / artifacts from a specific buildkite org
245+ parser .add_argument (
246+ "--org" , dest = "buildkite_org" , help = (
247+ "Lock down to this buildkite org"
248+ )
249+ )
250+
207251 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 + "/"
212252 arg_extract_path = args .extract
213253 arg_symlink = args .symlink
254+ arg_webbook_token = args .webhook_token
255+ arg_api_token = args .api_token
256+ arg_buildkit_org = args .buildkit_org
214257
215258 if not os .path .isdir (arg_extract_path ):
216259 os .mkdir (arg_extract_path )
@@ -222,25 +265,17 @@ def deploy_tarball(tar_gz_url, build_dir):
222265 for include in args .include :
223266 deployer .symlink_paths .update ({ os .path .basename (pth ): pth for pth in glob .iglob (include ) })
224267
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-
232268 if args .tarball_uri is not None :
233269 build_dir = os .path .join (arg_extract_path , "test-%i" % (time .time ()))
234270 deploy_tarball (args .tarball_uri , build_dir )
235271 else :
236272 print (
237- "Listening on port %s. Extracting to %s%s. Symlinking to %s. Jenkins URL: %s. Include files: %s" %
273+ "Listening on port %s. Extracting to %s%s. Symlinking to %s. Include files: %s" %
238274 (args .port ,
239275 arg_extract_path ,
240276 " (clean after)" if deployer .should_clean else "" ,
241277 arg_symlink ,
242- arg_jenkins_url ,
243278 deployer .symlink_paths ,
244279 )
245280 )
246- app .run (host = "0.0.0.0" , port = args .port , debug = True )
281+ app .run (port = args .port , debug = False )
0 commit comments