app.py 32 KB

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