app.py 24 KB

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