app.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  1. #!/usr/bin/env python3
  2. import os
  3. import subprocess
  4. import json
  5. import pathlib
  6. import shutil
  7. import glob
  8. import time
  9. import fcntl
  10. import base64
  11. import hashlib
  12. from distutils.dir_util import copy_tree
  13. from flask import Flask, render_template, request, send_from_directory, render_template_string, jsonify, redirect
  14. from threading import Thread, Lock
  15. import sys
  16. import re
  17. import requests
  18. from logging.config import dictConfig
  19. dictConfig({
  20. 'version': 1,
  21. 'formatters': {'default': {
  22. 'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
  23. }},
  24. 'handlers': {'wsgi': {
  25. 'class': 'logging.StreamHandler',
  26. 'stream': 'ext://flask.logging.wsgi_errors_stream',
  27. 'formatter': 'default'
  28. }},
  29. 'root': {
  30. 'level': 'INFO',
  31. 'handlers': ['wsgi']
  32. }
  33. })
  34. import ap_git
  35. import metadata_manager
  36. # run at lower priority
  37. os.nice(20)
  38. import optparse
  39. parser = optparse.OptionParser("app.py")
  40. parser.add_option("", "--basedir", type="string",
  41. default=os.path.abspath(os.path.join(os.path.dirname(__file__),"..","base")),
  42. help="base directory")
  43. cmd_opts, cmd_args = parser.parse_args()
  44. # define directories
  45. basedir = os.path.abspath(cmd_opts.basedir)
  46. sourcedir = os.path.join(basedir, 'ardupilot')
  47. outdir_parent = os.path.join(basedir, 'builds')
  48. tmpdir_parent = os.path.join(basedir, 'tmp')
  49. appdir = os.path.dirname(__file__)
  50. builds_dict = {}
  51. REMOTES = None
  52. # LOCKS
  53. queue_lock = Lock()
  54. try:
  55. repo = ap_git.GitRepo(sourcedir)
  56. except FileNotFoundError:
  57. repo = ap_git.GitRepo.clone(
  58. source="https://github.com/ardupilot/ardupilot.git",
  59. dest=sourcedir,
  60. recurse_submodules=True,
  61. )
  62. ap_src_metadata_fetcher = metadata_manager.APSourceMetadataFetcher(
  63. ap_repo_path=sourcedir
  64. )
  65. versions_fetcher = metadata_manager.VersionsFetcher(
  66. remotes_json_path=os.path.join(basedir, 'configs', 'remotes.json')
  67. )
  68. def load_remotes():
  69. versions_fetcher.reload_remotes_json()
  70. added_remotes = 0
  71. for remote_info in versions_fetcher.get_all_remotes_info():
  72. try:
  73. repo.remote_add(remote=remote_info.name, url=remote_info.url)
  74. except ap_git.DuplicateRemoteError:
  75. app.logger.info(
  76. f"Remote '{remote_info.name}' already exists. "
  77. f"Updating url to '{remote_info.url}'."
  78. )
  79. repo.remote_set_url(remote=remote_info.name, url=remote_info.url)
  80. added_remotes += 1
  81. app.logger.info(f"{added_remotes} remotes added to base repo")
  82. def remove_directory_recursive(dirname):
  83. '''remove a directory recursively'''
  84. app.logger.info('Removing directory ' + dirname)
  85. if not os.path.exists(dirname):
  86. return
  87. f = pathlib.Path(dirname)
  88. if f.is_file():
  89. f.unlink()
  90. else:
  91. shutil.rmtree(f, True)
  92. def create_directory(dir_path):
  93. '''create a directory, don't fail if it exists'''
  94. app.logger.info('Creating ' + dir_path)
  95. pathlib.Path(dir_path).mkdir(parents=True, exist_ok=True)
  96. def run_build(task, tmpdir, outdir, logpath):
  97. '''run a build with parameters from task'''
  98. remove_directory_recursive(tmpdir_parent)
  99. create_directory(tmpdir)
  100. tmp_src_dir = os.path.join(tmpdir, 'build_src')
  101. source_repo = ap_git.GitRepo.shallow_clone_at_commit_from_local(
  102. source=sourcedir,
  103. remote=task['remote'],
  104. commit_ref=task['git_hash_short'],
  105. dest=tmp_src_dir
  106. )
  107. # update submodules in temporary source directory
  108. source_repo.submodule_update(init=True, recursive=True, force=True)
  109. # checkout to the commit pointing to the requested commit
  110. source_repo.checkout_remote_commit_ref(
  111. remote=task['remote'],
  112. commit_ref=task['git_hash_short'],
  113. force=True,
  114. hard_reset=True,
  115. clean_working_tree=True
  116. )
  117. if not os.path.isfile(os.path.join(outdir, 'extra_hwdef.dat')):
  118. app.logger.error('Build aborted, missing extra_hwdef.dat')
  119. app.logger.info('Appending to build.log')
  120. with open(logpath, 'a') as log:
  121. log.write('Setting vehicle to: ' + task['vehicle'].capitalize() + '\n')
  122. log.flush()
  123. # setup PATH to point at our compiler
  124. env = os.environ.copy()
  125. bindir1 = os.path.abspath(os.path.join(appdir, "..", "bin"))
  126. bindir2 = os.path.abspath(os.path.join(appdir, "..", "gcc", "bin"))
  127. cachedir = os.path.abspath(os.path.join(appdir, "..", "cache"))
  128. env["PATH"] = bindir1 + ":" + bindir2 + ":" + env["PATH"]
  129. env['CCACHE_DIR'] = cachedir
  130. app.logger.info('Running waf configure')
  131. log.write('Running waf configure\n')
  132. log.flush()
  133. subprocess.run(['python3', './waf', 'configure',
  134. '--board', task['board'],
  135. '--out', tmpdir,
  136. '--extra-hwdef', task['extra_hwdef']],
  137. cwd = tmp_src_dir,
  138. env=env,
  139. stdout=log, stderr=log, shell=False)
  140. app.logger.info('Running clean')
  141. log.write('Running clean\n')
  142. log.flush()
  143. subprocess.run(['python3', './waf', 'clean'],
  144. cwd = tmp_src_dir,
  145. env=env,
  146. stdout=log, stderr=log, shell=False)
  147. app.logger.info('Running build')
  148. log.write('Running build\n')
  149. log.flush()
  150. subprocess.run(['python3', './waf', task['vehicle']],
  151. cwd = tmp_src_dir,
  152. env=env,
  153. stdout=log, stderr=log, shell=False)
  154. log.write('done build\n')
  155. log.flush()
  156. def sort_json_files(reverse=False):
  157. json_files = list(filter(os.path.isfile,
  158. glob.glob(os.path.join(outdir_parent,
  159. '*', 'q.json'))))
  160. json_files.sort(key=lambda x: os.path.getmtime(x), reverse=reverse)
  161. return json_files
  162. def check_queue():
  163. '''thread to continuously run queued builds'''
  164. queue_lock.acquire()
  165. json_files = sort_json_files()
  166. queue_lock.release()
  167. if len(json_files) == 0:
  168. return
  169. # remove multiple build requests from same ip address (keep newest)
  170. queue_lock.acquire()
  171. ip_list = []
  172. for f in json_files:
  173. file = json.loads(open(f).read())
  174. ip_list.append(file['ip'])
  175. seen = set()
  176. ip_list.reverse()
  177. for index, value in enumerate(ip_list):
  178. if value in seen:
  179. file = json.loads(open(json_files[-index-1]).read())
  180. outdir_to_delete = os.path.join(outdir_parent, file['token'])
  181. remove_directory_recursive(outdir_to_delete)
  182. else:
  183. seen.add(value)
  184. queue_lock.release()
  185. if len(json_files) == 0:
  186. return
  187. # open oldest q.json file
  188. json_files = sort_json_files()
  189. taskfile = json_files[0]
  190. app.logger.info('Opening ' + taskfile)
  191. task = json.loads(open(taskfile).read())
  192. app.logger.info('Removing ' + taskfile)
  193. os.remove(taskfile)
  194. outdir = os.path.join(outdir_parent, task['token'])
  195. tmpdir = os.path.join(tmpdir_parent, task['token'])
  196. logpath = os.path.abspath(os.path.join(outdir, 'build.log'))
  197. app.logger.info("LOGPATH: %s" % logpath)
  198. try:
  199. # run build and rename build directory
  200. app.logger.info('MIR: Running build ' + str(task))
  201. run_build(task, tmpdir, outdir, logpath)
  202. app.logger.info('Copying build files from %s to %s',
  203. os.path.join(tmpdir, task['board']),
  204. outdir)
  205. copy_tree(os.path.join(tmpdir, task['board'], 'bin'), outdir)
  206. app.logger.info('Build successful!')
  207. remove_directory_recursive(tmpdir)
  208. except Exception as ex:
  209. app.logger.info('Build failed: ', ex)
  210. pass
  211. open(logpath,'a').write("\nBUILD_FINISHED\n")
  212. def file_age(fname):
  213. '''return file age in seconds'''
  214. return time.time() - os.stat(fname).st_mtime
  215. def remove_old_builds():
  216. '''as a cleanup, remove any builds older than 24H'''
  217. for f in os.listdir(outdir_parent):
  218. bdir = os.path.join(outdir_parent, f)
  219. if os.path.isdir(bdir) and file_age(bdir) > 24 * 60 * 60:
  220. remove_directory_recursive(bdir)
  221. time.sleep(5)
  222. def queue_thread():
  223. while True:
  224. try:
  225. check_queue()
  226. remove_old_builds()
  227. except Exception as ex:
  228. app.logger.error('Failed queue: ', ex)
  229. pass
  230. def get_build_progress(build_id, build_status):
  231. '''return build progress on scale of 0 to 100'''
  232. if build_status in ['Pending', 'Error']:
  233. return 0
  234. if build_status == 'Finished':
  235. return 100
  236. log_file_path = os.path.join(outdir_parent,build_id,'build.log')
  237. app.logger.info('Opening ' + log_file_path)
  238. build_log = open(log_file_path, encoding='utf-8').read()
  239. compiled_regex = re.compile(r'(\[\D*(\d+)\D*\/\D*(\d+)\D*\])')
  240. all_matches = compiled_regex.findall(build_log)
  241. if (len(all_matches) < 1):
  242. return 0
  243. completed_steps, total_steps = all_matches[-1][1:]
  244. if (int(total_steps) < 20):
  245. # these steps are just little compilation and linking that happen at initialisation
  246. # these do not contribute significant percentage to overall build progress
  247. return 1
  248. if (int(total_steps) < 200):
  249. # these steps are for building the OS
  250. # we give this phase 4% weight in the whole build progress
  251. return (int(completed_steps) * 4 // int(total_steps)) + 1
  252. # these steps are the major part of the build process
  253. # we give 95% of weight to these
  254. return (int(completed_steps) * 95 // int(total_steps)) + 5
  255. def get_build_status(build_id):
  256. build_id_split = build_id.split(':')
  257. if len(build_id_split) < 2:
  258. raise Exception('Invalid build id')
  259. if os.path.exists(os.path.join(outdir_parent,build_id,'q.json')):
  260. status = "Pending"
  261. elif not os.path.exists(os.path.join(outdir_parent,build_id,'build.log')):
  262. status = "Error"
  263. else:
  264. log_file_path = os.path.join(outdir_parent,build_id,'build.log')
  265. app.logger.info('Opening ' + log_file_path)
  266. build_log = open(log_file_path, encoding='utf-8').read()
  267. if build_log.find("'%s' finished successfully" % build_id_split[0].lower()) != -1:
  268. status = "Finished"
  269. elif build_log.find('The configuration failed') != -1 or build_log.find('Build failed') != -1 or build_log.find('compilation terminated') != -1:
  270. status = "Failed"
  271. elif build_log.find('BUILD_FINISHED') == -1:
  272. status = "Running"
  273. else:
  274. status = "Failed"
  275. return status
  276. def update_build_dict():
  277. '''update the build_dict dictionary which keeps track of status of all builds'''
  278. global builds_dict
  279. # get list of directories
  280. blist = []
  281. for b in os.listdir(outdir_parent):
  282. if os.path.isdir(os.path.join(outdir_parent,b)):
  283. blist.append(b)
  284. #remove deleted builds from build_dict
  285. for build in builds_dict:
  286. if build not in blist:
  287. builds_dict.pop(build, None)
  288. for b in blist:
  289. build_id_split = b.split(':')
  290. if len(build_id_split) < 2:
  291. continue
  292. build_info = builds_dict.get(b, None)
  293. # add an entry for the build in build_dict if not exists
  294. if (build_info is None):
  295. build_info = {}
  296. build_info['vehicle'] = build_id_split[0].capitalize()
  297. build_info['board'] = build_id_split[1]
  298. feature_file = os.path.join(outdir_parent, b, 'selected_features.json')
  299. app.logger.info('Opening ' + feature_file)
  300. selected_features_dict = json.loads(open(feature_file).read())
  301. selected_features = selected_features_dict['selected_features']
  302. build_info['git_hash_short'] = selected_features_dict['git_hash_short']
  303. features = ''
  304. for feature in selected_features:
  305. if features == '':
  306. features = features + feature
  307. else:
  308. features = features + ", " + feature
  309. build_info['features'] = features
  310. age_min = int(file_age(os.path.join(outdir_parent,b))/60.0)
  311. build_info['age'] = "%u:%02u" % ((age_min // 60), age_min % 60)
  312. # refresh build status only if it was pending, running or not initialised
  313. if (build_info.get('status', None) in ['Pending', 'Running', None]):
  314. build_info['status'] = get_build_status(b)
  315. build_info['progress'] = get_build_progress(b, build_info['status'])
  316. # update dictionary entry
  317. builds_dict[b] = build_info
  318. temp_list = sorted(list(builds_dict.items()), key=lambda x: os.path.getmtime(os.path.join(outdir_parent,x[0])), reverse=True)
  319. builds_dict = {ele[0] : ele[1] for ele in temp_list}
  320. def create_status():
  321. '''create status.json'''
  322. global builds_dict
  323. update_build_dict()
  324. tmpfile = os.path.join(outdir_parent, "status.tmp")
  325. statusfile = os.path.join(outdir_parent, "status.json")
  326. json_object = json.dumps(builds_dict)
  327. with open(tmpfile, "w") as outfile:
  328. outfile.write(json_object)
  329. os.replace(tmpfile, statusfile)
  330. def status_thread():
  331. while True:
  332. try:
  333. create_status()
  334. except Exception as ex:
  335. app.logger.info(ex)
  336. pass
  337. time.sleep(3)
  338. app = Flask(__name__, template_folder='templates')
  339. if not os.path.isdir(outdir_parent):
  340. create_directory(outdir_parent)
  341. try:
  342. lock_file = open(os.path.join(basedir, "queue.lck"), "w")
  343. fcntl.flock(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
  344. app.logger.info("Got queue lock")
  345. # we only want one set of threads
  346. thread = Thread(target=queue_thread, args=())
  347. thread.daemon = True
  348. thread.start()
  349. status_thread = Thread(target=status_thread, args=())
  350. status_thread.daemon = True
  351. status_thread.start()
  352. except IOError:
  353. app.logger.info("No queue lock")
  354. load_remotes()
  355. app.logger.info('Python version is: %s' % sys.version)
  356. def get_auth_token():
  357. try:
  358. # try to read the secret token from the file
  359. with open(os.path.join(basedir, 'secrets', 'reload_token'), 'r') as file:
  360. token = file.read().strip()
  361. return token
  362. except (FileNotFoundError, PermissionError):
  363. app.logger.error("Couldn't open token file. Checking environment for token.")
  364. # if the file does not exist, check the environment variable
  365. return os.getenv('CBS_REMOTES_RELOAD_TOKEN')
  366. @app.route('/refresh_remotes', methods=['POST'])
  367. def refresh_remotes():
  368. auth_token = get_auth_token()
  369. if auth_token is None:
  370. app.logger.error("Couldn't retrieve authorization token")
  371. return "Internal Server Error", 500
  372. token = request.get_json().get('token')
  373. if not token or token != auth_token:
  374. return "Unauthorized", 401
  375. load_remotes()
  376. return "Successfully refreshed remotes", 200
  377. @app.route('/generate', methods=['GET', 'POST'])
  378. def generate():
  379. try:
  380. chosen_version = request.form['version']
  381. chosen_remote, chosen_commit_reference = chosen_version.split('/', 1)
  382. chosen_vehicle = request.form['vehicle']
  383. chosen_version_info = versions_fetcher.get_version_info(
  384. vehicle=chosen_vehicle,
  385. remote=chosen_remote,
  386. commit_ref=chosen_commit_reference
  387. )
  388. if chosen_version_info is None:
  389. raise Exception("Commit reference invalid or not listed to be built for given vehicle for remote")
  390. chosen_board = request.form['board']
  391. boards_at_commit, _ = ap_src_metadata_fetcher.get_boards_at_commit(
  392. remote=chosen_remote,
  393. commit_ref=chosen_commit_reference
  394. )
  395. if chosen_board not in boards_at_commit:
  396. raise Exception("bad board")
  397. #ToDo - maybe have the if-statement to check if it's changed.
  398. build_options = ap_src_metadata_fetcher.get_build_options_at_commit(
  399. remote=chosen_remote,
  400. commit_ref=chosen_commit_reference
  401. )
  402. # fetch features from user input
  403. extra_hwdef = []
  404. feature_list = []
  405. selected_features = []
  406. app.logger.info('Fetching features from user input')
  407. # add all undefs at the start
  408. for f in build_options:
  409. extra_hwdef.append('undef %s' % f.define)
  410. for f in build_options:
  411. if f.label not in request.form or request.form[f.label] != '1':
  412. extra_hwdef.append('define %s 0' % f.define)
  413. else:
  414. extra_hwdef.append('define %s 1' % f.define)
  415. feature_list.append(f.description)
  416. selected_features.append(f.label)
  417. extra_hwdef = '\n'.join(extra_hwdef)
  418. spaces = '\n'
  419. feature_list = spaces.join(feature_list)
  420. selected_features_dict = {}
  421. selected_features_dict['selected_features'] = selected_features
  422. queue_lock.acquire()
  423. # create extra_hwdef.dat file and obtain md5sum
  424. app.logger.info('Creating ' +
  425. os.path.join(outdir_parent, 'extra_hwdef.dat'))
  426. file = open(os.path.join(outdir_parent, 'extra_hwdef.dat'), 'w')
  427. app.logger.info('Writing\n' + extra_hwdef)
  428. file.write(extra_hwdef)
  429. file.close()
  430. extra_hwdef_md5sum = hashlib.md5(extra_hwdef.encode('utf-8')).hexdigest()
  431. app.logger.info('Removing ' +
  432. os.path.join(outdir_parent, 'extra_hwdef.dat'))
  433. os.remove(os.path.join(outdir_parent, 'extra_hwdef.dat'))
  434. new_git_hash = repo.commit_id_for_remote_ref(
  435. remote=chosen_remote,
  436. commit_ref=chosen_commit_reference
  437. )
  438. git_hash_short = new_git_hash[:10]
  439. app.logger.info('Git hash = ' + new_git_hash)
  440. selected_features_dict['git_hash_short'] = git_hash_short
  441. # create directories using concatenated token
  442. # of vehicle, board, git-hash of source, and md5sum of hwdef
  443. token = chosen_vehicle.lower() + ':' + chosen_board + ':' + new_git_hash + ':' + extra_hwdef_md5sum
  444. app.logger.info('token = ' + token)
  445. outdir = os.path.join(outdir_parent, token)
  446. if os.path.isdir(outdir):
  447. app.logger.info('Build already exists')
  448. else:
  449. create_directory(outdir)
  450. # create build.log
  451. build_log_info = ('Vehicle: ' + chosen_vehicle +
  452. '\nBoard: ' + chosen_board +
  453. '\nRemote: ' + chosen_remote +
  454. '\ngit-sha: ' + git_hash_short +
  455. '\nVersion: ' + chosen_version_info.release_type + '-' + chosen_version_info.version_number +
  456. '\nSelected Features:\n' + feature_list +
  457. '\n\nWaiting for build to start...\n\n')
  458. app.logger.info('Creating build.log')
  459. build_log = open(os.path.join(outdir, 'build.log'), 'w')
  460. build_log.write(build_log_info)
  461. build_log.close()
  462. # create hwdef.dat
  463. app.logger.info('Opening ' +
  464. os.path.join(outdir, 'extra_hwdef.dat'))
  465. file = open(os.path.join(outdir, 'extra_hwdef.dat'),'w')
  466. app.logger.info('Writing\n' + extra_hwdef)
  467. file.write(extra_hwdef)
  468. file.close()
  469. # fill dictionary of variables and create json file
  470. task = {}
  471. task['token'] = token
  472. task['remote'] = chosen_remote
  473. task['git_hash_short'] = git_hash_short
  474. task['version'] = chosen_version_info.release_type + '-' + chosen_version_info.version_number
  475. task['extra_hwdef'] = os.path.join(outdir, 'extra_hwdef.dat')
  476. task['vehicle'] = chosen_vehicle.lower()
  477. task['board'] = chosen_board
  478. task['ip'] = request.remote_addr
  479. app.logger.info('Opening ' + os.path.join(outdir, 'q.json'))
  480. jfile = open(os.path.join(outdir, 'q.json'), 'w')
  481. app.logger.info('Writing task file to ' +
  482. os.path.join(outdir, 'q.json'))
  483. jfile.write(json.dumps(task, separators=(',\n', ': ')))
  484. jfile.close()
  485. # create selected_features.dat for status table
  486. feature_file = open(os.path.join(outdir, 'selected_features.json'), 'w')
  487. app.logger.info('Writing\n' + os.path.join(outdir, 'selected_features.json'))
  488. feature_file.write(json.dumps(selected_features_dict))
  489. feature_file.close()
  490. queue_lock.release()
  491. base_url = request.url_root
  492. app.logger.info(base_url)
  493. app.logger.info('Redirecting to /viewlog')
  494. return redirect('/viewlog/'+token)
  495. except Exception as ex:
  496. app.logger.error(ex)
  497. return render_template('error.html', ex=ex)
  498. @app.route('/add_build')
  499. def add_build():
  500. app.logger.info('Rendering add_build.html')
  501. return render_template('add_build.html')
  502. def filter_build_options_by_category(build_options, category):
  503. return sorted([f for f in build_options if f.category == category], key=lambda x: x.description.lower())
  504. def parse_build_categories(build_options):
  505. return sorted(list(set([f.category for f in build_options])))
  506. @app.route('/', defaults={'token': None}, methods=['GET'])
  507. @app.route('/viewlog/<token>', methods=['GET'])
  508. def home(token):
  509. if token:
  510. app.logger.info("Showing log for build id " + token)
  511. app.logger.info('Rendering index.html')
  512. return render_template('index.html', token=token)
  513. @app.route("/builds/<path:name>")
  514. def download_file(name):
  515. app.logger.info('Downloading %s' % name)
  516. return send_from_directory(os.path.join(basedir,'builds'), name, as_attachment=False)
  517. @app.route("/boards_and_features/<string:vehicle_name>/<string:remote_name>/<string:commit_reference>", methods=['GET'])
  518. def boards_and_features(vehicle_name, remote_name, commit_reference):
  519. commit_reference = base64.urlsafe_b64decode(commit_reference).decode()
  520. if not versions_fetcher.is_version_listed(vehicle=vehicle_name, remote=remote_name, commit_ref=commit_reference):
  521. return "Bad request. Commit reference not allowed to build for the vehicle.", 400
  522. app.logger.info('Board list and build options requested for %s %s %s' % (vehicle_name, remote_name, commit_reference))
  523. # getting board list for the branch
  524. with repo.get_checkout_lock():
  525. repo.checkout_remote_commit_ref(
  526. remote=remote_name,
  527. commit_ref=commit_reference,
  528. force=True,
  529. hard_reset=True,
  530. clean_working_tree=True,
  531. )
  532. (boards, default_board) = ap_src_metadata_fetcher.get_boards_at_commit(
  533. remote=remote_name,
  534. commit_ref=commit_reference
  535. )
  536. options = ap_src_metadata_fetcher.get_build_options_at_commit(
  537. remote=remote_name,
  538. commit_ref=commit_reference
  539. ) # this is a list of Feature() objects defined in build_options.py
  540. # parse the set of categories from these objects
  541. categories = parse_build_categories(options)
  542. features = []
  543. for category in categories:
  544. filtered_options = filter_build_options_by_category(options, category)
  545. category_options = [] # options belonging to a given category
  546. for option in filtered_options:
  547. category_options.append({
  548. 'label' : option.label,
  549. 'description' : option.description,
  550. 'default' : option.default,
  551. 'define' : option.define,
  552. 'dependency' : option.dependency,
  553. })
  554. features.append({
  555. 'name' : category,
  556. 'options' : category_options,
  557. })
  558. # creating result dictionary
  559. result = {
  560. 'boards' : boards,
  561. 'default_board' : default_board,
  562. 'features' : features,
  563. }
  564. # return jsonified result dict
  565. return jsonify(result)
  566. @app.route("/get_versions/<string:vehicle_name>", methods=['GET'])
  567. def get_versions(vehicle_name):
  568. versions = list()
  569. for version_info in versions_fetcher.get_versions_for_vehicle(vehicle_name=vehicle_name):
  570. if version_info.release_type == "latest":
  571. title = f"Latest ({version_info.remote})"
  572. else:
  573. title = f"{version_info.release_type} {version_info.version_number} ({version_info.remote})"
  574. id = f"{version_info.remote}/{version_info.commit_ref}"
  575. versions.append({
  576. "title" : title,
  577. "id" : id,
  578. })
  579. return jsonify(sorted(versions, key=lambda x: x['title']))
  580. @app.route("/get_vehicles")
  581. def get_vehicles():
  582. return jsonify(versions_fetcher.get_all_vehicles_sorted_uniq())
  583. @app.route("/get_defaults/<string:vehicle_name>/<string:remote_name>/<string:commit_reference>/<string:board_name>", methods = ['GET'])
  584. def get_deafults(vehicle_name, remote_name, commit_reference, board_name):
  585. # Heli is built on copter
  586. if vehicle_name == "Heli":
  587. vehicle_name = "Copter"
  588. commit_reference = base64.urlsafe_b64decode(commit_reference).decode()
  589. version_info = versions_fetcher.get_version_info(vehicle=vehicle_name, remote=remote_name, commit_ref=commit_reference)
  590. if version_info is None:
  591. return "Bad request. Commit reference %s is not allowed for builds for the %s for %s remote." % (commit_reference, vehicle_name, remote_name), 400
  592. artifacts_dir = version_info.ap_build_artifacts_url
  593. if artifacts_dir is None:
  594. return "Couldn't find artifacts for requested release/branch/commit on ardupilot server", 404
  595. url_to_features_txt = artifacts_dir + '/' + board_name + '/features.txt'
  596. response = requests.get(url_to_features_txt, timeout=30)
  597. if not response.status_code == 200:
  598. return ("Could not retrieve features.txt for given vehicle, version and board combination (Status Code: %d, url: %s)" % (response.status_code, url_to_features_txt), response.status_code)
  599. # split response by new line character to get a list of defines
  600. result = response.text.split('\n')
  601. # omit the last two elements as they are always blank
  602. return jsonify(result[:-2])
  603. if __name__ == '__main__':
  604. app.run()