doctor.py 12 KB

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