-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmachine.py
2191 lines (2061 loc) · 86.9 KB
/
machine.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Machine manipulation request handlers
#
# Copyright (C) 2020 Eric Callahan <[email protected]>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import sys
import os
import re
import pathlib
import logging
import asyncio
import platform
import socket
import ipaddress
import time
import shutil
import distro
import tempfile
import getpass
import configparser
from ..confighelper import FileSourceWrapper
from ..utils import source_info, cansocket, sysfs_devs, load_system_module
from ..utils import json_wrapper as jsonw
from ..common import RequestType
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Awaitable,
Callable,
Dict,
List,
Optional,
Tuple,
Union,
cast
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..common import WebRequest
from .application import MoonrakerApp
from .klippy_connection import KlippyConnection
from .http_client import HttpClient
from .shell_command import ShellCommandFactory as SCMDComp
from .database import MoonrakerDatabase
from .file_manager.file_manager import FileManager
from .announcements import Announcements
from .proc_stats import ProcStats
from .dbus_manager import DbusManager
from dbus_next.aio import ProxyInterface
from dbus_next import Variant
SudoReturn = Union[Awaitable[Tuple[str, bool]], Tuple[str, bool]]
SudoCallback = Callable[[], SudoReturn]
DEFAULT_ALLOWED_SERVICES = [
"klipper_mcu",
"webcamd",
"MoonCord",
"KlipperScreen",
"moonraker-telegram-bot",
"moonraker-obico",
"sonar",
"crowsnest",
"octoeverywhere",
"ratos-configurator"
]
CGROUP_PATH = "/proc/1/cgroup"
SCHED_PATH = "/proc/1/sched"
SYSTEMD_PATH = "/etc/systemd/system"
SD_CID_PATH = "/sys/block/mmcblk0/device/cid"
SD_CSD_PATH = "/sys/block/mmcblk0/device/csd"
SD_MFGRS = {
'1b': "Samsung",
'03': "Sandisk",
'74': "PNY"
}
IP_FAMILIES = {'inet': 'ipv4', 'inet6': 'ipv6'}
NETWORK_UPDATE_SEQUENCE = 10
SERVICE_PROPERTIES = [
"Requires", "After", "SupplementaryGroups", "EnvironmentFiles",
"ExecStart", "WorkingDirectory", "FragmentPath", "Description",
"User"
]
USB_IDS_URL = "http://www.linux-usb.org/usb.ids"
class Machine:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self._allowed_services: List[str] = []
self._init_allowed_services()
dist_info: Dict[str, Any]
dist_info = {'name': distro.name(pretty=True)}
dist_info.update(distro.info())
dist_info['release_info'] = distro.distro_release_info()
self.inside_container = False
self.moonraker_service_info: Dict[str, Any] = {}
self.sudo_req_lock = asyncio.Lock()
self.periph_lock = asyncio.Lock()
self._sudo_password: Optional[str] = None
sudo_template = config.gettemplate("sudo_password", None)
if sudo_template is not None:
self._sudo_password = sudo_template.render()
self._public_ip = ""
self.system_info: Dict[str, Any] = {
'python': {
"version": tuple(sys.version_info),
"version_string": sys.version.replace("\n", " ")
},
'cpu_info': self._get_cpu_info(),
'sd_info': self._get_sdcard_info(),
'distribution': dist_info,
'virtualization': self._check_inside_container(),
'network': {},
'canbus': {}
}
self._update_log_rollover(log=True)
providers: Dict[str, type] = {
"none": BaseProvider,
"systemd_cli": SystemdCliProvider,
"systemd_dbus": SystemdDbusProvider,
"supervisord_cli": SupervisordCliProvider
}
self.provider_type = config.get('provider', 'systemd_dbus')
pclass = providers.get(self.provider_type)
if pclass is None:
raise config.error(f"Invalid Provider: {self.provider_type}")
self.sys_provider: BaseProvider = pclass(config)
self.system_info["provider"] = self.provider_type
logging.info(f"Using System Provider: {self.provider_type}")
self.validator = InstallValidator(config)
self.sudo_requests: List[Tuple[SudoCallback, str]] = []
self.server.register_endpoint(
"/machine/reboot", RequestType.POST, self._handle_machine_request
)
self.server.register_endpoint(
"/machine/shutdown", RequestType.POST, self._handle_machine_request
)
self.server.register_endpoint(
"/machine/services/restart", RequestType.POST, self._handle_service_request
)
self.server.register_endpoint(
"/machine/services/stop", RequestType.POST, self._handle_service_request
)
self.server.register_endpoint(
"/machine/services/start", RequestType.POST, self._handle_service_request
)
self.server.register_endpoint(
"/machine/system_info", RequestType.GET, self._handle_sysinfo_request
)
# self.server.register_endpoint(
# "/machine/system_info", RequestType.POST, self._handle_sysinfo_request
# )
self.server.register_endpoint(
"/machine/sudo/info", RequestType.GET, self._handle_sudo_info
)
self.server.register_endpoint(
"/machine/sudo/password", RequestType.POST, self._set_sudo_password
)
self.server.register_endpoint(
"/machine/peripherals/serial", RequestType.GET, self._handle_serial_request
)
self.server.register_endpoint(
"/machine/peripherals/usb", RequestType.GET, self._handle_usb_request
)
self.server.register_endpoint(
"/machine/peripherals/canbus", RequestType.GET, self._handle_can_query
)
self.server.register_endpoint(
"/machine/peripherals/video", RequestType.GET, self._handle_video_request
)
self.server.register_notification("machine:service_state_changed")
self.server.register_notification("machine:sudo_alert")
# Register remote methods
self.server.register_remote_method(
"shutdown_machine", self.sys_provider.shutdown)
self.server.register_remote_method(
"reboot_machine", self.sys_provider.reboot)
# IP network shell commands
shell_cmd: SCMDComp = self.server.load_component(
config, 'shell_command')
self.addr_cmd = shell_cmd.build_shell_command("ip -json -det address")
iwgetbin = "/sbin/iwgetid"
if not pathlib.Path(iwgetbin).exists():
iwgetbin = "iwgetid"
self.iwgetid_cmd = shell_cmd.build_shell_command(iwgetbin)
self.init_evt = asyncio.Event()
self.libcam = self._try_import_libcamera()
def _init_allowed_services(self) -> None:
app_args = self.server.get_app_args()
data_path = app_args["data_path"]
fpath = pathlib.Path(data_path).joinpath("moonraker.asvc")
fm: FileManager = self.server.lookup_component("file_manager")
fm.add_reserved_path("allowed_services", fpath, False)
try:
if not fpath.exists():
fpath.write_text("\n".join(DEFAULT_ALLOWED_SERVICES))
data = fpath.read_text()
except Exception:
logging.exception("Failed to read allowed_services.txt")
self._allowed_services = DEFAULT_ALLOWED_SERVICES
else:
svcs = [svc.strip() for svc in data.split("\n") if svc.strip()]
for svc in svcs:
if svc.endswith(".service"):
svc = svc.rsplit(".", 1)[0]
if svc not in self._allowed_services:
self._allowed_services.append(svc)
def _update_log_rollover(self, log: bool = False) -> None:
sys_info_msg = "\nSystem Info:"
for header, info in self.system_info.items():
sys_info_msg += f"\n\n***{header}***"
if not isinstance(info, dict):
sys_info_msg += f"\n {repr(info)}"
else:
for key, val in info.items():
sys_info_msg += f"\n {key}: {val}"
sys_info_msg += "\n\n***Allowed Services***"
for svc in self._allowed_services:
sys_info_msg += f"\n {svc}"
self.server.add_log_rollover_item('system_info', sys_info_msg, log=log)
def _try_import_libcamera(self) -> Any:
try:
libcam = load_system_module("libcamera")
cmgr = libcam.CameraManager.singleton()
self.server.add_log_rollover_item(
"libcamera",
f"Found libcamera Python module, version: {cmgr.version}"
)
return libcam
except Exception:
if self.server.is_verbose_enabled():
logging.exception("Failed to import libcamera")
self.server.add_log_rollover_item(
"libcamera", "Module libcamera unavailble, import failed"
)
return None
@property
def public_ip(self) -> str:
return self._public_ip
@property
def unit_name(self) -> str:
svc_info = self.moonraker_service_info
unit_name = svc_info.get("unit_name", "moonraker.service")
return unit_name.split(".", 1)[0]
def is_service_allowed(self, service: str) -> bool:
return (
service in self._allowed_services or
re.match(r"moonraker[_-]?\d*", service) is not None or
re.match(r"klipper[_-]?\d*", service) is not None
)
def validation_enabled(self) -> bool:
return self.validator.validation_enabled
def get_system_provider(self):
return self.sys_provider
def is_inside_container(self):
return self.inside_container
def get_provider_type(self):
return self.provider_type
def get_moonraker_service_info(self):
return dict(self.moonraker_service_info)
async def wait_for_init(
self, timeout: Optional[float] = None
) -> None:
try:
await asyncio.wait_for(self.init_evt.wait(), timeout)
except asyncio.TimeoutError:
pass
async def component_init(self) -> None:
eventloop = self.server.get_event_loop()
eventloop.create_task(self.update_usb_ids())
await self.validator.validation_init()
await self.sys_provider.initialize()
if not self.inside_container:
virt_info = await self.sys_provider.check_virt_status()
self.system_info['virtualization'] = virt_info
await self._parse_network_interfaces(0, notify=False)
pstats: ProcStats = self.server.lookup_component('proc_stats')
pstats.register_stat_callback(self._parse_network_interfaces)
available_svcs = self.sys_provider.get_available_services()
avail_list = list(available_svcs.keys())
self.system_info['available_services'] = avail_list
self.system_info['service_state'] = available_svcs
svc_info = await self.sys_provider.extract_service_info(
"moonraker", os.getpid()
)
self.moonraker_service_info = svc_info
self.log_service_info(svc_info)
self.init_evt.set()
async def validate_installation(self) -> bool:
return await self.validator.perform_validation()
async def on_exit(self) -> None:
await self.validator.remove_announcement()
async def _handle_machine_request(self, web_request: WebRequest) -> str:
ep = web_request.get_endpoint()
if self.inside_container:
virt_id = self.system_info['virtualization'].get(
'virt_identifier', "none")
raise self.server.error(
f"Cannot {ep.split('/')[-1]} from within a "
f"{virt_id} container")
if ep == "/machine/shutdown":
await self.sys_provider.shutdown()
elif ep == "/machine/reboot":
await self.sys_provider.reboot()
else:
raise self.server.error("Unsupported machine request")
return "ok"
async def do_service_action(self,
action: str,
service_name: str
) -> None:
await self.sys_provider.do_service_action(action, service_name)
def restart_moonraker_service(self):
async def wrapper():
try:
await self.do_service_action("restart", self.unit_name)
except Exception:
pass
self.server.get_event_loop().create_task(wrapper())
async def _handle_service_request(self, web_request: WebRequest) -> str:
name: str = web_request.get_str('service')
action = web_request.get_endpoint().split('/')[-1]
if name == self.unit_name:
if action != "restart":
raise self.server.error(
f"Service action '{action}' not available for moonraker")
self.restart_moonraker_service()
elif self.sys_provider.is_service_available(name):
await self.do_service_action(action, name)
else:
if name in self._allowed_services:
raise self.server.error(f"Service '{name}' not installed")
raise self.server.error(
f"Service '{name}' not allowed")
return "ok"
async def _handle_sysinfo_request(self,
web_request: WebRequest
) -> Dict[str, Any]:
kconn: KlippyConnection
kconn = self.server.lookup_component("klippy_connection")
sys_info = self.system_info.copy()
sys_info["instance_ids"] = {
"moonraker": self.unit_name,
"klipper": kconn.unit_name
}
dev_name = web_request.get_str('dev_name',default=None)
if dev_name !=None:
Note=open('dev_info.txt',mode='w')
Note.write(dev_name)
Note.close()
with open('dev_info.txt', 'r') as f:
content = f.read()
f.close()
self.system_info["machine_name"] = content
return {"system_info": sys_info}
async def _set_sudo_password(
self, web_request: WebRequest
) -> Dict[str, Any]:
async with self.sudo_req_lock:
self._sudo_password = web_request.get_str("password")
if not await self.check_sudo_access():
self._sudo_password = None
raise self.server.error(
"Invalid password, sudo access was denied"
)
sudo_responses = ["Sudo password successfully set."]
restart: bool = False
failed: List[Tuple[SudoCallback, str]] = []
failed_msgs: List[str] = []
if self.sudo_requests:
while self.sudo_requests:
cb, msg = self.sudo_requests.pop(0)
try:
ret = cb()
if isinstance(ret, Awaitable):
ret = await ret
msg, need_restart = ret
sudo_responses.append(msg)
restart |= need_restart
except asyncio.CancelledError:
raise
except Exception as e:
failed.append((cb, msg))
failed_msgs.append(str(e))
restart = False if len(failed) > 0 else restart
self.sudo_requests = failed
if not restart and len(sudo_responses) > 1:
# at least one successful response and not restarting
eventloop = self.server.get_event_loop()
eventloop.delay_callback(
.05, self.server.send_event,
"machine:sudo_alert",
{
"sudo_requested": self.sudo_requested,
"request_messages": self.sudo_request_messages
}
)
if failed_msgs:
err_msg = "\n".join(failed_msgs)
raise self.server.error(err_msg, 500)
if restart:
self.restart_moonraker_service()
sudo_responses.append(
"Moonraker is currently in the process of restarting."
)
return {
"sudo_responses": sudo_responses,
"is_restarting": restart
}
async def _handle_sudo_info(
self, web_request: WebRequest
) -> Dict[str, Any]:
check_access = web_request.get_boolean("check_access", False)
has_sudo: Optional[bool] = None
if check_access:
has_sudo = await self.check_sudo_access()
return {
"sudo_access": has_sudo,
"linux_user": self.linux_user,
"sudo_requested": self.sudo_requested,
"request_messages": self.sudo_request_messages
}
async def _handle_serial_request(self, web_request: WebRequest) -> Dict[str, Any]:
return {
"serial_devices": await self.detect_serial_devices()
}
async def _handle_usb_request(self, web_request: WebRequest) -> Dict[str, Any]:
return {
"usb_devices": await self.detect_usb_devices()
}
async def _handle_can_query(self, web_request: WebRequest) -> Dict[str, Any]:
interface = web_request.get_str("interface", "can0")
return {
"can_uuids": await self.query_can_uuids(interface)
}
async def _handle_video_request(self, web_request: WebRequest) -> Dict[str, Any]:
return await self.detect_video_devices()
def get_system_info(self) -> Dict[str, Any]:
return self.system_info
@property
def sudo_password(self) -> Optional[str]:
return self._sudo_password
@sudo_password.setter
def sudo_password(self, pwd: Optional[str]) -> None:
self._sudo_password = pwd
@property
def sudo_requested(self) -> bool:
return len(self.sudo_requests) > 0
@property
def linux_user(self) -> str:
return getpass.getuser()
@property
def sudo_request_messages(self) -> List[str]:
return [req[1] for req in self.sudo_requests]
def register_sudo_request(
self, callback: SudoCallback, message: str
) -> None:
self.sudo_requests.append((callback, message))
self.server.send_event(
"machine:sudo_alert",
{
"sudo_requested": True,
"request_messages": self.sudo_request_messages
}
)
async def check_sudo_access(self, cmds: List[str] = []) -> bool:
if not cmds:
cmds = ["systemctl --version", "ls /root"]
shell_cmd: SCMDComp = self.server.lookup_component("shell_command")
for cmd in cmds:
try:
await self.exec_sudo_command(cmd, timeout=10.)
except shell_cmd.error:
return False
return True
async def exec_sudo_command(
self, command: str, tries: int = 1, timeout=2.
) -> str:
proc_input = None
full_cmd = f"sudo {command}"
if self._sudo_password is not None:
proc_input = self._sudo_password
full_cmd = f"sudo -S {command}"
shell_cmd: SCMDComp = self.server.lookup_component("shell_command")
return await shell_cmd.exec_cmd(
full_cmd, proc_input=proc_input, log_complete=False, attempts=tries,
timeout=timeout
)
def _get_sdcard_info(self) -> Dict[str, Any]:
sd_info: Dict[str, Any] = {}
cid_file = pathlib.Path(SD_CID_PATH)
if not cid_file.exists():
# No SDCard detected at mmcblk0
return {}
try:
cid_text = cid_file.read_text().strip().lower()
mid = cid_text[:2]
sd_info['manufacturer_id'] = mid
sd_info['manufacturer'] = SD_MFGRS.get(mid, "Unknown")
sd_info['oem_id'] = cid_text[2:6]
sd_info['product_name'] = bytes.fromhex(cid_text[6:16]).decode(
encoding="ascii", errors="ignore")
sd_info['product_revision'] = \
f"{int(cid_text[16], 16)}.{int(cid_text[17], 16)}"
sd_info['serial_number'] = cid_text[18:26]
mfg_year = int(cid_text[27:29], 16) + 2000
mfg_month = int(cid_text[29], 16)
sd_info['manufacturer_date'] = f"{mfg_month}/{mfg_year}"
except Exception:
logging.info("Error reading SDCard CID Register")
return {}
sd_info['capacity'] = "Unknown"
sd_info['total_bytes'] = 0
csd_file = pathlib.Path(SD_CSD_PATH)
# Read CSD Register
try:
csd_reg = bytes.fromhex(csd_file.read_text().strip())
csd_type = (csd_reg[0] >> 6) & 0x3
if csd_type == 0:
# Standard Capacity (CSD Version 1.0)
max_block_len: int = 2**(csd_reg[5] & 0xF)
c_size = ((csd_reg[6] & 0x3) << 10) | (csd_reg[7] << 2) | \
((csd_reg[8] >> 6) & 0x3)
c_mult_reg = ((csd_reg[9] & 0x3) << 1) | (csd_reg[10] >> 7)
c_mult = 2**(c_mult_reg + 2)
total_bytes: int = (c_size + 1) * c_mult * max_block_len
sd_info['capacity'] = f"{(total_bytes / (1024.0**2)):.1f} MiB"
elif csd_type == 1:
# High Capacity (CSD Version 2.0)
c_size = ((csd_reg[7] & 0x3F) << 16) | (csd_reg[8] << 8) | \
csd_reg[9]
total_bytes = (c_size + 1) * 512 * 1024
sd_info['capacity'] = f"{(total_bytes / (1024.0**3)):.1f} GiB"
elif csd_type == 2:
# Ultra Capacity (CSD Version 3.0)
c_size = ((csd_reg[6]) & 0xF) << 24 | (csd_reg[7] << 16) | \
(csd_reg[8] << 8) | csd_reg[9]
total_bytes = (c_size + 1) * 512 * 1024
sd_info['capacity'] = f"{(total_bytes / (1024.0**4)):.1f} TiB"
else:
# Invalid CSD, skip capacity check
return sd_info
sd_info['total_bytes'] = total_bytes
except Exception:
logging.info("Error Reading SDCard CSD Register")
return sd_info
def _get_cpu_info(self) -> Dict[str, Any]:
cpu_file = pathlib.Path("/proc/cpuinfo")
mem_file = pathlib.Path("/proc/meminfo")
cpu_info = {
'cpu_count': os.cpu_count(),
'bits': platform.architecture()[0],
'processor': platform.processor() or platform.machine(),
'cpu_desc': "",
'serial_number': "",
'hardware_desc': "",
'model': "",
'total_memory': None,
'memory_units': ""
}
if cpu_file.exists():
try:
cpu_text = cpu_file.read_text().strip()
cpu_items = [item.strip() for item in cpu_text.split("\n\n")
if item.strip()]
for item in cpu_items:
cpu_desc_match = re.search(r"model name\s+:\s+(.+)", item)
if cpu_desc_match is not None:
cpu_info['cpu_desc'] = cpu_desc_match.group(1).strip()
break
hw_match = re.search(r"Hardware\s+:\s+(.+)", cpu_items[-1])
if hw_match is not None:
cpu_info['hardware_desc'] = hw_match.group(1).strip()
sn_match = re.search(r"Serial\s+:\s+0*(.+)", cpu_items[-1])
if sn_match is not None:
cpu_info['serial_number'] = sn_match.group(1).strip()
model_match = re.search(r"Model\s+:\s+(.+)", cpu_items[-1])
if model_match is not None:
cpu_info['model'] = model_match.group(1).strip()
except Exception:
logging.info("Error Reading /proc/cpuinfo")
if mem_file.exists():
try:
mem_text = mem_file.read_text().strip()
for line in mem_text.split('\n'):
line = line.strip()
if line.startswith("MemTotal:"):
parts = line.split()
cpu_info['total_memory'] = int(parts[1])
cpu_info['memory_units'] = parts[2]
break
except Exception:
logging.info("Error Reading /proc/meminfo")
return cpu_info
def _check_inside_container(self) -> Dict[str, Any]:
cgroup_file = pathlib.Path(CGROUP_PATH)
virt_type = virt_id = "none"
if cgroup_file.exists():
try:
data = cgroup_file.read_text()
container_types = ["docker", "lxc"]
for ct in container_types:
if ct in data:
self.inside_container = True
virt_type = "container"
virt_id = ct
logging.info(
f"Container detected via cgroup: {ct}"
)
break
except Exception:
logging.exception(f"Error reading {CGROUP_PATH}")
# Fall back to process schedule check
if not self.inside_container:
sched_file = pathlib.Path(SCHED_PATH)
if sched_file.exists():
try:
data = sched_file.read_text().strip()
proc_name = data.split('\n')[0].split()[0]
if proc_name not in ["init", "systemd"]:
self.inside_container = True
virt_type = "container"
virt_id = "lxc"
if (
os.path.exists("/.dockerenv") or
os.path.exists("/.dockerinit")
):
virt_id = "docker"
logging.info(
f"Container detected via sched: {virt_id}"
)
except Exception:
logging.exception(f"Error reading {SCHED_PATH}")
return {
'virt_type': virt_type,
'virt_identifier': virt_id
}
async def _parse_network_interfaces(self,
sequence: int,
notify: bool = True
) -> None:
if sequence % NETWORK_UPDATE_SEQUENCE:
return
network: Dict[str, Any] = {}
canbus: Dict[str, Any] = {}
try:
# get network interfaces
resp = await self.addr_cmd.run_with_response(log_complete=False)
decoded: List[Dict[str, Any]] = jsonw.loads(resp)
for interface in decoded:
if interface['operstate'] != "UP":
continue
if interface['link_type'] == "can":
infodata: dict = interface.get(
"linkinfo", {}).get("info_data", {})
canbus[interface['ifname']] = {
'tx_queue_len': interface['txqlen'],
'bitrate': infodata.get("bittiming", {}).get(
"bitrate", -1
),
'driver': infodata.get("bittiming_const", {}).get(
"name", "unknown"
)
}
elif (
interface['link_type'] == "ether" and
'address' in interface
):
addresses: List[Dict[str, Any]] = [
{
'family': IP_FAMILIES[addr['family']],
'address': addr['local'],
'is_link_local': addr.get('scope', "") == "link"
}
for addr in interface.get('addr_info', [])
if 'family' in addr and 'local' in addr
]
if not addresses:
continue
network[interface['ifname']] = {
'mac_address': interface['address'],
'ip_addresses': addresses
}
except Exception:
logging.exception("Error processing network update")
return
prev_network = self.system_info.get('network', {})
if network != prev_network:
self._find_public_ip()
if notify:
self.server.send_event("machine:net_state_changed", network)
self.system_info['network'] = network
self.system_info['canbus'] = canbus
async def get_public_network(self) -> Dict[str, Any]:
wifis = await self._get_wifi_interfaces()
public_intf = self._find_public_interface()
ifname = public_intf["ifname"]
is_wifi = ifname in wifis
public_intf["is_wifi"] = is_wifi
if is_wifi:
public_intf["ssid"] = wifis[ifname]
# TODO: Can we detect the private top level domain? That
# would be ideal
public_intf["hostname"] = socket.gethostname()
return public_intf
def _find_public_interface(self) -> Dict[str, Any]:
src_ip = self._find_public_ip()
networks = self.system_info.get("network", {})
for ifname, ifinfo in networks.items():
for addrinfo in ifinfo["ip_addresses"]:
if addrinfo["is_link_local"]:
continue
fam = addrinfo["family"]
addr = addrinfo["address"]
if fam == "ipv6" and not src_ip:
ip = ipaddress.ip_address(addr)
if ip.is_global:
return {
"ifname": ifname,
"address": addr,
"family": fam
}
elif src_ip == addr:
return {
"ifname": ifname,
"address": addr,
"family": fam
}
return {
"ifname": "",
"address": src_ip or "",
"family": ""
}
def _find_public_ip(self) -> str:
# Check for an IPv4 Source IP
# NOTE: It should also be possible to extract this from
# the routing table, ie: ip -json route
# It would be an entry with a "gateway" with the lowest
# metric. Might also be able to get IPv6 info from this.
# However, it would be better to use NETLINK for this rather
# than run another shell command
src_ip: str = ""
# First attempt: use "broadcast" to find the local IP
addr_info = [
("<broadcast>", 0, socket.AF_INET),
("10.255.255.255", 1, socket.AF_INET),
("2001:db8::1234", 1, socket.AF_INET6),
]
for (addr, port, fam) in addr_info:
s = socket.socket(fam, socket.SOCK_DGRAM | socket.SOCK_NONBLOCK)
try:
if addr == "<broadcast>":
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.connect((addr, port))
src_ip = s.getsockname()[0]
except Exception:
continue
logging.info(f"Detected Local IP: {src_ip}")
break
if src_ip != self._public_ip:
self._public_ip = src_ip
self.server.send_event("machine:public_ip_changed", src_ip)
if not src_ip:
logging.info("Failed to detect local IP address")
return src_ip
async def _get_wifi_interfaces(self) -> Dict[str, Any]:
# get wifi interfaces
shell_cmd: SCMDComp = self.server.lookup_component('shell_command')
wifi_intfs: Dict[str, Any] = {}
try:
resp = await self.iwgetid_cmd.run_with_response(log_complete=False)
except shell_cmd.error:
logging.info("Failed to run 'iwgetid' command")
return {}
if resp:
for line in resp.split("\n"):
parts = line.strip().split(maxsplit=1)
wifi_intfs[parts[0]] = parts[1].split(":")[-1].strip('"')
return wifi_intfs
def log_service_info(self, svc_info: Dict[str, Any]) -> None:
if not svc_info:
return
name = svc_info.get("unit_name", "unknown")
manager = svc_info.get("manager", "systemd").capitalize()
msg = f"\n{manager} unit {name}:"
for key, val in svc_info.items():
if key == "properties":
msg += "\nProperties:"
for prop_key, prop in val.items():
msg += f"\n**{prop_key}={prop}"
else:
msg += f"\n{key}: {val}"
self.server.add_log_rollover_item(name, msg)
async def update_usb_ids(self, force: bool = False) -> None:
async with self.periph_lock:
db: MoonrakerDatabase = self.server.lookup_component("database")
client: HttpClient = self.server.lookup_component("http_client")
dpath = pathlib.Path(self.server.get_app_arg("data_path"))
usb_ids_path = pathlib.Path(dpath).joinpath("misc/usb.ids")
if usb_ids_path.is_file() and not force:
return
usb_id_req_info: Dict[str, str]
usb_id_req_info = await db.get_item("moonraker", "usb_id_req_info", {})
etag: Optional[str] = usb_id_req_info.pop("etag", None)
last_modified: Optional[str] = usb_id_req_info.pop("last_modified", None)
headers = {"Accept": "text/plain"}
if etag is not None and usb_ids_path.is_file():
headers["If-None-Match"] = etag
if last_modified is not None and usb_ids_path.is_file():
headers["If-Modified-Since"] = last_modified
logging.info("Fetching latest usb.ids file...")
resp = await client.get(
USB_IDS_URL, headers, enable_cache=False
)
if resp.has_error():
logging.info("Failed to retrieve usb.ids file")
return
if resp.status_code == 304:
logging.info("USB IDs file up to date")
return
# Save etag and modified headers
if resp.etag is not None:
usb_id_req_info["etag"] = resp.etag
if resp.last_modified is not None:
usb_id_req_info["last_modifed"] = resp.last_modified
await db.insert_item("moonraker", "usb_id_req_info", usb_id_req_info)
# Write file
logging.info("Writing usb.ids file...")
eventloop = self.server.get_event_loop()
await eventloop.run_in_thread(usb_ids_path.write_bytes, resp.content)
async def detect_serial_devices(self) -> List[Dict[str, Any]]:
async with self.periph_lock:
eventloop = self.server.get_event_loop()
return await eventloop.run_in_thread(sysfs_devs.find_serial_devices)
async def detect_usb_devices(self) -> List[Dict[str, Any]]:
async with self.periph_lock:
eventloop = self.server.get_event_loop()
return await eventloop.run_in_thread(self._do_usb_detect)
def _do_usb_detect(self) -> List[Dict[str, Any]]:
data_path = pathlib.Path(self.server.get_app_args()["data_path"])
usb_id_path = data_path.joinpath("misc/usb.ids")
usb_id_data = sysfs_devs.UsbIdData(usb_id_path)
dev_list = sysfs_devs.find_usb_devices()
for usb_dev_info in dev_list:
cls_ids: List[str] = usb_dev_info.pop("class_ids", None)
class_info = usb_id_data.get_class_info(*cls_ids)
usb_dev_info.update(class_info)
prod_info = usb_id_data.get_product_info(
usb_dev_info["vendor_id"], usb_dev_info["product_id"]
)
for field, desc in prod_info.items():
if usb_dev_info.get(field) is None:
usb_dev_info[field] = desc
return dev_list
async def query_can_uuids(self, interface: str) -> List[Dict[str, Any]]:
async with self.periph_lock:
cansock = cansocket.CanSocket(interface)
uuids = await cansocket.query_klipper_uuids(cansock)
cansock.close()
return uuids
async def detect_video_devices(self) -> Dict[str, List[Dict[str, Any]]]:
async with self.periph_lock:
eventloop = self.server.get_event_loop()
v4l2_devs = await eventloop.run_in_thread(sysfs_devs.find_video_devices)
libcam_devs = await eventloop.run_in_thread(self.get_libcamera_devices)
return {
"v4l2_devices": v4l2_devs,
"libcamera_devices": libcam_devs
}
def get_libcamera_devices(self) -> List[Dict[str, Any]]:
libcam = self.libcam
libcam_devs: List[Dict[str, Any]] = []
if libcam is not None:
cm = libcam.CameraManager.singleton()
for cam in cm.cameras:
device: Dict[str, Any] = {"libcamera_id": cam.id}
props_by_name = {cid.name: val for cid, val in cam.properties.items()}
device["model"] = props_by_name.get("Model")
modes: List[Dict[str, Any]] = []
cam_config = cam.generate_configuration([libcam.StreamRole.Raw])
for stream_cfg in cam_config:
formats = stream_cfg.formats
for pix_fmt in formats.pixel_formats:
cur_mode: Dict[str, Any] = {"format": str(pix_fmt)}
resolutions: List[str] = []
for size in formats.sizes(pix_fmt):
resolutions.append(str(size))
cur_mode["resolutions"] = resolutions
modes.append(cur_mode)
device["modes"] = modes
libcam_devs.append(device)
return libcam_devs
class BaseProvider:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.shutdown_action = config.get("shutdown_action", "poweroff")
self.shutdown_action = self.shutdown_action.lower()
if self.shutdown_action not in ["halt", "poweroff"]:
raise config.error(
"Section [machine], Option 'shutdown_action':"
f"Invalid value '{self.shutdown_action}', must be "
"'halt' or 'poweroff'"
)
self.available_services: Dict[str, Dict[str, str]] = {}
self.shell_cmd: SCMDComp = self.server.load_component(
config, 'shell_command')
async def initialize(self) -> None:
pass
async def _exec_sudo_command(self, command: str):
machine: Machine = self.server.lookup_component("machine")
return await machine.exec_sudo_command(command)
async def shutdown(self) -> None:
await self._exec_sudo_command(f"systemctl {self.shutdown_action}")
async def reboot(self) -> None:
await self._exec_sudo_command("systemctl reboot")
async def do_service_action(self,
action: str,
service_name: str
) -> None:
raise self.server.error("Service Actions Not Available", 503)
async def check_virt_status(self) -> Dict[str, Any]:
return {
'virt_type': "unknown",
'virt_identifier': "unknown"
}
def is_service_available(self, service: str) -> bool:
return service in self.available_services
def get_available_services(self) -> Dict[str, Dict[str, str]]:
return self.available_services