forked from openSUSE/openSUSE-release-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
obs_operator.py
executable file
·392 lines (326 loc) · 14 KB
/
obs_operator.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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
#!/usr/bin/python3 -u
# Without the -u option for unbuffered output nothing shows up in journal or
# kubernetes logs.
import argparse
import http
from http.cookies import SimpleCookie
from http.cookiejar import Cookie, LWPCookieJar
from http.server import BaseHTTPRequestHandler, HTTPServer
from socketserver import ThreadingMixIn
import json
import tempfile
import os
from osc import conf
from osclib import common
from osclib.sentry import sentry_client
from osclib.sentry import sentry_init
import subprocess
import sys
import time
from urllib.parse import urlparse
from urllib.parse import parse_qs
# A cookie with an invalid key is intermittently generated on opensuse.org
# domain which causes the operator to crash when parsing the cookie. The desired
# cookie is valid, but cannot be utilize due to the exception. As suggested in
# https://stackoverflow.com/a/47012250, workaround by making EVERYTHING LEGAL!
http.cookies._is_legal_key = lambda _: True
sentry_sdk = sentry_init()
# Available in python 3.7.
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
def handle_error(self, request, client_address):
super().handle_error(request, client_address)
sentry_sdk.capture_exception()
class RequestHandler(BaseHTTPRequestHandler):
COOKIE_NAME = 'openSUSE_session' # Both OBS and IBS.
GET_PATHS = [
'origin/config',
'origin/history',
'origin/list',
'origin/package',
'origin/potentials',
'origin/projects',
'origin/report',
'package/diff',
]
POST_PATHS = [
'request/submit',
'staging/select',
]
def do_OPTIONS(self):
try:
with OSCRequestEnvironment(self, require_session=False) as oscrc_file:
self.send_header('Access-Control-Allow-Methods', 'GET, POST')
self.send_header('Access-Control-Allow-Headers', 'Access-Control-Allow-Origin, Content-Type, X-Requested-With')
except OSCRequestEnvironmentException as e:
self.send_header('Allow', 'OPTIONS, GET, POST')
self.end_headers()
def do_GET(self):
url_parts = urlparse(self.path)
path = url_parts.path.lstrip('/')
path_parts = path.split('/')
path_prefix = '/'.join(path_parts[:2])
query = parse_qs(url_parts.query)
if path_prefix == '':
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.write_string('namespace: {}\n'.format(common.NAME))
self.write_string('name: {}\n'.format('OBS Operator'))
self.write_string('version: {}\n'.format(common.VERSION))
return
if len(path_parts) < 3 or path_prefix not in self.GET_PATHS:
self.send_response(404)
self.end_headers()
return
try:
with OSCRequestEnvironment(self) as oscrc_file:
func = getattr(self, 'handle_{}'.format(path_prefix.replace('/', '_')))
command = func(path_parts[2:], query)
self.end_headers()
if command and not self.execute(oscrc_file, command):
self.write_string('failed')
except OSCRequestEnvironmentException as e:
self.write_string(str(e))
def do_POST(self):
url_parts = urlparse(self.path)
path = url_parts.path.lstrip('/')
path_parts = path.split('/')
path_prefix = '/'.join(path_parts[:2])
query = parse_qs(url_parts.query)
if len(path_parts) < 2 or path_prefix not in self.POST_PATHS:
self.send_response(404)
self.end_headers()
return
data = self.data_parse()
user = data.get('user')
if self.debug:
print('data: {}'.format(data))
try:
with OSCRequestEnvironment(self, user) as oscrc_file:
func = getattr(self, 'handle_{}'.format(path_prefix.replace('/', '_')))
commands = func(path_parts[2:], query, data)
self.end_headers()
for command in commands:
self.write_string('$ {}\n'.format(' '.join(command)))
if not self.execute(oscrc_file, command):
self.write_string('failed')
break
except OSCRequestEnvironmentException as e:
self.write_string(str(e))
def data_parse(self):
if int(self.headers['Content-Length']) == 0:
return {}
data = self.rfile.read(int(self.headers['Content-Length']))
return json.loads(data.decode('utf-8'))
def apiurl_get(self):
if self.apiurl:
return self.apiurl
host = self.headers.get('Host')
if not host:
return None
# Strip port if present.
domain = host.split(':', 2)[0]
if '.' not in domain:
return None
# Remove first subdomain and replace with api subdomain.
domain_parent = '.'.join(domain.split('.')[-2:])
return 'https://api.{}'.format(domain_parent)
def origin_domain_get(self):
origin = self.headers.get('Origin')
if origin is not None:
# Strip port if present.
domain = urlparse(origin).netloc.split(':', 2)[0]
if '.' in domain:
return '.'.join(domain.split('.')[-2:])
return None
def session_get(self):
if self.session:
return self.session
else:
cookie = self.headers.get('Cookie')
if cookie:
cookie = SimpleCookie(cookie)
if self.COOKIE_NAME in cookie:
return cookie[self.COOKIE_NAME].value
return None
def oscrc_create(self, oscrc_file, apiurl, cookiejar_file, user):
sentry_dsn = sentry_client().dsn
sentry_environment = sentry_client().options.get('environment')
oscrc_file.write('\n'.join([
'[general]',
# Passthru sentry_sdk options to allow for reporting on subcommands.
'sentry_sdk.dsn = {}'.format(sentry_dsn) if sentry_dsn else '',
'sentry_sdk.environment = {}'.format(sentry_environment) if sentry_environment else '',
'apiurl = {}'.format(apiurl),
'cookiejar = {}'.format(cookiejar_file.name),
'staging.color = 0',
'[{}]'.format(apiurl),
'user = {}'.format(user),
'pass = invalid',
'',
]).encode('utf-8'))
oscrc_file.flush()
# In order to avoid osc clearing the cookie file the modified time of
# the oscrc file must be set further into the past.
# if int(round(config_mtime)) > int(os.stat(cookie_file).st_mtime):
recent_past = time.time() - 3600
os.utime(oscrc_file.name, (recent_past, recent_past))
def cookiejar_create(self, cookiejar_file, session):
cookie_jar = LWPCookieJar(cookiejar_file.name)
cookie_jar.set_cookie(Cookie(0, self.COOKIE_NAME, session,
None, False,
'', False, True,
'/', True,
True,
None, None, None, None, {}))
cookie_jar.save()
cookiejar_file.flush()
def execute(self, oscrc_file, command):
env = os.environ
env['OSC_CONFIG'] = oscrc_file.name
# Would be preferrable to stream incremental output, but python http
# server does not seem to support this easily.
result = subprocess.run(command, env=env, stdout=self.wfile, stderr=self.wfile)
return result.returncode == 0
def write_string(self, string):
self.wfile.write(string.encode('utf-8'))
def command_format_add(self, command, query):
format = None
if self.headers.get('Accept'):
format = self.headers.get('Accept').split('/', 2)[1]
if format != 'json' and format != 'yaml':
format = None
if not format and 'format' in query:
format = query['format'][0]
if format:
command.append('--format')
command.append(format)
def handle_origin_config(self, args, query):
command = ['osc', 'origin', '-p', args[0], 'config']
if 'origins-only' in query:
command.append('--origins-only')
return command
def handle_origin_history(self, args, query):
command = ['osc', 'origin', '-p', args[0], 'history']
self.command_format_add(command, query)
if len(args) > 1:
command.append(args[1])
return command
def handle_origin_list(self, args, query):
command = ['osc', 'origin', '-p', args[0], 'list']
if 'force-refresh' in query:
command.append('--force-refresh')
self.command_format_add(command, query)
return command
def handle_origin_package(self, args, query):
command = ['osc', 'origin', '-p', args[0], 'package']
if 'debug' in query:
command.append('--debug')
if len(args) > 1:
command.append(args[1])
return command
def handle_origin_potentials(self, args, query):
command = ['osc', 'origin', '-p', args[0], 'potentials']
self.command_format_add(command, query)
if len(args) > 1:
command.append(args[1])
return command
def handle_origin_projects(self, args, query):
command = ['osc', 'origin', 'projects']
self.command_format_add(command, query)
return command
def handle_origin_report(self, args, query):
command = ['osc', 'origin', '-p', args[0], 'report']
if 'force-refresh' in query:
command.append('--force-refresh')
return command
def handle_package_diff(self, args, query):
# source_project source_package target_project [target_package] [source_revision] [target_revision]
command = ['osc', 'rdiff', args[0], args[1], args[2]] # len(args) == 3
if len(args) >= 4:
command.append(args[3]) # target_package
if len(args) >= 5:
command.append('--revision')
command.append(':'.join(args[4:6]))
return command
def handle_request_submit(self, args, query, data):
command = ['osc', 'sr', args[0], args[1], args[2]]
command.append('-m')
if 'message' in query and query['message'][0]:
command.append(query['message'][0])
else:
command.append('created via operator')
command.append('--yes')
return [command]
def staging_command(self, project, subcommand):
return ['osc', 'staging', '-p', project, subcommand]
def handle_staging_select(self, args, query, data):
for staging, requests in data['selection'].items():
command = self.staging_command(data['project'], 'select')
if 'move' in data and data['move']:
command.append('--move')
command.append(staging)
command.extend(requests)
yield command
class OSCRequestEnvironment(object):
def __init__(self, handler, user=None, require_session=True):
self.handler = handler
self.user = user
self.require_session = require_session
def __enter__(self):
apiurl = self.handler.apiurl_get()
origin_domain = self.handler.origin_domain_get()
if not apiurl or (not self.handler.apiurl and origin_domain and not apiurl.endswith(origin_domain)):
self.handler.send_response(400)
self.handler.end_headers()
if not apiurl:
raise OSCRequestEnvironmentException('unable to determine apiurl')
else:
raise OSCRequestEnvironmentException('origin does not match host domain')
session = self.handler.session_get()
if self.require_session and not session:
self.handler.send_response(401)
self.handler.end_headers()
raise OSCRequestEnvironmentException('unable to determine session')
if self.handler.debug:
print('apiurl: {}'.format(apiurl))
print('session: {}'.format(session))
self.handler.send_response(200)
self.handler.send_header('Content-type', 'text/plain')
if origin_domain:
self.handler.send_header('Access-Control-Allow-Credentials', 'true')
self.handler.send_header('Access-Control-Allow-Origin', self.handler.headers.get('Origin'))
self.cookiejar_file = tempfile.NamedTemporaryFile()
self.oscrc_file = tempfile.NamedTemporaryFile()
self.cookiejar_file.__enter__()
self.oscrc_file.__enter__()
self.handler.oscrc_create(self.oscrc_file, apiurl, self.cookiejar_file, self.user)
self.handler.cookiejar_create(self.cookiejar_file, session)
return self.oscrc_file
def __exit__(self, exc_type, exc_val, exc_tb):
self.cookiejar_file.__exit__(exc_type, exc_val, exc_tb)
self.oscrc_file.__exit__(exc_type, exc_val, exc_tb)
class OSCRequestEnvironmentException(Exception):
pass
def main(args):
conf.get_config() # Allow sentry DSN to be available.
sentry_sdk = sentry_init()
RequestHandler.apiurl = args.apiurl
RequestHandler.session = args.session
RequestHandler.debug = args.debug
with ThreadedHTTPServer((args.host, args.port), RequestHandler) as httpd:
print('listening on {}:{}'.format(args.host, args.port))
httpd.serve_forever()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='OBS Operator server used to perform staging operations.')
parser.set_defaults(func=main)
parser.add_argument('--host', default='', help='host name to which to bind')
parser.add_argument('--port', type=int, default=8080, help='port number to which to bind')
parser.add_argument('-A', '--apiurl',
help='OBS instance API URL to use instead of basing from request origin')
parser.add_argument('--session',
help='session cookie value to use instead of any passed cookie')
parser.add_argument('-d', '--debug', action='store_true',
help='print debugging information')
args = parser.parse_args()
sys.exit(args.func(args))