app.py 18 KB

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