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
#!/usr/bin/env python3
"""Record a Release build while XCTest scrolls the iPhone feed."""
import argparse
import os
from pathlib import Path
import signal
import subprocess
import sys
import time
import uuid
def stop(process, timeout=60):
if process is None or process.poll() is not None:
return
os.killpg(process.pid, signal.SIGINT)
try:
process.wait(timeout=timeout)
except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGTERM)
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGKILL)
process.wait()
def interrupted(_signal, _frame):
raise KeyboardInterrupt
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("device")
parser.add_argument("seconds", type=int, choices=range(5, 301), metavar="SECONDS")
parser.add_argument("template", choices=["Animation Hitches", "Time Profiler", "SwiftUI"])
args = parser.parse_args()
feed = os.environ.get("OLDFELLA_PROFILE_FEED", "live")
if feed not in ("live", "rich"):
parser.error("OLDFELLA_PROFILE_FEED must be live or rich.")
direction = os.environ.get("OLDFELLA_PROFILE_DIRECTION", "alternating")
if direction not in ("alternating", "forward", "manual"):
parser.error("OLDFELLA_PROFILE_DIRECTION must be alternating, forward, or manual.")
root = Path(__file__).resolve().parent.parent
directory = root / ".build" / "profiles"
directory.mkdir(parents=True, exist_ok=True)
prefix = directory / f"scroll-{time.strftime('%Y%m%d-%H%M%S')}-{os.getpid()}"
trace_path = prefix.with_suffix(".trace")
result_path = prefix.with_suffix(".xcresult")
trace_log_path = prefix.with_suffix(".trace.log")
test_log_path = prefix.with_suffix(".test.log")
notification = f"com.oldfella.profiling.ready.{uuid.uuid4().hex}"
ready = recorder = driver = None
try:
with trace_log_path.open("w") as trace_log, test_log_path.open("w") as test_log:
environment = os.environ.copy()
environment.update({
"TEST_RUNNER_OLDFELLA_DEVICE_SCROLL_PROFILE": "1",
"TEST_RUNNER_OLDFELLA_PROFILE_SECONDS": str(args.seconds),
"TEST_RUNNER_OLDFELLA_PROFILE_FEED": feed,
"TEST_RUNNER_OLDFELLA_PROFILE_DIRECTION": direction,
"TEST_RUNNER_OLDFELLA_PROFILE_START_NOTIFICATION": notification,
"NSUnbufferedIO": "YES",
})
driver = subprocess.Popen([
"xcodebuild", "-scheme", "OldFellaScrollProfile", "-configuration", "Release",
"-destination", f"platform=iOS,id={args.device}",
"-only-testing:OldFellaUITests/DeviceScrollProfile/testScrollFeed",
"-parallel-testing-enabled", "NO", "-enableCodeCoverage", "NO",
"-collect-test-diagnostics", "never", "-resultBundlePath", str(result_path),
"test-without-building",
], cwd=root, env=environment, stdout=test_log, stderr=subprocess.STDOUT, start_new_session=True)
print(f"XCTest is opening the {feed} feed and testing the swipe controls. Leave the phone untouched.", flush=True)
print(f"Driver log: {test_log_path}", flush=True)
deadline = time.monotonic() + 120
while "OLDFELLA_PROFILE_READY" not in test_log_path.read_text():
if driver.poll() is not None:
raise RuntimeError(f"The scrolling driver stopped before it was ready. Read {test_log_path}.")
if time.monotonic() >= deadline:
raise RuntimeError(f"The feed did not become ready within 120 seconds. Read {test_log_path}.")
time.sleep(0.2)
ready = subprocess.Popen(["/usr/bin/notifyutil", "-1", notification], start_new_session=True)
recorder = subprocess.Popen([
"xcrun", "xctrace", "record", "--template", args.template,
"--instrument", "Hitches", "--instrument", "Points of Interest",
"--device", args.device, "--all-processes",
"--time-limit", f"{args.seconds + 120}s", "--output", str(trace_path),
"--notify-tracing-started", notification,
], stdout=trace_log, stderr=subprocess.STDOUT, start_new_session=True)
print(f"Waiting for Instruments. Recorder log: {trace_log_path}", flush=True)
deadline = time.monotonic() + 60
while ready.poll() is None:
if recorder.poll() is not None:
raise RuntimeError(f"The recorder stopped before it was ready. Read {trace_log_path}.")
if time.monotonic() >= deadline:
raise RuntimeError(f"The recorder did not become ready within 60 seconds. Read {trace_log_path}.")
time.sleep(0.1)
if ready.returncode != 0:
raise RuntimeError("The recording notification failed.")
subprocess.run([
"xcrun", "devicectl", "device", "notification", "post", "--device", args.device,
"--name", notification, "--timeout", "15",
], timeout=20, check=True)
print(f"Recording {direction} scrolling for about {args.seconds} seconds.", flush=True)
deadline = time.monotonic() + args.seconds + 45
while "OLDFELLA_PROFILE_FINISHED" not in test_log_path.read_text():
if driver.poll() is not None:
raise RuntimeError(f"The scrolling driver stopped before finishing. Read {test_log_path}.")
if recorder.poll() is not None:
raise RuntimeError(f"The recorder stopped during scrolling. Read {trace_log_path}.")
if time.monotonic() >= deadline:
raise RuntimeError(f"The scrolling driver timed out. Read {test_log_path}.")
time.sleep(0.2)
print("Scrolling ended. Saving Instruments data before closing the app.", flush=True)
stop(recorder, timeout=180)
if recorder.returncode != 0:
raise RuntimeError(f"The recorder failed to save the trace. Read {trace_log_path}.")
subprocess.run([
"xcrun", "devicectl", "device", "notification", "post", "--device", args.device,
"--name", notification + ".finished", "--timeout", "15",
], timeout=20, check=True)
status = driver.wait(timeout=60)
if status != 0:
raise RuntimeError(f"The scrolling driver failed. Read {test_log_path}.")
if "OLDFELLA_SCROLL_END" not in test_log_path.read_text():
raise RuntimeError("XCTest did not finish the scrolling interval. Do not use this trace as a measurement.")
print(f"Saved the trace: {trace_path}", flush=True)
print(f"Saved the driver result: {result_path}", flush=True)
print("Filter the trace to OldFella within the OldFellaScrollProfile interval. Launch and loading are outside that interval.", flush=True)
finally:
stop(driver, timeout=15)
stop(recorder)
stop(ready, timeout=5)
restored = subprocess.run([
"xcrun", "devicectl", "device", "process", "launch", "--device", args.device,
"--timeout", "30", "--terminate-existing", "industries.geesawra.oldfella",
], timeout=40, check=False)
if restored.returncode == 0:
print("Relaunched Old Fella without the keep-awake argument.", flush=True)
else:
print("The normal launch failed. Reopen Old Fella. Its keep-awake mode also ends after ten minutes.", file=sys.stderr)
subprocess.run([
sys.executable, str(root / "scripts" / "summarize-scroll.py"),
str(trace_path), "--seconds", str(args.seconds),
], check=True)
if __name__ == "__main__":
signal.signal(signal.SIGTERM, interrupted)
try:
main()
except (RuntimeError, subprocess.SubprocessError) as error:
print(str(error), file=sys.stderr)
sys.exit(1)
except KeyboardInterrupt:
sys.exit(130)