app.py 19 KB

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