-
Notifications
You must be signed in to change notification settings - Fork 7
/
bort_cli.py
executable file
·1320 lines (1118 loc) · 46 KB
/
bort_cli.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*
import abc
import argparse # requires Python 3.2+
import datetime
import glob
import logging
import logging.handlers
import os
import platform
import re
import shlex
import shutil
import subprocess
import sys
import tempfile
from string import Template
from typing import Any, Dict, Iterable, List, Optional, Tuple
LOG_FILE = "validate-sdk-integration.log"
logging.basicConfig(format="%(message)s", level=logging.INFO)
DEFAULT_ENCODING = "utf-8"
PLACEHOLDER_BORT_AOSP_PATCH_VERSION = "manually_patched"
PLACEHOLDER_BORT_APP_ID = "vnd.myandroid.bortappid"
PLACEHOLDER_BORT_OTA_APP_ID = "vnd.myandroid.bort.otaappid"
PLACEHOLDER_FEATURE_NAME = "vnd.myandroid.bortfeaturename"
PLACEHOLDER_SYSTEM = "__SYSTEM_PATH__"
RELEASES = range(8, 14 + 1)
SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
GRADLE_PROPERTIES = os.path.join(SCRIPT_DIR, "MemfaultPackages", "gradle.properties")
PYTHON_MIN_VERSION = (3, 6, 0)
USAGE_REPORTER_APPLICATION_ID = "com.memfault.usagereporter"
USAGE_REPORTER_APK_PATH = r"package:/(system|system_ext|system/system_ext)/priv-app/MemfaultUsageReporter/MemfaultUsageReporter.apk"
MEMFAULT_DUMPSTATE_RUNNER_PATH = f"/{PLACEHOLDER_SYSTEM}/bin/MemfaultDumpstateRunner"
MEMFAULT_INIT_RC_PATH = f"/{PLACEHOLDER_SYSTEM}/etc/init/memfault_init.rc"
MEMFAULT_DUMPSTER_PATH = f"/{PLACEHOLDER_SYSTEM}/bin/MemfaultDumpster"
MEMFAULT_DUMPSTER_DATA_PATH = "/data/system/MemfaultDumpster/"
MEMFAULT_DUMPSTER_RC_PATH = f"/{PLACEHOLDER_SYSTEM}/etc/init/memfault_dumpster.rc"
MEMFAULT_STRUCTURED_RC_PATH = f"/{PLACEHOLDER_SYSTEM}/etc/init/memfault_structured_logd.rc"
MEMFAULT_STRUCTURED_APPLICATION_ID = "com.memfault.structuredlogd"
BORT_APK_PATH = (
r"package:/(system|system_ext|system/system_ext)/priv-app/MemfaultBort/MemfaultBort.apk"
)
BORT_OTA_APK_PATH = (
r"package:/(system|system_ext|system/system_ext)/priv-app/MemfaultBortOta/MemfaultBortOta.apk"
)
VENDOR_CIL_PATH = "/vendor/etc/selinux/vendor_sepolicy.cil"
LOG_ENTRY_SEPARATOR = "============================================================"
def shlex_join(cmd):
"""
Backport of shlex.join (which would require Python 3.8+)
"""
return " ".join(cmd)
def readable_dir_type(path):
"""
Arg parser for directory paths
"""
if os.path.isdir(path) and os.access(path, os.R_OK):
return path
raise argparse.ArgumentTypeError("Couldn't find/access directory %r" % path)
def executable_bin_type(path):
"""
Arg parser for binary paths
"""
if os.path.isfile(path) and os.access(path, os.X_OK):
return path
raise argparse.ArgumentTypeError("Couldn't find/access binary at %s" % path)
def shell_command_type(arg):
"""
Argument type for shell commands
"""
parts = shlex.split(arg)
if not parts:
raise argparse.ArgumentTypeError("%s is not a valid command" % arg)
cmd = parts[0]
if not shutil.which(cmd):
raise argparse.ArgumentTypeError("Couldn't find executable %s" % cmd)
return parts
def android_application_id_type(arg):
"""
Argument type for Android Application ID
"""
if not re.match(r"^([a-z][a-z0-9]+)(\.[a-z][a-z0-9]+)+$", arg, re.RegexFlag.IGNORECASE):
raise argparse.ArgumentTypeError("Not a valid application ID: %r" % arg)
return arg
def _replace_placeholders(content, mapping):
for placeholder, value in mapping.items():
content = content.replace(placeholder, value)
return content
def _get_bort_version():
properties = {}
with open(GRADLE_PROPERTIES) as properties_file:
for line in properties_file:
matches = re.match(r"^([A-Z_]+)=(.*)\s+$", line)
if matches:
properties[matches.group(1)] = matches.group(2)
return "%s.%s.%s" % (
properties["UPSTREAM_MAJOR_VERSION"],
properties["UPSTREAM_MINOR_VERSION"],
properties["UPSTREAM_PATCH_VERSION"],
)
class Command(abc.ABC):
"""
Base class for commands
"""
@abc.abstractmethod
def run(self):
pass
class PatchAOSPCommand(Command):
def __init__(
self,
aosp_root,
check_patch_command,
apply_patch_command,
force,
android_release,
patch_dir,
exclude,
):
self._aosp_root = aosp_root
self._check_patch_command = check_patch_command or self._default_check_patch_command()
self._apply_patch_command = apply_patch_command or self._default_apply_patch_command()
self._force = force
self._patches_dir = os.path.join(patch_dir, f"android-{android_release}")
self._exclude_dirs = exclude or []
self._errors = []
self._warnings = []
@classmethod
def register(cls, create_parser):
parser = create_parser(cls, "patch-aosp")
parser.add_argument(
"aosp_root", type=readable_dir_type, help="The path of the checked out AOSP repository"
)
parser.add_argument(
"--android-release",
type=int,
choices=RELEASES,
required=True,
help="Android platform version",
)
parser.add_argument(
"--check-patch-command",
type=shell_command_type,
default=None,
help="Command to check whether patch is applied. Expected to exit with status 0 if patch is applied.",
)
parser.add_argument(
"--apply-patch-command",
type=shell_command_type,
default=None,
help="Command to apply patch. The patch is provided through stdin.",
)
parser.add_argument(
"--force",
action="store_true",
default=False,
help="Apply patch, even when already applied.",
)
parser.add_argument(
"--exclude", action="append", help="Directories to exclude from patching"
)
parser.add_argument(
"--patch-dir",
type=str,
default=os.path.join(SCRIPT_DIR, "patches"),
help="Directory containing versioned patches to apply",
)
@staticmethod
def _default_apply_patch_command():
try:
return shell_command_type("patch -f -p1")
except argparse.ArgumentTypeError as error:
sys.exit(str(error))
@staticmethod
def _default_check_patch_command():
try:
return shell_command_type("patch -R -p1 --dry-run")
except argparse.ArgumentTypeError as error:
sys.exit(str(error))
def run(self):
self._apply_all_patches()
if self._errors:
sys.exit("Some patches couldn't be applied.")
if self._warnings:
sys.exit("Some optional patches couldn't be applied.")
logging.info("All patches applied successfully.")
def _apply_all_patches(self):
glob_pattern = os.path.join(self._patches_dir, "**", "git.diff")
mapping = {
PLACEHOLDER_BORT_AOSP_PATCH_VERSION: _get_bort_version(),
}
for patch_abspath in glob.iglob(glob_pattern, recursive=True):
patch_relpath = os.path.relpath(patch_abspath, self._patches_dir)
repo_subdir = os.path.dirname(patch_relpath)
if repo_subdir in self._exclude_dirs:
logging.info("Skipping patch: %r: excluded!", patch_relpath)
continue
with open(patch_abspath) as patch_file:
content = _replace_placeholders(patch_file.read(), mapping)
if not self._force and self._check_patch(repo_subdir, patch_relpath, content):
continue # Already applied!
self._apply_patch(repo_subdir, patch_relpath, content)
def _check_patch(self, repo_subdir, patch_relpath, content) -> bool:
check_cmd = self._check_patch_command
try:
subprocess.check_output(
check_cmd,
cwd=os.path.join(self._aosp_root, repo_subdir),
input=content.encode(DEFAULT_ENCODING),
)
except (subprocess.CalledProcessError, FileNotFoundError):
return False
logging.info("Skipping patch %r: already applied!", patch_relpath)
return True
def _apply_patch(self, repo_subdir, patch_relpath, content):
apply_cmd = self._apply_patch_command
logging.info("Running %r (in %r)", shlex_join(apply_cmd), repo_subdir)
try:
output = subprocess.check_output(
apply_cmd,
cwd=os.path.join(self._aosp_root, repo_subdir),
input=content.encode(DEFAULT_ENCODING),
stderr=sys.stderr,
)
logging.info(output.decode(DEFAULT_ENCODING))
except (subprocess.CalledProcessError, FileNotFoundError):
if repo_subdir == "device/google/cuttlefish":
logging.exception(
"Failed to apply %r (only needed for Cuttlefish/AVD)", patch_relpath
)
self._warnings.append(patch_relpath)
else:
logging.exception("Failed to apply %r", patch_relpath)
self._errors.append(patch_relpath)
def _replace_placeholders_in_file(file_abspath, mapping):
logging.info("Patching %r with %r", file_abspath, mapping)
with open(file_abspath) as file:
content = _replace_placeholders(file.read(), mapping)
with open(file_abspath, "w") as file:
file.write(content)
class PatchBortCommand(Command):
def __init__(self, path, bort_app_id, bort_ota_app_id=None, vendor_feature_name=None):
self._path = path
self._bort_app_id = bort_app_id
self._bort_ota_app_id = bort_ota_app_id
self._vendor_feature_name = vendor_feature_name or bort_app_id
@classmethod
def register(cls, create_parser):
parser = create_parser(cls, "patch-bort")
parser.add_argument("--bort-app-id", type=android_application_id_type, required=True)
parser.add_argument("--bort-ota-app-id", type=android_application_id_type, required=False)
parser.add_argument(
"--vendor-feature-name", type=str, help="Defaults to the provided Application ID"
)
parser.add_argument(
"path",
type=readable_dir_type,
help="The path to the MemfaultPackages folder from the SDK",
)
def run(self):
for file_relpath in [
"bort.properties",
]:
replacements = {
PLACEHOLDER_BORT_APP_ID: self._bort_app_id,
PLACEHOLDER_FEATURE_NAME: self._vendor_feature_name,
}
if self._bort_ota_app_id:
replacements[PLACEHOLDER_BORT_OTA_APP_ID] = self._bort_ota_app_id
file_abspath = os.path.join(self._path, file_relpath)
_replace_placeholders_in_file(
file_abspath,
mapping=replacements,
)
def _get_shell_cmd_output_and_errors(
*, description: str, cmd: Tuple
) -> Tuple[Optional[str], List[str]]:
logging.info("\n%s", description)
shell_cmd = shlex_join(cmd)
logging.info("\t%s", shell_cmd)
def _shell_command():
try:
return shell_command_type(shell_cmd)
except argparse.ArgumentTypeError as arg_error:
sys.exit(str(arg_error))
try:
# In case the host system is Windows, adb will used \r\n as line endings, and this breaks our regexes, so
# configure universal newlines.
output = subprocess.check_output(
_shell_command(), stderr=sys.stderr, encoding="utf-8", universal_newlines=True
)
except subprocess.CalledProcessError as error:
return None, [str(error)]
result: str = output[:-1] # Trim trailing newline
return result, []
def _create_adb_command(cmd: Tuple, device: Optional[str] = None) -> Tuple:
return ("adb", *(("-s", device) if device else ()), *cmd)
def _get_adb_shell_cmd_output_and_errors(
*, description: str, cmd, device: Optional[str] = None
) -> Tuple[Optional[str], List[str]]:
return _get_shell_cmd_output_and_errors(
description=description, cmd=_create_adb_command(("shell", *cmd), device=device)
)
def _query_provider(uri: str, device: Optional[str] = None) -> Tuple[Optional[str], List[str]]:
return _get_shell_cmd_output_and_errors(
description="contentprovider",
cmd=_create_adb_command(("shell", "content", "query", "--uri", uri), device=device),
)
def _query_jobscheduler(
package: str, device: Optional[str] = None
) -> Tuple[Optional[str], List[str]]:
return _get_shell_cmd_output_and_errors(
description="jobscheduler",
cmd=_create_adb_command(("shell", "dumpsys", "jobscheduler", package), device=device),
)
class _Matcher(abc.ABC):
@abc.abstractmethod
def __call__(self, adb_output: str) -> Tuple[bool, str]:
pass
class _RegexMatcher(_Matcher):
def __init__(self, pattern: str) -> None:
self._re = re.compile(pattern, flags=re.RegexFlag.MULTILINE)
def __call__(self, adb_output: str) -> Tuple[bool, str]:
return bool(self._re.search(adb_output)), f"Expected pattern: {self._re.pattern}"
class _IdleWhitelistMatcher(_Matcher):
def __init__(self, bort_app_id: str) -> None:
self._bort_app_id = bort_app_id
def __call__(self, output: str) -> Tuple[bool, str]:
lines = output.splitlines()
for idx, line in enumerate(lines):
if "Whitelist system apps:" in line:
whitelist_start = idx
break
else:
return False, "Failed to find 'Whitelist system apps' in output"
for line in lines[whitelist_start:]:
if self._bort_app_id in line:
return True, f"Found '{self._bort_app_id}'"
return False, f"Failed to find '{self._bort_app_id}' in 'Whitelist system apps' list"
class _ConnectedDeviceMatcher(_Matcher):
def __init__(self, device: Optional[str]) -> None:
self._device = device
def __call__(self, output: str) -> Tuple[bool, str]:
lines = output.splitlines()
if len(lines) < 2:
return False, "Too few output lines from 'adb devices'"
if "List of devices attached" not in lines[0]:
return False, "Unexpected output from 'adb devices'"
# If a device was provided, verify it's connected
if self._device:
for line in lines[1:]:
if self._device in line:
return True, f"Found '{self._device}'"
return False, f"Failed to find '{self._device}'"
# Otherwise, verify any device is connected
# Entries look like 'XXX device'
for line in lines[1:]:
if "device" in line:
return True, "Found a device"
return False, "No connected devices"
class _AlwaysMatcher(_Matcher):
def __call__(self, output: str) -> Tuple[bool, str]:
return True, "OK"
def _format_error(description: str, *details: Any) -> str: # noqa: ANN401
return (2 * os.linesep).join(map(str, ("", description, *details)))
def _expect_or_errors(*, output: Optional[str], description: str, matcher: _Matcher) -> List[str]:
if output is None:
return [_format_error(description, "No output to match")]
passed, reason = matcher(output)
if not passed:
logging.info("\t Test failed")
return [_format_error(description, "Output did not match:", output, reason)]
logging.info("\tTest passed")
return []
def _run_shell_cmd_and_expect(*, description: str, cmd: Tuple, matcher: _Matcher) -> List[str]:
output, errors = _get_shell_cmd_output_and_errors(description=description, cmd=cmd)
if errors:
return errors
return _expect_or_errors(output=output, description=description, matcher=matcher)
def _run_adb_shell_cmd_and_expect(
*, description: str, cmd: Tuple, matcher: _Matcher, device: Optional[str] = None
) -> List[str]:
output, errors = _get_adb_shell_cmd_output_and_errors(
description=description, cmd=cmd, device=device
)
if errors:
return errors
return _expect_or_errors(output=output, description=description, matcher=matcher)
def _run_adb_shell_dumpsys_package(
package_id: str, device: Optional[str] = None
) -> Tuple[Optional[str], List[str]]:
output, errors = _get_adb_shell_cmd_output_and_errors(
description=f"Querying package info for {package_id}",
cmd=("dumpsys", "package", package_id),
device=device,
)
unable_to_find_str = f"Unable to find package: {package_id}"
if output and unable_to_find_str in output:
return None, [_format_error(unable_to_find_str, output)]
return output, errors
def _check_file_ownership_and_secontext(
*,
path: str,
mode: str,
owner: str,
group: str,
secontext: str,
device: Optional[str] = None,
directory: bool = False,
) -> List[str]:
return _run_adb_shell_cmd_and_expect(
description=f"Verifying {path} is installed correctly",
cmd=("ls", "-lZd" if directory else "-lZ", path),
matcher=_RegexMatcher(rf"^{mode}\s[0-9]+\s{owner}\s{group}\s{secontext}.*{path}$"),
device=device,
)
def _log_errors(errors: Iterable[str]) -> None:
for error in errors:
logging.info(LOG_ENTRY_SEPARATOR)
logging.info(error)
def _verify_device_connected(device: Optional[str] = None) -> List[str]:
"""
If a target device is specified, verify that specific is connected. Otherwise, verify any device is connected.
If there are multiple devices, `-s` (thus `--device`) must be used as well.
"""
return _run_shell_cmd_and_expect(
description="Verifying device is connected",
cmd=("adb", "devices"),
matcher=_ConnectedDeviceMatcher(device),
)
def _check_bort_app_id(bort_app_id: str) -> None:
if bort_app_id == PLACEHOLDER_BORT_APP_ID:
sys.exit(
f"Invalid application ID '{bort_app_id}'. Please configure BORT_APPLICATION_ID in bort.properties."
)
def _check_bort_ota_app_id(bort_ota_app_id: str) -> None:
if bort_ota_app_id == PLACEHOLDER_BORT_OTA_APP_ID:
sys.exit(
f"Invalid application ID '{bort_ota_app_id}'. Please configure BORT_OTA_APPLICATION_ID in bort.properties."
)
def _check_feature_name(feature_name: str) -> None:
if feature_name == PLACEHOLDER_FEATURE_NAME:
sys.exit(
f"Invalid feature name '{feature_name}'. Please configure BORT_FEATURE_NAME in bort.properties."
)
def _send_broadcast(
bort_app_id: str, description: str, broadcast: Tuple, device: Optional[str] = None
):
_check_bort_app_id(bort_app_id)
output, errors = _get_adb_shell_cmd_output_and_errors(
description=description, cmd=broadcast, device=device
)
logging.info(output)
if errors:
_log_errors(errors)
sys.exit(" Failure: unable to send broadcast")
logging.info("Sent broadcast: check logcat logs for result")
class RequestBugReport(Command):
def __init__(self, bort_app_id: str, device: Optional[str] = None):
self._bort_app_id = bort_app_id
self._device = device
@classmethod
def register(cls, create_parser):
parser = create_parser(cls, "request-bug-report")
parser.add_argument("--bort-app-id", type=android_application_id_type, required=True)
parser.add_argument(
"--device",
type=str,
help="Optional device ID passed to ADB's `-s` flag. Required if multiple devices are connected.",
)
def run(self):
_check_bort_app_id(self._bort_app_id)
broadcast_cmd = (
"am",
"broadcast",
"--receiver-include-background",
"-a",
"com.memfault.intent.action.REQUEST_BUG_REPORT",
"-n",
f"{self._bort_app_id}/com.memfault.bort.receivers.ShellControlReceiver",
)
_send_broadcast(
self._bort_app_id, "Requesting bug report from bort", broadcast_cmd, self._device
)
class RequestMetricCollection(Command):
def __init__(self, bort_app_id: str, device: Optional[str] = None):
self._bort_app_id = bort_app_id
self._device = device
@classmethod
def register(cls, create_parser):
parser = create_parser(cls, "request-metrics")
parser.add_argument("--bort-app-id", type=android_application_id_type, required=True)
parser.add_argument(
"--device",
type=str,
help="Optional device ID passed to ADB's `-s` flag. Required if multiple devices are connected.",
)
def run(self):
_check_bort_app_id(self._bort_app_id)
broadcast_cmd = (
"am",
"broadcast",
"--receiver-include-background",
"-a",
"com.memfault.intent.action.REQUEST_METRICS_COLLECTION",
"-n",
f"{self._bort_app_id}/com.memfault.bort.receivers.ShellControlReceiver",
)
_send_broadcast(
self._bort_app_id, "Requesting metric collection from bort", broadcast_cmd, self._device
)
class RequestUpdateConfig(Command):
def __init__(self, bort_app_id: str, device: Optional[str] = None):
self._bort_app_id = bort_app_id
self._device = device
@classmethod
def register(cls, create_parser):
parser = create_parser(cls, "request-update-config")
parser.add_argument("--bort-app-id", type=android_application_id_type, required=True)
parser.add_argument(
"--device",
type=str,
help="Optional device ID passed to ADB's `-s` flag. Required if multiple devices are connected.",
)
def run(self):
_check_bort_app_id(self._bort_app_id)
broadcast_cmd = (
"am",
"broadcast",
"--receiver-include-background",
"-a",
"com.memfault.intent.action.REQUEST_UPDATE_CONFIGURATION",
"-n",
f"{self._bort_app_id}/com.memfault.bort.receivers.ShellControlReceiver",
)
_send_broadcast(
self._bort_app_id,
"Requesting bort to update configuration from Memfault",
broadcast_cmd,
self._device,
)
class EnableBort(Command):
def __init__(self, bort_app_id, device=None):
self._bort_app_id = bort_app_id
self._device = device
@classmethod
def register(cls, create_parser):
parser = create_parser(cls, "enable-bort")
parser.add_argument("--bort-app-id", type=android_application_id_type, required=True)
parser.add_argument(
"--device",
type=str,
help="Optional device ID passed to ADB's `-s` flag. Required if multiple devices are connected.",
)
def run(self):
_check_bort_app_id(self._bort_app_id)
broadcast_cmd = (
"am",
"broadcast",
"--receiver-include-background",
"-a",
"com.memfault.intent.action.BORT_ENABLE",
"-n",
f"{self._bort_app_id}/com.memfault.bort.receivers.ShellControlReceiver",
"--ez",
"com.memfault.intent.extra.BORT_ENABLED",
"true",
)
_send_broadcast(self._bort_app_id, "Enabling bort", broadcast_cmd, self._device)
class OtaCheckForUpdates(Command):
def __init__(self, bort_ota_app_id, device=None):
self._bort_ota_app_id = bort_ota_app_id
self._device = device
@classmethod
def register(cls, create_parser):
parser = create_parser(cls, "ota-check")
parser.add_argument("--bort-ota-app-id", type=android_application_id_type, required=True)
parser.add_argument(
"--device",
type=str,
help="Optional device ID passed to ADB's `-s` flag. Required if multiple devices are connected.",
)
def run(self):
_check_bort_app_id(self._bort_ota_app_id)
broadcast_cmd = (
"am",
"broadcast",
"--receiver-include-background",
"-a",
"com.memfault.intent.action.OTA_CHECK_FOR_UPDATES_SHELL",
"-n",
f"{self._bort_ota_app_id}/com.memfault.bort.ota.lib.ShellCheckForUpdatesReceiver",
)
_send_broadcast(
self._bort_ota_app_id, "Checking for OTA updates", broadcast_cmd, self._device
)
class DevMode(Command):
def __init__(self, bort_app_id, enabled, device=None):
self._bort_app_id = bort_app_id
self._device = device
self._enabled = enabled
@classmethod
def register(cls, create_parser):
parser = create_parser(cls, "dev-mode")
parser.add_argument("--bort-app-id", type=android_application_id_type, required=True)
parser.add_argument("--enabled", type=str, required=True)
parser.add_argument(
"--device",
type=str,
help="Optional device ID passed to ADB's `-s` flag. Required if multiple devices are connected.",
)
def run(self):
_check_bort_app_id(self._bort_app_id)
broadcast_cmd = (
"am",
"broadcast",
"--receiver-include-background",
"-a",
"com.memfault.intent.action.DEV_MODE",
"-n",
f"{self._bort_app_id}/com.memfault.bort.receivers.ShellControlReceiver",
"--ez",
"com.memfault.intent.extra.DEV_MODE_ENABLED",
f"{self._enabled}",
)
_send_broadcast(
self._bort_app_id, "Changing Bort developer mode", broadcast_cmd, self._device
)
logging.info("")
logging.info(
"To bypass server-side rate limits temporarily for development, "
"please enable Server-Side Development Mode for this device.\n"
" - https://docs.memfault.com/docs/platform/rate-limiting/#server-side-development-mode"
)
class ValidateConnectedDevice(Command):
def __init__(
self,
bort_app_id,
bort_ota_app_id=None,
device=None,
vendor_feature_name=None,
ignore_enabled=False,
):
self._bort_app_id = bort_app_id
self._bort_ota_app_id = bort_ota_app_id
self._device = device
self._vendor_feature_name = vendor_feature_name or bort_app_id
self._errors = []
self._ignore_enabled = ignore_enabled
sdk_version = self._query_sdk_version()
if not sdk_version:
sys.exit("Failure: could not get SDK version.")
self.sdk_version = sdk_version
if self.sdk_version >= 30:
self.path_placeholders = {
PLACEHOLDER_SYSTEM: "system_ext",
}
else:
self.path_placeholders = {
PLACEHOLDER_SYSTEM: "system",
}
@classmethod
def register(cls, create_parser):
parser = create_parser(cls, "validate-sdk-integration")
parser.add_argument("--bort-app-id", type=android_application_id_type, required=True)
parser.add_argument("--bort-ota-app-id", type=android_application_id_type, required=False)
parser.add_argument(
"--device", type=str, help="Optional device ID passed to ADB's `-s` flag"
)
parser.add_argument(
"--vendor-feature-name", type=str, help="Defaults to the provided Application ID"
)
parser.add_argument("--ignore-enabled", action="store_true")
def _getprop(self, key: str) -> Optional[str]:
output, errors = _get_adb_shell_cmd_output_and_errors(
description=f"Querying {key}", cmd=("getprop", key), device=self._device
)
if errors:
self._errors.extend(errors)
return output
def _query_sdk_version(self) -> Optional[int]:
version_str = self._getprop("ro.build.version.sdk")
if version_str:
return int(version_str)
return None
def _query_build_type(self) -> Optional[str]:
return self._getprop("ro.build.type")
def _check_vendor_sepolicy_cil(self):
with tempfile.NamedTemporaryFile() as vendor_cil:
_, errors = _get_shell_cmd_output_and_errors(
description="Verifying selinux access rules",
cmd=_create_adb_command(
("pull", VENDOR_CIL_PATH, vendor_cil.name), device=self._device
),
)
if not errors:
with open(vendor_cil.name, "r") as cil:
rules = cil.read()
if not re.search(
r"allow .*_app_.* memfault_dumpster_service \(service_manager \(find\)\)",
rules,
):
errors.extend([
"Expected a selinux rule (allow priv_app memfault_dumpster_service:service_manager find), please recheck integration - see https://mflt.io/android-sepolicy"
])
return errors
def _run_checks_requiring_root(self, sdk_version: int):
_run_shell_cmd_and_expect(
description="Restarting ADB with root permissions",
cmd=_create_adb_command(("root",), device=self._device),
matcher=_AlwaysMatcher(),
)
self._errors.extend(
_check_file_ownership_and_secontext(
path=_replace_placeholders(MEMFAULT_DUMPSTATE_RUNNER_PATH, self.path_placeholders),
mode="-rwxr-xr-x",
owner="root",
group="shell",
secontext="u:object_r:dumpstate_exec:s0",
device=self._device,
)
)
self._errors.extend(
_check_file_ownership_and_secontext(
path=_replace_placeholders(MEMFAULT_INIT_RC_PATH, self.path_placeholders),
mode="-rw-r--r--",
owner="root",
group="root",
secontext="u:object_r:system_file:s0",
device=self._device,
)
)
self._errors.extend(
_check_file_ownership_and_secontext(
path=_replace_placeholders(MEMFAULT_DUMPSTER_PATH, self.path_placeholders),
mode="-rwxr-xr-x",
owner="root",
group="shell",
secontext="u:object_r:dumpstate_exec:s0",
device=self._device,
)
)
self._errors.extend(
_check_file_ownership_and_secontext(
path=_replace_placeholders(MEMFAULT_DUMPSTER_RC_PATH, self.path_placeholders),
mode="-rw-r--r--",
owner="root",
group="root",
secontext="u:object_r:system_file:s0",
device=self._device,
)
)
self._errors.extend(
_check_file_ownership_and_secontext(
path=MEMFAULT_DUMPSTER_DATA_PATH,
mode="drwx------",
owner="root",
group="root",
secontext="u:object_r:memfault_dumpster_data_file:s0",
directory=True,
device=self._device,
)
)
self._errors.extend(
_check_file_ownership_and_secontext(
path=f"/data/data/{self._bort_app_id}/",
mode="drwx------",
owner="u[0-9]+_a[0-9]+",
group="u[0-9]+_a[0-9]+",
secontext="u:object_r:bort_app_data_file:s0",
directory=True,
device=self._device,
)
)
if self._bort_ota_app_id:
context = "privapp_data_file" if sdk_version >= 29 else "app_data_file"
self._errors.extend(
_check_file_ownership_and_secontext(
path=f"/data/data/{self._bort_ota_app_id}/",
mode="drwx------",
owner="u[0-9]+_a[0-9]+",
group="u[0-9]+_a[0-9]+",
secontext=f"u:object_r:{context}:s0",
directory=True,
device=self._device,
)
)
self._errors.extend(
_check_file_ownership_and_secontext(
path=_replace_placeholders(MEMFAULT_STRUCTURED_RC_PATH, self.path_placeholders),
mode="-rw-r--r--",
owner="root",
group="root",
secontext="u:object_r:system_file:s0",
device=self._device,
)
)
self._errors.extend(
_check_file_ownership_and_secontext(
path=f"/data/data/{MEMFAULT_STRUCTURED_APPLICATION_ID}/",
mode="drwx------",
owner="system",
group="system",
secontext="u:object_r:system_app_data_file:s0",
directory=True,
device=self._device,
)
)
if sdk_version >= 28:
self._errors.extend(self._check_vendor_sepolicy_cil())
def _check_bort_permissions(self, bort_package_info: Optional[str], sdk_version: int):
for permission, min_sdk_version in (
("android.permission.FOREGROUND_SERVICE", 28),
("android.permission.RECEIVE_BOOT_COMPLETED", 1),
("android.permission.INTERNET", 1),
("android.permission.ACCESS_NETWORK_STATE", 1),
("android.permission.DUMP", 1),
("android.permission.WAKE_LOCK", 1),
("android.permission.READ_LOGS", 1),
("android.permission.PACKAGE_USAGE_STATS", 1),
("android.permission.INTERACT_ACROSS_USERS", 1),
):
if sdk_version < min_sdk_version:
logging.info(
"\nSkipping check for '%s' because it is not supported (SDK version %d < %d)",
permission,
sdk_version,
min_sdk_version,
)
continue
description = f"Verifying MemfaultBort app has permission '{permission}'"
logging.info("\n%s", description)
self._errors.extend(
_expect_or_errors(
output=bort_package_info,
description=description,
matcher=_RegexMatcher(rf"{permission}: granted=true"),
)
)
def _check_package_versions(self, *package_infos: Optional[str]):
description = "\nVerifying Bort packages have the same version"
logging.info(description)