app.py 20 KB

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