app.py 19 KB

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