app.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  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 hashlib
  11. import fnmatch
  12. from distutils.dir_util import copy_tree
  13. from flask import Flask, render_template, request, send_from_directory, render_template_string
  14. from threading import Thread, Lock
  15. import sys
  16. # run at lower priority
  17. os.nice(20)
  18. #BOARDS = [ 'BeastF7', 'BeastH7' ]
  19. appdir = os.path.dirname(__file__)
  20. VEHICLES = [ 'Copter', 'Plane', 'Rover', 'Sub', 'Tracker', 'Blimp', 'Heli']
  21. default_vehicle = 'Copter'
  22. chosen_vehicle = default_vehicle
  23. BRANCHES = {
  24. 'upstream/master' : 'Latest',
  25. 'upstream/Plane-4.2' : 'Plane 4.2 stable',
  26. 'upstream/Copter-4.2' : 'Copter 4.2 stable',
  27. 'upstream/Rover-4.2' : 'Rover 4.2 stable'
  28. }
  29. default_branch = 'upstream/master'
  30. chosen_branch = default_branch
  31. def get_boards_from_ardupilot_tree():
  32. '''return a list of boards to build'''
  33. tstart = time.time()
  34. import importlib.util
  35. spec = importlib.util.spec_from_file_location("board_list.py",
  36. os.path.join(sourcedir,
  37. 'Tools', 'scripts',
  38. 'board_list.py'))
  39. mod = importlib.util.module_from_spec(spec)
  40. spec.loader.exec_module(mod)
  41. all_boards = mod.AUTOBUILD_BOARDS
  42. default_board = mod.AUTOBUILD_BOARDS[0]
  43. exclude_patterns = [ 'fmuv*', 'SITL*' ]
  44. boards = []
  45. for b in all_boards:
  46. excluded = False
  47. for p in exclude_patterns:
  48. if fnmatch.fnmatch(b.lower(), p.lower()):
  49. excluded = True
  50. break
  51. if not excluded:
  52. boards.append(b)
  53. app.logger.info('Took %f seconds to get boards' % (time.time() - tstart))
  54. return boards
  55. def get_boards():
  56. global BOARDS
  57. boards = BOARDS
  58. boards.sort()
  59. return (boards, boards[0])
  60. def get_build_options_from_ardupilot_tree():
  61. '''return a list of build options'''
  62. tstart = time.time()
  63. import importlib.util
  64. spec = importlib.util.spec_from_file_location(
  65. "build_options.py",
  66. os.path.join(sourcedir, 'Tools', 'scripts', 'build_options.py'))
  67. mod = importlib.util.module_from_spec(spec)
  68. spec.loader.exec_module(mod)
  69. app.logger.info('Took %f seconds to get build options' % (time.time() - tstart))
  70. return mod.BUILD_OPTIONS
  71. queue_lock = Lock()
  72. from logging.config import dictConfig
  73. dictConfig({
  74. 'version': 1,
  75. 'formatters': {'default': {
  76. 'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
  77. }},
  78. 'handlers': {'wsgi': {
  79. 'class': 'logging.StreamHandler',
  80. 'stream': 'ext://flask.logging.wsgi_errors_stream',
  81. 'formatter': 'default'
  82. }},
  83. 'root': {
  84. 'level': 'INFO',
  85. 'handlers': ['wsgi']
  86. }
  87. })
  88. def remove_directory_recursive(dirname):
  89. '''remove a directory recursively'''
  90. app.logger.info('Removing directory ' + dirname)
  91. if not os.path.exists(dirname):
  92. return
  93. f = pathlib.Path(dirname)
  94. if f.is_file():
  95. f.unlink()
  96. else:
  97. shutil.rmtree(f, True)
  98. def create_directory(dir_path):
  99. '''create a directory, don't fail if it exists'''
  100. app.logger.info('Creating ' + dir_path)
  101. pathlib.Path(dir_path).mkdir(parents=True, exist_ok=True)
  102. def run_build(task, tmpdir, outdir, logpath):
  103. '''run a build with parameters from task'''
  104. remove_directory_recursive(tmpdir_parent)
  105. create_directory(tmpdir)
  106. if not os.path.isfile(os.path.join(outdir, 'extra_hwdef.dat')):
  107. app.logger.error('Build aborted, missing extra_hwdef.dat')
  108. app.logger.info('Appending to build.log')
  109. with open(logpath, 'a') as log:
  110. # setup PATH to point at our compiler
  111. env = os.environ.copy()
  112. bindir1 = os.path.abspath(os.path.join(appdir, "..", "bin"))
  113. bindir2 = os.path.abspath(os.path.join(appdir, "..", "gcc", "bin"))
  114. cachedir = os.path.abspath(os.path.join(appdir, "..", "cache"))
  115. env["PATH"] = bindir1 + ":" + bindir2 + ":" + env["PATH"]
  116. env['CCACHE_DIR'] = cachedir
  117. app.logger.info('Running waf configure')
  118. subprocess.run(['python3', './waf', 'configure',
  119. '--board', task['board'],
  120. '--out', tmpdir,
  121. '--extra-hwdef', task['extra_hwdef']],
  122. cwd = task['sourcedir'],
  123. env=env,
  124. stdout=log, stderr=log)
  125. app.logger.info('Running clean')
  126. subprocess.run(['python3', './waf', 'clean'],
  127. cwd = task['sourcedir'],
  128. env=env,
  129. stdout=log, stderr=log)
  130. app.logger.info('Running build')
  131. subprocess.run(['python3', './waf', task['vehicle']],
  132. cwd = task['sourcedir'],
  133. env=env,
  134. stdout=log, stderr=log)
  135. def sort_json_files(reverse=False):
  136. json_files = list(filter(os.path.isfile,
  137. glob.glob(os.path.join(outdir_parent,
  138. '*', 'q.json'))))
  139. json_files.sort(key=lambda x: os.path.getmtime(x), reverse=reverse)
  140. return json_files
  141. def check_queue():
  142. '''thread to continuously run queued builds'''
  143. queue_lock.acquire()
  144. json_files = sort_json_files()
  145. queue_lock.release()
  146. if len(json_files) == 0:
  147. return
  148. # remove multiple build requests from same ip address (keep newest)
  149. queue_lock.acquire()
  150. ip_list = []
  151. for f in json_files:
  152. file = json.loads(open(f).read())
  153. ip_list.append(file['ip'])
  154. seen = set()
  155. ip_list.reverse()
  156. for index, value in enumerate(ip_list):
  157. if value in seen:
  158. file = json.loads(open(json_files[-index-1]).read())
  159. outdir_to_delete = os.path.join(outdir_parent, file['token'])
  160. remove_directory_recursive(outdir_to_delete)
  161. else:
  162. seen.add(value)
  163. queue_lock.release()
  164. if len(json_files) == 0:
  165. return
  166. # open oldest q.json file
  167. json_files = sort_json_files()
  168. taskfile = json_files[0]
  169. app.logger.info('Opening ' + taskfile)
  170. task = json.loads(open(taskfile).read())
  171. app.logger.info('Removing ' + taskfile)
  172. os.remove(taskfile)
  173. outdir = os.path.join(outdir_parent, task['token'])
  174. tmpdir = os.path.join(tmpdir_parent, task['token'])
  175. logpath = os.path.abspath(os.path.join(outdir, 'build.log'))
  176. app.logger.info("LOGPATH: %s" % logpath)
  177. try:
  178. # run build and rename build directory
  179. run_build(task, tmpdir, outdir, logpath)
  180. app.logger.info('Copying build files from %s to %s',
  181. os.path.join(tmpdir, task['board']),
  182. outdir)
  183. copy_tree(os.path.join(tmpdir, task['board'], 'bin'), outdir)
  184. app.logger.info('Build successful!')
  185. remove_directory_recursive(tmpdir)
  186. except Exception as ex:
  187. app.logger.info('Build failed: ', ex)
  188. pass
  189. open(logpath,'a').write("\nBUILD_FINISHED\n")
  190. def file_age(fname):
  191. '''return file age in seconds'''
  192. return time.time() - os.stat(fname).st_mtime
  193. def remove_old_builds():
  194. '''as a cleanup, remove any builds older than 24H'''
  195. for f in os.listdir(outdir_parent):
  196. bdir = os.path.join(outdir_parent, f)
  197. if os.path.isdir(bdir) and file_age(bdir) > 24 * 60 * 60:
  198. remove_directory_recursive(bdir)
  199. time.sleep(5)
  200. def queue_thread():
  201. while True:
  202. try:
  203. check_queue()
  204. remove_old_builds()
  205. except Exception as ex:
  206. app.logger.error('Failed queue: ', ex)
  207. pass
  208. def get_build_status():
  209. '''return build status tuple list
  210. returns tuples of form (status,age,board,vehicle,genlink)
  211. '''
  212. ret = []
  213. # get list of directories
  214. blist = []
  215. for b in os.listdir(outdir_parent):
  216. if os.path.isdir(os.path.join(outdir_parent,b)):
  217. blist.append(b)
  218. blist.sort(key=lambda x: os.path.getmtime(os.path.join(outdir_parent,x)), reverse=True)
  219. for b in blist:
  220. a = b.split(':')
  221. if len(a) < 2:
  222. continue
  223. vehicle = a[0].capitalize()
  224. board = a[1]
  225. link = "/view?token=%s" % b
  226. age_min = int(file_age(os.path.join(outdir_parent,b))/60.0)
  227. age_str = "%u:%02u" % ((age_min // 60), age_min % 60)
  228. feature_file = os.path.join(outdir_parent, b, 'selected_features.json')
  229. app.logger.info('Opening ' + feature_file)
  230. selected_features_dict = json.loads(open(feature_file).read())
  231. selected_features = selected_features_dict['selected_features']
  232. git_hash_short = selected_features_dict['git_hash_short']
  233. features = ''
  234. for feature in selected_features:
  235. if features == '':
  236. features = features + feature
  237. else:
  238. features = features + ", " + feature
  239. if os.path.exists(os.path.join(outdir_parent,b,'q.json')):
  240. status = "Pending"
  241. elif not os.path.exists(os.path.join(outdir_parent,b,'build.log')):
  242. status = "Error"
  243. else:
  244. build = open(os.path.join(outdir_parent,b,'build.log')).read()
  245. if build.find("'%s' finished successfully" % vehicle.lower()) != -1:
  246. status = "Finished"
  247. elif build.find('The configuration failed') != -1 or build.find('Build failed') != -1 or build.find('compilation terminated') != -1:
  248. status = "Failed"
  249. elif build.find('BUILD_FINISHED') == -1:
  250. status = "Running"
  251. else:
  252. status = "Failed"
  253. ret.append((status,age_str,board,vehicle,link,features,git_hash_short))
  254. return ret
  255. def create_status():
  256. '''create status.html'''
  257. build_status = get_build_status()
  258. tmpfile = os.path.join(outdir_parent, "status.tmp")
  259. statusfile = os.path.join(outdir_parent, "status.html")
  260. f = open(tmpfile, "w")
  261. app2 = Flask("status")
  262. with app2.app_context():
  263. f.write(render_template_string(open(os.path.join(appdir, 'templates', 'status.html')).read(),
  264. build_status=build_status))
  265. f.close()
  266. os.replace(tmpfile, statusfile)
  267. def status_thread():
  268. while True:
  269. try:
  270. create_status()
  271. except Exception as ex:
  272. app.logger.info(ex)
  273. pass
  274. time.sleep(3)
  275. def update_source(branch):
  276. '''update submodules and ardupilot git tree. Returns new source git hash'''
  277. app.logger.info('Updating to new branch: '+branch)
  278. app.logger.info('Fetching ardupilot remote')
  279. subprocess.run(['git', 'fetch', branch.split('/', 1)[0]],
  280. cwd=sourcedir)
  281. app.logger.info('Updating ardupilot git tree')
  282. subprocess.run(['git', 'reset', '--hard',
  283. branch],
  284. cwd=sourcedir)
  285. app.logger.info('Updating submodules')
  286. subprocess.run(['git', 'submodule',
  287. 'update', '--recursive',
  288. '--force', '--init'],
  289. cwd=sourcedir)
  290. source_git_hash = subprocess.check_output([
  291. 'git',
  292. 'rev-parse',
  293. 'HEAD',
  294. ], cwd=sourcedir, encoding = 'utf-8')
  295. source_git_hash = source_git_hash.rstrip()
  296. app.logger.info('new git hash ' + source_git_hash)
  297. return source_git_hash
  298. import optparse
  299. parser = optparse.OptionParser("app.py")
  300. parser.add_option("", "--basedir", type="string",
  301. default=os.path.abspath(os.path.join(os.path.dirname(__file__),"..","base")),
  302. help="base directory")
  303. cmd_opts, cmd_args = parser.parse_args()
  304. # define directories
  305. basedir = os.path.abspath(cmd_opts.basedir)
  306. sourcedir = os.path.abspath(os.path.join(basedir, 'ardupilot'))
  307. outdir_parent = os.path.join(basedir, 'builds')
  308. tmpdir_parent = os.path.join(basedir, 'tmp')
  309. app = Flask(__name__, template_folder='templates')
  310. if not os.path.isdir(outdir_parent):
  311. create_directory(outdir_parent)
  312. try:
  313. lock_file = open(os.path.join(basedir, "queue.lck"), "w")
  314. fcntl.flock(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
  315. app.logger.info("Got queue lock")
  316. # we only want one set of threads
  317. thread = Thread(target=queue_thread, args=())
  318. thread.daemon = True
  319. thread.start()
  320. status_thread = Thread(target=status_thread, args=())
  321. status_thread.daemon = True
  322. status_thread.start()
  323. except IOError:
  324. app.logger.info("No queue lock")
  325. app.logger.info('Initial fetch')
  326. global SOURCE_GIT_HASH
  327. global BUILD_OPTIONS
  328. global BOARDS
  329. SOURCE_GIT_HASH = update_source(default_branch)
  330. # get build options from source:
  331. BUILD_OPTIONS = get_build_options_from_ardupilot_tree()
  332. BOARDS = get_boards_from_ardupilot_tree()
  333. app.logger.info('Python version is: %s' % sys.version)
  334. @app.route('/generate', methods=['GET', 'POST'])
  335. def generate():
  336. try:
  337. global chosen_branch
  338. global chosen_vehicle
  339. # fetch features from user input
  340. extra_hwdef = []
  341. feature_list = []
  342. selected_features = []
  343. app.logger.info('Fetching features from user input')
  344. # add all undefs at the start
  345. for f in BUILD_OPTIONS:
  346. extra_hwdef.append('undef %s' % f.define)
  347. for f in BUILD_OPTIONS:
  348. if f.label not in request.form or request.form[f.label] != '1':
  349. extra_hwdef.append('define %s 0' % f.define)
  350. else:
  351. extra_hwdef.append('define %s 1' % f.define)
  352. feature_list.append(f.description)
  353. selected_features.append(f.label)
  354. extra_hwdef = '\n'.join(extra_hwdef)
  355. spaces = '\n'
  356. feature_list = spaces.join(feature_list)
  357. selected_features_dict = {}
  358. selected_features_dict['selected_features'] = selected_features
  359. queue_lock.acquire()
  360. # create extra_hwdef.dat file and obtain md5sum
  361. app.logger.info('Creating ' +
  362. os.path.join(outdir_parent, 'extra_hwdef.dat'))
  363. file = open(os.path.join(outdir_parent, 'extra_hwdef.dat'), 'w')
  364. app.logger.info('Writing\n' + extra_hwdef)
  365. file.write(extra_hwdef)
  366. file.close()
  367. md5sum = hashlib.md5(extra_hwdef.encode('utf-8')).hexdigest()
  368. app.logger.info('Removing ' +
  369. os.path.join(outdir_parent, 'extra_hwdef.dat'))
  370. os.remove(os.path.join(outdir_parent, 'extra_hwdef.dat'))
  371. git_hash_short = SOURCE_GIT_HASH[:10]
  372. git_hash = SOURCE_GIT_HASH[:len(SOURCE_GIT_HASH)-1]
  373. app.logger.info('Git hash = ' + SOURCE_GIT_HASH)
  374. selected_features_dict['git_hash_short'] = git_hash_short
  375. # create directories using concatenated token
  376. # of vehicle, board, git-hash of source, and md5sum of hwdef
  377. board = request.form['board']
  378. if board not in get_boards()[0]:
  379. raise Exception("bad board")
  380. token = chosen_vehicle.lower() + ':' + board + ':' + SOURCE_GIT_HASH + ':' + md5sum
  381. app.logger.info('token = ' + token)
  382. global outdir
  383. outdir = os.path.join(outdir_parent, token)
  384. if os.path.isdir(outdir):
  385. app.logger.info('Build already exists')
  386. else:
  387. create_directory(outdir)
  388. # create build.log
  389. build_log_info = ('Vehicle: ' + chosen_vehicle +
  390. '\nBoard: ' + board +
  391. '\nBranch:' + chosen_branch +
  392. '\nSelected Features:\n' + feature_list +
  393. '\n\nWaiting for build to start...\n\n')
  394. app.logger.info('Creating build.log')
  395. build_log = open(os.path.join(outdir, 'build.log'), 'w')
  396. build_log.write(build_log_info)
  397. build_log.close()
  398. # create hwdef.dat
  399. app.logger.info('Opening ' +
  400. os.path.join(outdir, 'extra_hwdef.dat'))
  401. file = open(os.path.join(outdir, 'extra_hwdef.dat'),'w')
  402. app.logger.info('Writing\n' + extra_hwdef)
  403. file.write(extra_hwdef)
  404. file.close()
  405. # fill dictionary of variables and create json file
  406. task = {}
  407. task['token'] = token
  408. task['sourcedir'] = sourcedir
  409. task['extra_hwdef'] = os.path.join(outdir, 'extra_hwdef.dat')
  410. task['vehicle'] = chosen_vehicle.lower()
  411. task['board'] = board
  412. task['ip'] = request.remote_addr
  413. app.logger.info('Opening ' + os.path.join(outdir, 'q.json'))
  414. jfile = open(os.path.join(outdir, 'q.json'), 'w')
  415. app.logger.info('Writing task file to ' +
  416. os.path.join(outdir, 'q.json'))
  417. jfile.write(json.dumps(task, separators=(',\n', ': ')))
  418. jfile.close()
  419. # create selected_features.dat for status table
  420. feature_file = open(os.path.join(outdir, 'selected_features.json'), 'w')
  421. app.logger.info('Writing\n' + os.path.join(outdir, 'selected_features.json'))
  422. feature_file.write(json.dumps(selected_features_dict))
  423. feature_file.close()
  424. queue_lock.release()
  425. base_url = request.url_root
  426. app.logger.info(base_url)
  427. app.logger.info('Rendering generate.html')
  428. return render_template('generate.html', token=token)
  429. except Exception as ex:
  430. app.logger.error(ex)
  431. return render_template('generate.html', error='Error occured: ', ex=ex)
  432. @app.route('/view', methods=['GET'])
  433. def view():
  434. '''view a build from status'''
  435. token=request.args['token']
  436. app.logger.info("viewing %s" % token)
  437. return render_template('generate.html', token=token)
  438. def get_build_options(BUILD_OPTIONS, category):
  439. return sorted([f for f in BUILD_OPTIONS if f.category == category], key=lambda x: x.description.lower())
  440. def get_build_categories(BUILD_OPTIONS):
  441. return sorted(list(set([f.category for f in BUILD_OPTIONS])))
  442. def get_vehicles():
  443. return (VEHICLES, default_vehicle)
  444. def get_branches():
  445. return (BRANCHES, default_branch)
  446. @app.route('/')
  447. def home():
  448. app.logger.info('Rendering index.html')
  449. global BUILD_OPTIONS
  450. return render_template('index.html',
  451. get_branches=get_branches,
  452. get_vehicles=get_vehicles,)
  453. @app.route('/index2', methods=['GET', 'POST'])
  454. def home2():
  455. app.logger.info('Rendering index2.html')
  456. global chosen_branch
  457. chosen_branch = request.form['branch']
  458. if not chosen_branch in BRANCHES:
  459. raise Exception("bad branch")
  460. new_git_hash = update_source(chosen_branch)
  461. global chosen_vehicle
  462. chosen_vehicle = request.form['vehicle']
  463. if not chosen_vehicle in VEHICLES:
  464. raise Exception("bad vehicle")
  465. global SOURCE_GIT_HASH
  466. global BUILD_OPTIONS
  467. global BOARDS
  468. if new_git_hash == SOURCE_GIT_HASH:
  469. app.logger.info('Source git hash unchanged')
  470. else:
  471. app.logger.info('Source git hash changed; refreshing')
  472. SOURCE_GIT_HASH = new_git_hash
  473. # get build options from source:
  474. BUILD_OPTIONS = get_build_options_from_ardupilot_tree()
  475. BOARDS = get_boards_from_ardupilot_tree()
  476. return render_template('index2.html',
  477. get_boards=get_boards,
  478. chosen_vehicle=chosen_vehicle,
  479. chosen_branch=chosen_branch,
  480. get_branches=get_branches,
  481. get_build_options=lambda x : get_build_options(BUILD_OPTIONS, x),
  482. get_build_categories=lambda : get_build_categories(BUILD_OPTIONS))
  483. @app.route("/builds/<path:name>")
  484. def download_file(name):
  485. app.logger.info('Downloading %s' % name)
  486. return send_from_directory(os.path.join(basedir,'builds'), name, as_attachment=False)
  487. if __name__ == '__main__':
  488. app.run()