doctor.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. """QMK Doctor
  2. Check out the user's QMK environment and make sure it's ready to compile.
  3. """
  4. import platform
  5. import re
  6. import shutil
  7. import subprocess
  8. from pathlib import Path
  9. from enum import Enum
  10. from milc import cli
  11. from milc.questions import yesno
  12. from qmk import submodules
  13. from qmk.constants import QMK_FIRMWARE
  14. from qmk.commands import run
  15. class CheckStatus(Enum):
  16. OK = 1
  17. WARNING = 2
  18. ERROR = 3
  19. ESSENTIAL_BINARIES = {
  20. 'dfu-programmer': {},
  21. 'avrdude': {},
  22. 'dfu-util': {},
  23. 'avr-gcc': {
  24. 'version_arg': '-dumpversion'
  25. },
  26. 'arm-none-eabi-gcc': {
  27. 'version_arg': '-dumpversion'
  28. },
  29. 'bin/qmk': {},
  30. }
  31. def _udev_rule(vid, pid=None, *args):
  32. """ Helper function that return udev rules
  33. """
  34. rule = ""
  35. if pid:
  36. rule = 'SUBSYSTEMS=="usb", ATTRS{idVendor}=="%s", ATTRS{idProduct}=="%s", TAG+="uaccess"' % (
  37. vid,
  38. pid,
  39. )
  40. else:
  41. rule = 'SUBSYSTEMS=="usb", ATTRS{idVendor}=="%s", TAG+="uaccess"' % vid
  42. if args:
  43. rule = ', '.join([rule, *args])
  44. return rule
  45. def _deprecated_udev_rule(vid, pid=None):
  46. """ Helper function that return udev rules
  47. Note: these are no longer the recommended rules, this is just used to check for them
  48. """
  49. if pid:
  50. return 'SUBSYSTEMS=="usb", ATTRS{idVendor}=="%s", ATTRS{idProduct}=="%s", MODE:="0666"' % (vid, pid)
  51. else:
  52. return 'SUBSYSTEMS=="usb", ATTRS{idVendor}=="%s", MODE:="0666"' % vid
  53. def parse_gcc_version(version):
  54. m = re.match(r"(\d+)(?:\.(\d+))?(?:\.(\d+))?", version)
  55. return {
  56. 'major': int(m.group(1)),
  57. 'minor': int(m.group(2)) if m.group(2) else 0,
  58. 'patch': int(m.group(3)) if m.group(3) else 0,
  59. }
  60. def check_arm_gcc_version():
  61. """Returns True if the arm-none-eabi-gcc version is not known to cause problems.
  62. """
  63. if 'output' in ESSENTIAL_BINARIES['arm-none-eabi-gcc']:
  64. version_number = ESSENTIAL_BINARIES['arm-none-eabi-gcc']['output'].strip()
  65. cli.log.info('Found arm-none-eabi-gcc version %s', version_number)
  66. return CheckStatus.OK # Right now all known arm versions are ok
  67. def check_avr_gcc_version():
  68. """Returns True if the avr-gcc version is not known to cause problems.
  69. """
  70. rc = CheckStatus.ERROR
  71. if 'output' in ESSENTIAL_BINARIES['avr-gcc']:
  72. version_number = ESSENTIAL_BINARIES['avr-gcc']['output'].strip()
  73. cli.log.info('Found avr-gcc version %s', version_number)
  74. rc = CheckStatus.OK
  75. parsed_version = parse_gcc_version(version_number)
  76. if parsed_version['major'] > 8:
  77. cli.log.warning('{fg_yellow}We do not recommend avr-gcc newer than 8. Downgrading to 8.x is recommended.')
  78. rc = CheckStatus.WARNING
  79. return rc
  80. def check_avrdude_version():
  81. if 'output' in ESSENTIAL_BINARIES['avrdude']:
  82. last_line = ESSENTIAL_BINARIES['avrdude']['output'].split('\n')[-2]
  83. version_number = last_line.split()[2][:-1]
  84. cli.log.info('Found avrdude version %s', version_number)
  85. return CheckStatus.OK
  86. def check_dfu_util_version():
  87. if 'output' in ESSENTIAL_BINARIES['dfu-util']:
  88. first_line = ESSENTIAL_BINARIES['dfu-util']['output'].split('\n')[0]
  89. version_number = first_line.split()[1]
  90. cli.log.info('Found dfu-util version %s', version_number)
  91. return CheckStatus.OK
  92. def check_dfu_programmer_version():
  93. if 'output' in ESSENTIAL_BINARIES['dfu-programmer']:
  94. first_line = ESSENTIAL_BINARIES['dfu-programmer']['output'].split('\n')[0]
  95. version_number = first_line.split()[1]
  96. cli.log.info('Found dfu-programmer version %s', version_number)
  97. return CheckStatus.OK
  98. def check_binaries():
  99. """Iterates through ESSENTIAL_BINARIES and tests them.
  100. """
  101. ok = True
  102. for binary in sorted(ESSENTIAL_BINARIES):
  103. if not is_executable(binary):
  104. ok = False
  105. return ok
  106. def check_submodules():
  107. """Iterates through all submodules to make sure they're cloned and up to date.
  108. """
  109. for submodule in submodules.status().values():
  110. if submodule['status'] is None:
  111. cli.log.error('Submodule %s has not yet been cloned!', submodule['name'])
  112. return CheckStatus.ERROR
  113. elif not submodule['status']:
  114. cli.log.warning('Submodule %s is not up to date!', submodule['name'])
  115. return CheckStatus.WARNING
  116. return CheckStatus.OK
  117. def check_git_repo():
  118. """Checks that the .git directory exists inside QMK_HOME.
  119. This is a decent enough indicator that the qmk_firmware directory is a
  120. proper Git repository, rather than a .zip download from GitHub.
  121. """
  122. dot_git_dir = QMK_FIRMWARE / '.git'
  123. return CheckStatus.OK if dot_git_dir.is_dir() else CheckStatus.WARNING
  124. def check_udev_rules():
  125. """Make sure the udev rules look good.
  126. """
  127. rc = CheckStatus.OK
  128. udev_dir = Path("/etc/udev/rules.d/")
  129. desired_rules = {
  130. 'atmel-dfu': {
  131. _udev_rule("03eb", "2fef"), # ATmega16U2
  132. _udev_rule("03eb", "2ff0"), # ATmega32U2
  133. _udev_rule("03eb", "2ff3"), # ATmega16U4
  134. _udev_rule("03eb", "2ff4"), # ATmega32U4
  135. _udev_rule("03eb", "2ff9"), # AT90USB64
  136. _udev_rule("03eb", "2ffb") # AT90USB128
  137. },
  138. 'kiibohd': {_udev_rule("1c11", "b007")},
  139. 'stm32': {
  140. _udev_rule("1eaf", "0003"), # STM32duino
  141. _udev_rule("0483", "df11") # STM32 DFU
  142. },
  143. 'bootloadhid': {_udev_rule("16c0", "05df")},
  144. 'usbasploader': {_udev_rule("16c0", "05dc")},
  145. 'massdrop': {_udev_rule("03eb", "6124", 'ENV{ID_MM_DEVICE_IGNORE}="1"')},
  146. 'caterina': {
  147. # Spark Fun Electronics
  148. _udev_rule("1b4f", "9203", 'ENV{ID_MM_DEVICE_IGNORE}="1"'), # Pro Micro 3V3/8MHz
  149. _udev_rule("1b4f", "9205", 'ENV{ID_MM_DEVICE_IGNORE}="1"'), # Pro Micro 5V/16MHz
  150. _udev_rule("1b4f", "9207", 'ENV{ID_MM_DEVICE_IGNORE}="1"'), # LilyPad 3V3/8MHz (and some Pro Micro clones)
  151. # Pololu EleCTRONICS
  152. _udev_rule("1ffb", "0101", 'ENV{ID_MM_DEVICE_IGNORE}="1"'), # A-Star 32U4
  153. # Arduino SA
  154. _udev_rule("2341", "0036", 'ENV{ID_MM_DEVICE_IGNORE}="1"'), # Leonardo
  155. _udev_rule("2341", "0037", 'ENV{ID_MM_DEVICE_IGNORE}="1"'), # Micro
  156. # Adafruit INDUSTRIES llC
  157. _udev_rule("239a", "000c", 'ENV{ID_MM_DEVICE_IGNORE}="1"'), # Feather 32U4
  158. _udev_rule("239a", "000d", 'ENV{ID_MM_DEVICE_IGNORE}="1"'), # ItsyBitsy 32U4 3V3/8MHz
  159. _udev_rule("239a", "000e", 'ENV{ID_MM_DEVICE_IGNORE}="1"'), # ItsyBitsy 32U4 5V/16MHz
  160. # dog hunter ag
  161. _udev_rule("2a03", "0036", 'ENV{ID_MM_DEVICE_IGNORE}="1"'), # Leonardo
  162. _udev_rule("2a03", "0037", 'ENV{ID_MM_DEVICE_IGNORE}="1"') # Micro
  163. }
  164. }
  165. # These rules are no longer recommended, only use them to check for their presence.
  166. deprecated_rules = {
  167. 'atmel-dfu': {_deprecated_udev_rule("03eb", "2ff4"), _deprecated_udev_rule("03eb", "2ffb"), _deprecated_udev_rule("03eb", "2ff0")},
  168. 'kiibohd': {_deprecated_udev_rule("1c11")},
  169. 'stm32': {_deprecated_udev_rule("1eaf", "0003"), _deprecated_udev_rule("0483", "df11")},
  170. 'bootloadhid': {_deprecated_udev_rule("16c0", "05df")},
  171. 'caterina': {'ATTRS{idVendor}=="2a03", ENV{ID_MM_DEVICE_IGNORE}="1"', 'ATTRS{idVendor}=="2341", ENV{ID_MM_DEVICE_IGNORE}="1"'},
  172. 'tmk': {_deprecated_udev_rule("feed")}
  173. }
  174. if udev_dir.exists():
  175. udev_rules = [rule_file for rule_file in udev_dir.glob('*.rules')]
  176. current_rules = set()
  177. # Collect all rules from the config files
  178. for rule_file in udev_rules:
  179. for line in rule_file.read_text().split('\n'):
  180. line = line.strip()
  181. if not line.startswith("#") and len(line):
  182. current_rules.add(line)
  183. # Check if the desired rules are among the currently present rules
  184. for bootloader, rules in desired_rules.items():
  185. if not rules.issubset(current_rules):
  186. deprecated_rule = deprecated_rules.get(bootloader)
  187. if deprecated_rule and deprecated_rule.issubset(current_rules):
  188. cli.log.warning("{fg_yellow}Found old, deprecated udev rules for '%s' boards. The new rules on https://docs.qmk.fm/#/faq_build?id=linux-udev-rules offer better security with the same functionality.", bootloader)
  189. else:
  190. # For caterina, check if ModemManager is running
  191. if bootloader == "caterina":
  192. if check_modem_manager():
  193. rc = CheckStatus.WARNING
  194. cli.log.warning("{fg_yellow}Detected ModemManager without the necessary udev rules. Please either disable it or set the appropriate udev rules if you are using a Pro Micro.")
  195. rc = CheckStatus.WARNING
  196. cli.log.warning("{fg_yellow}Missing or outdated udev rules for '%s' boards. Run 'sudo cp %s/util/udev/50-qmk.rules /etc/udev/rules.d/'.", bootloader, QMK_FIRMWARE)
  197. else:
  198. cli.log.warning("{fg_yellow}'%s' does not exist. Skipping udev rule checking...", udev_dir)
  199. return rc
  200. def check_systemd():
  201. """Check if it's a systemd system
  202. """
  203. return bool(shutil.which("systemctl"))
  204. def check_modem_manager():
  205. """Returns True if ModemManager is running.
  206. """
  207. if check_systemd():
  208. mm_check = run(["systemctl", "--quiet", "is-active", "ModemManager.service"], timeout=10)
  209. if mm_check.returncode == 0:
  210. return True
  211. else:
  212. """(TODO): Add check for non-systemd systems
  213. """
  214. return False
  215. def is_executable(command):
  216. """Returns True if command exists and can be executed.
  217. """
  218. # Make sure the command is in the path.
  219. res = shutil.which(command)
  220. if res is None:
  221. cli.log.error("{fg_red}Can't find %s in your path.", command)
  222. return False
  223. # Make sure the command can be executed
  224. version_arg = ESSENTIAL_BINARIES[command].get('version_arg', '--version')
  225. check = run([command, version_arg], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=5, universal_newlines=True)
  226. ESSENTIAL_BINARIES[command]['output'] = check.stdout
  227. if check.returncode in [0, 1]: # Older versions of dfu-programmer exit 1
  228. cli.log.debug('Found {fg_cyan}%s', command)
  229. return True
  230. cli.log.error("{fg_red}Can't run `%s %s`", command, version_arg)
  231. return False
  232. def os_tests():
  233. """Determine our OS and run platform specific tests
  234. """
  235. platform_id = platform.platform().lower()
  236. if 'darwin' in platform_id or 'macos' in platform_id:
  237. return os_test_macos()
  238. elif 'linux' in platform_id:
  239. return os_test_linux()
  240. elif 'windows' in platform_id:
  241. return os_test_windows()
  242. else:
  243. cli.log.warning('Unsupported OS detected: %s', platform_id)
  244. return CheckStatus.WARNING
  245. def os_test_linux():
  246. """Run the Linux specific tests.
  247. """
  248. cli.log.info("Detected {fg_cyan}Linux.")
  249. return check_udev_rules()
  250. def os_test_macos():
  251. """Run the Mac specific tests.
  252. """
  253. cli.log.info("Detected {fg_cyan}macOS.")
  254. return CheckStatus.OK
  255. def os_test_windows():
  256. """Run the Windows specific tests.
  257. """
  258. cli.log.info("Detected {fg_cyan}Windows.")
  259. return CheckStatus.OK
  260. @cli.argument('-y', '--yes', action='store_true', arg_only=True, help='Answer yes to all questions.')
  261. @cli.argument('-n', '--no', action='store_true', arg_only=True, help='Answer no to all questions.')
  262. @cli.subcommand('Basic QMK environment checks')
  263. def doctor(cli):
  264. """Basic QMK environment checks.
  265. This is currently very simple, it just checks that all the expected binaries are on your system.
  266. TODO(unclaimed):
  267. * [ ] Compile a trivial program with each compiler
  268. """
  269. cli.log.info('QMK Doctor is checking your environment.')
  270. status = os_tests()
  271. cli.log.info('QMK home: {fg_cyan}%s', QMK_FIRMWARE)
  272. # Make sure our QMK home is a Git repo
  273. git_ok = check_git_repo()
  274. if git_ok == CheckStatus.WARNING:
  275. cli.log.warning("QMK home does not appear to be a Git repository! (no .git folder)")
  276. status = CheckStatus.WARNING
  277. # Make sure the basic CLI tools we need are available and can be executed.
  278. bin_ok = check_binaries()
  279. if not bin_ok:
  280. if yesno('Would you like to install dependencies?', default=True):
  281. run(['util/qmk_install.sh'])
  282. bin_ok = check_binaries()
  283. if bin_ok:
  284. cli.log.info('All dependencies are installed.')
  285. else:
  286. status = CheckStatus.ERROR
  287. # Make sure the tools are at the correct version
  288. ver_ok = []
  289. for check in (check_arm_gcc_version, check_avr_gcc_version, check_avrdude_version, check_dfu_util_version, check_dfu_programmer_version):
  290. ver_ok.append(check())
  291. if CheckStatus.ERROR in ver_ok:
  292. status = CheckStatus.ERROR
  293. elif CheckStatus.WARNING in ver_ok and status == CheckStatus.OK:
  294. status = CheckStatus.WARNING
  295. # Check out the QMK submodules
  296. sub_ok = check_submodules()
  297. if sub_ok == CheckStatus.OK:
  298. cli.log.info('Submodules are up to date.')
  299. else:
  300. if yesno('Would you like to clone the submodules?', default=True):
  301. submodules.update()
  302. sub_ok = check_submodules()
  303. if CheckStatus.ERROR in sub_ok:
  304. status = CheckStatus.ERROR
  305. elif CheckStatus.WARNING in sub_ok and status == CheckStatus.OK:
  306. status = CheckStatus.WARNING
  307. # Report a summary of our findings to the user
  308. if status == CheckStatus.OK:
  309. cli.log.info('{fg_green}QMK is ready to go')
  310. return 0
  311. elif status == CheckStatus.WARNING:
  312. cli.log.info('{fg_yellow}QMK is ready to go, but minor problems were found')
  313. return 1
  314. else:
  315. cli.log.info('{fg_red}Major problems detected, please fix these problems before proceeding.')
  316. cli.log.info('{fg_blue}Check out the FAQ (https://docs.qmk.fm/#/faq_build) or join the QMK Discord (https://discord.gg/Uq7gcHh) for help.')
  317. return 2