app.py 29 KB

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