app.py 22 KB

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