app.py 18 KB

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