app.py 30 KB

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