-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathlava_callback.py
executable file
·783 lines (685 loc) · 26.6 KB
/
lava_callback.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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
# SPDX-License-Identifier: LGPL-2.1-or-later
#
# Copyright (C) 2023,2024 Collabora Limited
# Author: Guillaume Tucker <[email protected]>
# Author: Denys Fedoryshchenko <[email protected]>
import os
import tempfile
import gzip
import json
import requests
import toml
import threading
import uvicorn
import jwt
import logging
import hashlib
from datetime import datetime, timedelta
from fastapi import FastAPI, HTTPException, Request, Header, Response
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from typing import Optional
import kernelci.api.helper
import kernelci.config
import kernelci.runtime.lava
import kernelci.storage
import kernelci.config
from concurrent.futures import ThreadPoolExecutor
SETTINGS = toml.load(os.getenv('KCI_SETTINGS', 'config/kernelci.toml'))
CONFIGS = kernelci.config.load(
SETTINGS.get('DEFAULT', {}).get('yaml_config', 'config')
)
SETTINGS_PREFIX = 'runtime'
YAMLCFG = kernelci.config.load_yaml('config')
app = FastAPI()
executor = ThreadPoolExecutor(max_workers=16)
class ManualCheckout(BaseModel):
commit: str
nodeid: Optional[str] = None
url: Optional[str] = None
branch: Optional[str] = None
commit: Optional[str] = None
jobfilter: Optional[list] = None
platformfilter: Optional[list] = None
class PatchSet(BaseModel):
nodeid: str
patchurl: Optional[list] = None
patch: Optional[list] = None
jobfilter: Optional[list] = None
platformfilter: Optional[list] = None
class JobRetry(BaseModel):
nodeid: str
class Metrics():
def __init__(self, kind):
self.kind = kind
self.metrics = {}
self.metrics['http_requests_total'] = 0
self.metrics['lava_callback_requests_total'] = 0
self.metrics['lava_callback_requests_authfail_total'] = 0
self.metrics['lava_callback_late_fail_total'] = 0
self.metrics['pipeline_api_auth_fail_total'] = 0
self.metrics['pipeline_api_requests_total'] = 0
self.lock = threading.Lock()
# Various internal metrics
def update(self):
with self.lock:
# This might not work as we have ASGI/WSGI server which have their own threads
self.metrics['executor_threads_active'] = executor._work_queue.qsize()
self.metrics['executor_threads_all'] = executor._max_workers
def add(self, key, value):
with self.lock:
if key not in self.metrics:
self.metrics[key] = 0
self.metrics[key] += value
def get(self, key):
self.update()
with self.lock:
return self.metrics.get(key, 0)
def all(self):
self.update()
with self.lock:
return self.metrics
def export(self):
counters = ['_total', '_counter', '_created']
self.update()
with self.lock:
promstr = ''
for key, value in self.metrics.items():
promstr += f'# HELP {key} {key}\n'
# if key doesn't end in _total, _counter - it is a gauge, otherwise counter
if not any([key.endswith(c) for c in counters]):
promstr += f'# TYPE {key} gauge\n'
else:
promstr += f'# TYPE {key} counter\n'
promstr += f'{key}{{kind="{self.kind}"}} {value}\n'
return promstr
metrics = Metrics('pipeline_callback')
def _get_api_helper(api_config_name, api_token):
api_config = CONFIGS['api'][api_config_name]
api = kernelci.api.get_api(api_config, api_token)
return kernelci.api.helper.APIHelper(api)
def _get_storage(storage_config_name):
storage_config = CONFIGS['storage_configs'][storage_config_name]
storage_cred = SETTINGS['storage'][storage_config_name]['storage_cred']
return kernelci.storage.get_storage(storage_config, storage_cred)
def _upload_file(storage, job_node, source_name, destination_name=None):
if not destination_name:
destination_name = source_name
upload_dir = '-'.join((job_node['name'], job_node['id']))
# remove GET parameters from destination_name
return storage.upload_single((source_name, destination_name), upload_dir)
def _upload_callback_data(data, job_node, storage):
filename = 'lava_callback.json.gz'
# Temporarily we dont remove log field
# data.pop('log', None)
# Ensure we don't leak secrets
data.pop('token', None)
# Create temporary file to store callback data as gzip'ed JSON
with tempfile.TemporaryDirectory() as tmp_dir:
# open gzip in explicit text mode to avoid platform-dependent line endings
with gzip.open(os.path.join(tmp_dir, filename), 'wt') as f:
serjson = json.dumps(data, indent=4)
f.write(serjson)
src = os.path.join(tmp_dir, filename)
return _upload_file(storage, job_node, src, filename)
def _upload_log(log_parser, job_node, storage):
# create temporary file to store log with gzip
id = job_node['id']
with tempfile.TemporaryDirectory(suffix=id) as tmp_dir:
# open gzip in explicit text mode to avoid platform-dependent line endings
with gzip.open(os.path.join(tmp_dir, 'lava_log.txt.gz'), 'wt') as f:
data = log_parser.get_text()
if not data or len(data) == 0:
return None
# Delete NULL characters from log data
data = data.replace('\x00', '')
# Sanitize log data from non-printable characters (except newline)
# replace them with '?', original still exists in cb data
data = ''.join([c if c.isprintable() or c == '\n' else
'?' for c in data])
f.write(data)
src = os.path.join(tmp_dir, 'lava_log.txt.gz')
return _upload_file(storage, job_node, src, 'log.txt.gz')
@app.get('/')
async def read_root():
page = '''
<html>
<head>
<title>KernelCI Pipeline Callback</title>
</head>
<body>
<h1>KernelCI Pipeline Callback</h1>
<p>This is a callback endpoint for the KernelCI pipeline.</p>
</body>
</html>
'''
return page
def async_job_submit(api_helper, node_id, job_callback):
'''
Heavy lifting is done in a separate thread to avoid blocking the callback
handler. This is not ideal as we don't have a way to report errors back to
the caller, but it's OK as LAVA don't care about the response.
'''
results = job_callback.get_results()
job_node = api_helper.api.node.get(node_id)
if not job_node:
metrics.add('lava_callback_late_fail_total', 1)
logging.error(f'Node {node_id} not found')
return
# TODO: Verify lab_name matches job node lab name
# Also extract job_id and compare with node job_id (future)
# Or at least first record job_id in node metadata
callback_data = job_callback.get_data()
log_parser = job_callback.get_log_parser()
job_result = job_callback.get_job_status()
device_id = job_callback.get_device_id()
storage_config_name = job_callback.get_meta('storage_config_name')
storage = _get_storage(storage_config_name)
log_txt_url = _upload_log(log_parser, job_node, storage)
if log_txt_url:
job_node['artifacts']['lava_log'] = log_txt_url
print(f"Log uploaded to {log_txt_url}")
else:
print("Failed to upload log")
metrics.add('lava_callback_late_fail_total', 1)
callback_json_url = _upload_callback_data(callback_data, job_node, storage)
if callback_json_url:
job_node['artifacts']['callback_data'] = callback_json_url
print(f"Callback data uploaded to {callback_json_url}")
else:
metrics.add('lava_callback_late_fail_total', 1)
# failed LAVA job should have result set to 'incomplete'
job_node['result'] = job_result
job_node['state'] = 'done'
if job_node.get('error_code') == 'node_timeout':
job_node['error_code'] = None
job_node['error_msg'] = None
if device_id:
job_node['data']['device'] = device_id
hierarchy = job_callback.get_hierarchy(results, job_node)
api_helper.submit_results(hierarchy, job_node)
def submit_job(api_helper, node_id, job_callback):
'''
Spawn a thread to do the job submission without blocking
the callback
'''
executor.submit(async_job_submit, api_helper, node_id, job_callback)
# POST /node/<node_id>
@app.post('/node/{node_id}')
async def callback(node_id: str, request: Request):
metrics.add('http_requests_total', 1)
metrics.add('lava_callback_requests_total', 1)
tokens = SETTINGS.get(SETTINGS_PREFIX)
if not tokens:
item = {}
item['message'] = 'No tokens configured'
return JSONResponse(content=item, status_code=500)
lab_token = request.headers.get('Authorization')
# return 401 if no token
if not lab_token:
metrics.add('lava_callback_requests_authfail_total', 1)
item = {}
item['message'] = 'Unauthorized'
return JSONResponse(content=item, status_code=401)
# iterate over tokens and check if value of one matches
# we might have runtime_token and callback_token
lab_name = None
for lab, tokens in tokens.items():
if tokens.get('runtime_token') == lab_token:
lab_name = lab
break
if tokens.get('callback_token') == lab_token:
lab_name = lab
break
if not lab_name:
metrics.add('lava_callback_requests_authfail_total', 1)
item = {}
item['message'] = 'Unauthorized'
return JSONResponse(content=item, status_code=401)
try:
data = await request.json()
except Exception as e:
logging.error(f'Error decoding JSON: {e}')
item = {}
item['message'] = 'Error decoding JSON'
return JSONResponse(content=item, status_code=400)
job_callback = kernelci.runtime.lava.Callback(data)
api_config_name = job_callback.get_meta('api_config_name')
api_token = os.getenv('KCI_API_TOKEN')
api_helper = _get_api_helper(api_config_name, api_token)
submit_job(api_helper, node_id, job_callback)
item = {}
item['message'] = 'OK'
return JSONResponse(content=item, status_code=202)
def decode_jwt(jwtstr):
'''
JWT secret stored at SETTINGS['jwt']['secret']
which means secret.toml file should have jwt section
with parameter secret= "<secret>"
'''
secret = SETTINGS.get('jwt', {}).get('secret')
if not secret:
logging.error('No JWT secret configured')
return None
return jwt.decode(jwtstr, secret, algorithms=['HS256'])
def validate_permissions(jwtoken, permission):
if not jwtoken:
return False
try:
decoded = decode_jwt(jwtoken)
except Exception as e:
logging.error(f'Error decoding JWT: {e}')
return False
if not decoded:
logging.error('Invalid JWT')
return False
permissions = decoded.get('permissions')
if not permissions:
logging.error('No permissions in JWT')
return False
if permission not in permissions:
logging.error(f'Permission {permission} not in JWT')
return False
return decoded
def find_parent_kind(node, api_helper, kind):
'''
Find parent node of a specific "kind" value
'''
parent_id = node.get('parent')
if not parent_id:
return None
parent_node = api_helper.api.node.get(parent_id)
if not parent_node:
return None
if parent_node.get('kind') == kind:
return parent_node
return find_parent_kind(parent_node, api_helper, kind)
def find_tree(url, branch):
'''
Find tree name from the URL and branch
'''
treename = None
for tree in YAMLCFG['trees']:
data = YAMLCFG['trees'].get(tree)
if data.get('url') == url:
treename = tree
if not treename:
return None
for bconfig in YAMLCFG['build_configs']:
data = YAMLCFG['build_configs'].get(bconfig)
if data.get('tree') == treename and data.get('branch') == branch:
return treename
return None
@app.post('/api/jobretry')
async def jobretry(data: JobRetry, request: Request,
Authorization: str = Header(None)):
'''
API call to assist in regression bisecting by retrying a specific job
retrieved from test results.
'''
metrics.add('http_requests_total', 1)
metrics.add('pipeline_api_requests_total', 1)
# return item
item = {}
# Validate JWT token from Authorization header
jwtoken = Authorization
decoded = validate_permissions(jwtoken, 'testretry')
if not decoded:
metrics.add('pipeline_api_auth_fail_total', 1)
item['message'] = 'Unauthorized'
return JSONResponse(content=item, status_code=401)
email = decoded.get('email')
logging.info(f"User {email} is retrying job {data.nodeid}")
api_config_name = SETTINGS.get('DEFAULT', {}).get('api_config')
if not api_config_name:
item['message'] = 'No default API name set'
return JSONResponse(content=item, status_code=500)
api_token = os.getenv('KCI_API_TOKEN')
api_helper = _get_api_helper(api_config_name, api_token)
try:
node = api_helper.api.node.get(data.nodeid)
except Exception as e:
logging.error(f'Error getting node {data.nodeid}: {e}')
item['message'] = 'Error getting node'
return JSONResponse(content=item, status_code=500)
if not node:
item['message'] = 'Node not found'
return JSONResponse(content=item, status_code=404)
if node['kind'] != 'job':
item['message'] = 'Node is not a job'
return JSONResponse(content=item, status_code=400)
knode = find_parent_kind(node, api_helper, 'kbuild')
if not knode:
item['message'] = 'Kernel build not found'
return JSONResponse(content=item, status_code=404)
jobfilter = [knode['name'], node['name']]
knode['jobfilter'] = jobfilter
knode['op'] = 'updated'
knode['data'].pop('artifacts', None)
# state - done, result - pass
if knode.get('state') != 'done':
item['message'] = 'Kernel build is not done'
return JSONResponse(content=item, status_code=400)
if knode.get('result') != 'pass':
item['message'] = 'Kernel build result is not pass'
return JSONResponse(content=item, status_code=400)
# remove created, updated, timeout, owner, submitter, usergroups
knode.pop('created', None)
knode.pop('updated', None)
knode.pop('timeout', None)
knode.pop('owner', None)
knode.pop('submitter', None)
knode.pop('usergroups', None)
evnode = {'data': knode}
# Now we can submit custom kbuild node to the API(pub/sub)
api_helper.api.send_event('node', evnode)
logging.info(f"Job retry for node {data.nodeid} submitted")
item['message'] = 'OK'
return JSONResponse(content=item, status_code=200)
def get_jobfilter(node, api_helper):
jobfilter = []
if node['kind'] != 'job':
jobnode = find_parent_kind(node, api_helper, 'job')
if not jobnode:
return None
else:
jobnode = node
kbuildnode = find_parent_kind(node, api_helper, 'kbuild')
if not kbuildnode:
return None
kbuildname = kbuildnode['name']
testname = jobnode['name']
jobfilter = [kbuildname, testname]
return jobfilter
def is_valid_commit_string(commit):
'''
Validate commit string format
'''
if not commit:
return False
if len(commit) < 7:
return False
if len(commit) > 40:
return False
if not all(c in '0123456789abcdef' for c in commit):
return False
return True
def is_job_exist(jobname):
'''
Check if job exists in the config
'''
for job in YAMLCFG['jobs']:
if job == jobname:
return True
return False
def is_platform_exist(platform):
'''
Check if platform exists in the config
'''
for p in YAMLCFG['platforms']:
if p == platform:
return True
return False
@app.post('/api/checkout')
async def checkout(data: ManualCheckout, request: Request,
Authorization: str = Header(None)):
'''
API call to assist in regression bisecting by manually checking out
a specific commit on a specific branch of a specific tree, retrieved
from test results.
User either supplies a node ID to checkout, or a tree URL, branch and
commit hash. In the latter case, the tree name is looked up in the
configuration file.
'''
metrics.add('http_requests_total', 1)
metrics.add('pipeline_api_requests_total', 1)
item = {}
# Validate JWT token from Authorization header
jwtoken = Authorization
decoded = validate_permissions(jwtoken, 'checkout')
if not decoded:
metrics.add('pipeline_api_auth_fail_total', 1)
item['message'] = 'Unauthorized'
return JSONResponse(content=item, status_code=401)
email = decoded.get('email')
if not email:
item['message'] = 'Unauthorized'
return JSONResponse(content=item, status_code=401)
logging.info(f"User {email} is checking out {data.nodeid} at custom commit {data.commit}")
api_config_name = SETTINGS.get('DEFAULT', {}).get('api_config')
if not api_config_name:
item['message'] = 'No default API name set'
return JSONResponse(content=item, status_code=500)
api_token = os.getenv('KCI_API_TOKEN')
api_helper = _get_api_helper(api_config_name, api_token)
# if user set node - we retrieve all the tree data from it
if data.nodeid:
node = api_helper.api.node.get(data.nodeid)
# validate commit string
if not is_valid_commit_string(data.commit):
item['message'] = 'Invalid commit format'
return JSONResponse(content=item, status_code=400)
if not node:
item['message'] = 'Node not found'
return JSONResponse(content=item, status_code=404)
try:
treename = node['data']['kernel_revision']['tree']
treeurl = node['data']['kernel_revision']['url']
branch = node['data']['kernel_revision']['branch']
commit = data.commit
except KeyError:
item['message'] = 'Node does not have kernel revision data'
return JSONResponse(content=item, status_code=400)
jobfilter = get_jobfilter(node, api_helper)
# TBD: platformfilter
else:
if not data.url or not data.branch or not data.commit:
item['message'] = 'Missing tree URL, branch or commit'
return JSONResponse(content=item, status_code=400)
if not is_valid_commit_string(data.commit):
item['message'] = 'Invalid commit format'
return JSONResponse(content=item, status_code=400)
treename = find_tree(data.url, data.branch)
if not treename:
item['message'] = 'Tree not found'
return JSONResponse(content=item, status_code=404)
treeurl = data.url
branch = data.branch
commit = data.commit
# validate jobfilter list
if data.jobfilter:
# to be on safe side restrict length of jobfilter to 8
if len(data.jobfilter) > 8:
item['message'] = 'Too many jobs in jobfilter'
return JSONResponse(content=item, status_code=400)
for jobname in data.jobfilter:
if not is_job_exist(jobname):
item['message'] = f'Job {jobname} not found'
return JSONResponse(content=item, status_code=404)
jobfilter = data.jobfilter
else:
jobfilter = None
if data.platformfilter:
# to be on safe side restrict length of platformfilter to 8
if len(data.platformfilter) > 8:
item['message'] = 'Too many platforms in platformfilter'
return JSONResponse(content=item, status_code=400)
for platform in data.platformfilter:
if not is_platform_exist(platform):
item['message'] = f'Platform {platform} not found'
return JSONResponse(content=item, status_code=404)
platform_filter = data.platformfilter
else:
platform_filter = None
# Now we can submit custom checkout node to the API
# Maybe add field who requested the checkout?
timeout = 300
checkout_timeout = datetime.utcnow() + timedelta(minutes=timeout)
treeidsrc = treeurl + branch + str(datetime.now())
treeid = hashlib.sha256(treeidsrc.encode()).hexdigest()
node = {
"kind": "checkout",
"name": "checkout",
"path": ["checkout"],
"data": {
"kernel_revision": {
"tree": treename,
"branch": branch,
"commit": commit,
"url": treeurl,
"tip_of_branch": False
}
},
"timeout": checkout_timeout.isoformat(),
"submitter": f'user:{email}',
"treeid": treeid,
}
if jobfilter:
node['jobfilter'] = jobfilter
if platform_filter:
node['platform_filter'] = platform_filter
r = api_helper.api.node.add(node)
if not r:
item['message'] = 'Failed to submit checkout node'
return JSONResponse(content=item, status_code=500)
else:
logging.info(f"Checkout node {r['id']} submitted")
item['message'] = 'OK'
item['node'] = r
return JSONResponse(content=item, status_code=200)
def validate_patch_url(patchurl):
'''
Validate patch URL
'''
if not patchurl:
return False
if not patchurl.startswith('http'):
return False
try:
r = requests.get(patchurl)
if r.status_code != 200:
return False
except Exception as e:
logging.error(f'Error fetching patch URL: {e}')
return False
return True
@app.post('/api/patchset')
async def patchset(data: PatchSet, request: Request,
Authorization: str = Header(None)):
'''
API call to test existing checkout with a patch(set)
Patch can be supplied as a URL or within the request body
'''
metrics.add('http_requests_total', 1)
metrics.add('pipeline_api_requests_total', 1)
item = {}
# Validate JWT token from Authorization header
jwtoken = Authorization
decoded = validate_permissions(jwtoken, 'patchset')
if not decoded:
metrics.add('pipeline_api_auth_fail_total', 1)
item['message'] = 'Unauthorized'
return JSONResponse(content=item, status_code=401)
email = decoded.get('email')
if not email:
item['message'] = 'Unauthorized'
return JSONResponse(content=item, status_code=401)
logging.info(f"User {email} is testing patchset on {data.nodeid}")
api_config_name = SETTINGS.get('DEFAULT', {}).get('api_config')
if not api_config_name:
item['message'] = 'No default API name set'
return JSONResponse(content=item, status_code=500)
api_token = os.getenv('KCI_API_TOKEN')
api_helper = _get_api_helper(api_config_name, api_token)
node = api_helper.api.node.get(data.nodeid)
if not node:
item['message'] = 'Node not found'
return JSONResponse(content=item, status_code=404)
if node['kind'] != 'checkout':
item['message'] = 'Node is not a checkout'
return JSONResponse(content=item, status_code=400)
# validate patch URL
if data.patchurl:
if isinstance(data.patchurl, list):
for patchurl in data.patchurl:
if not isinstance(patchurl, str):
item['message'] = 'Invalid patch URL element type'
return JSONResponse(content=item, status_code=400)
if not validate_patch_url(patchurl):
item['message'] = 'Invalid patch URL'
return JSONResponse(content=item, status_code=400)
else:
return 'Invalid patch URL type', 400
elif data.patch:
# We need to implement upload to storage and return URL
item['message'] = 'Not implemented yet'
return JSONResponse(content=item, status_code=501)
else:
item['message'] = 'Missing patch URL or patch'
return JSONResponse(content=item, status_code=400)
# Now we can submit custom patchset node to the API
# Maybe add field who requested the patchset?
timeout = 300
patchset_timeout = datetime.utcnow() + timedelta(minutes=timeout)
treeidsrc = node['data']['kernel_revision']['url'] + \
node['data']['kernel_revision']['branch'] + str(datetime.now())
treeid = hashlib.sha256(treeidsrc.encode()).hexdigest()
# copy node to newnode
newnode = node.copy()
# delete some fields, like id, created, updated, timeout
newnode.pop('id', None)
newnode.pop('created', None)
newnode.pop('updated', None)
newnode.pop('timeout', None)
newnode.pop('result', None)
newnode.pop('owner', None)
newnode['name'] = 'patchset'
newnode['path'] = ['checkout', 'patchset']
newnode['group'] = 'patchset'
newnode['state'] = 'running'
newnode['parent'] = node['id']
newnode['artifacts'] = {}
newnode['timeout'] = patchset_timeout.isoformat()
newnode['submitter'] = f'user:{email}'
newnode['treeid'] = treeid
if data.patchurl:
for i, patchurl in enumerate(data.patchurl):
newnode['artifacts'][f'patch{i}'] = patchurl
if data.jobfilter:
newnode['jobfilter'] = data.jobfilter
if data.platformfilter:
newnode['platform_filter'] = data.platformfilter
r = api_helper.api.node.add(newnode)
if not r:
item['message'] = 'Failed to submit patchset node'
return JSONResponse(content=item, status_code=500)
else:
logging.info(f"Patchset node {r['id']} submitted")
item['message'] = 'OK'
item['node'] = r
return JSONResponse(content=item, status_code=200)
@app.get('/api/metrics')
async def apimetrics():
'''
Prometheus compatible metrics export
/api/metrics
http_requests_total{kind="pipeline_callback"} 4633433
lava_callback_requests_total{kind="pipeline_callback"} 4633433
lava_callback_requests_authfail{kind="pipeline_callback"} 0
lava_callback_late_fail{kind="pipeline_callback"} 0
'''
metrics.add('http_requests_total', 1)
export_str = metrics.export()
return Response(content=export_str, media_type='text/plain')
# Default built-in development server, not suitable for production
if __name__ == '__main__':
tokens = SETTINGS.get(SETTINGS_PREFIX)
if not tokens:
print('No tokens configured in toml file')
jwt_secret = SETTINGS.get('jwt', {}).get('secret')
if not jwt_secret:
print('No JWT secret configured')
api_token = os.getenv('KCI_API_TOKEN')
if not api_token:
print('No API token set')
uvicorn.run(app, host='0.0.0.0', port=8000)