app.py 19 KB

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