app.py 32 KB

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