app.py 19 KB

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