app.py 22 KB

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