-
Notifications
You must be signed in to change notification settings - Fork 2
2453 lines (2252 loc) · 114 KB
/
Copy pathintegration-test.yml
File metadata and controls
2453 lines (2252 loc) · 114 KB
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
name: Integration Test
on:
workflow_dispatch:
inputs:
os:
description: "Platform to test"
required: true
type: choice
options:
- all
- windows-latest
- ubuntu-latest
- macos-latest
jobs:
build:
permissions:
contents: read
uses: ./.github/workflows/build.yml
with:
os_list: "${{ inputs.os == 'all' && '[''windows-latest'',''ubuntu-latest'',''macos-latest'']' || format('[{0}{1}{0}]', '''', inputs.os) }}"
cache: true
build-integration-test:
permissions:
contents: read
strategy:
fail-fast: false
matrix:
os: ${{ fromJson(inputs.os == 'all' && '[''windows-latest'',''ubuntu-latest'',''macos-latest'']' || format('[{0}{1}{0}]', '''', inputs.os)) }}
runs-on: ${{ matrix.os }}
steps:
- name: Checkout code
uses: actions/checkout@v5
with:
ref: ${{ github.ref }}
fetch-depth: 0
- name: Cache integration test build output
id: cache-build
uses: actions/cache@v5
with:
path: ./dist
key: build-it-${{ matrix.os }}-go1.25.0-${{ hashFiles('**/*.go', 'go.sum', 'go.mod') }}
- name: Setup go
if: steps.cache-build.outputs.cache-hit != 'true'
uses: actions/setup-go@v6
with:
go-version: "1.25.0"
cache: true
- name: Build integration test binary
if: steps.cache-build.outputs.cache-hit != 'true'
shell: pwsh
id: build
run: ./scripts/build_integration_test.ps1 | % { "binary_path=$_" } >> $env:GITHUB_OUTPUT
- name: Upload integration test binary
uses: actions/upload-artifact@v6
with:
name: it-${{ matrix.os }}
path: ${{ steps.build.outputs.binary_path || './dist/*' }}
set-matrix:
permissions:
contents: read
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.gen.outputs.matrix }}
steps:
- name: Build test matrix include
id: gen
shell: pwsh
env:
OS_INPUT: ${{ inputs.os }}
ORG_ID: ${{ vars.IT_ORG_ID }}
run: |
$winSuccess = @'
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$PS_Results = New-Object -TypeName psobject
# Start of typed powershell
$PS_Results | Add-Member -MemberType NoteProperty -Name \"error\" -Value \"\"
$PS_Results | Add-Member -MemberType NoteProperty -Name \"output\" -Value \"hello world`n\"
# Post results back to Rewst
$postData = $PS_Results | ConvertTo-Json
Invoke-RestMethod -Method \"Post\" -Uri $post_url -Body $postData -ContentType \"application/json\""
'@
$winFailure = @'
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$PS_Results = New-Object -TypeName psobject
# Start of typed powershell
throw \"this is a test error\"
# Post results back to Rewst
$postData = $PS_Results | ConvertTo-Json
Invoke-RestMethod -Method \"Post\" -Uri $post_url -Body $postData -ContentType \"application/json\""
'@
$orgId = $env:ORG_ID
# Output-flood scripts for the bounded-output scenario (sc-106105).
# Deliberately quote-free and backslash-free so they survive the trip
# through the trigger's JSON-quoted commands field unchanged, and
# byte-exact so the produced counts the agent reports are predictable:
# verbose 200 MiB to stdout, then a clean exit
# verbose_stderr a short stdout line, then 200 MiB to stderr
# verbose_hang 200 MiB to stdout, then a hang past the timeout
# All three write 200 MiB - three orders of magnitude past the ceiling
# the scenario configures - so the RSS ceiling asserted while they run
# is far below what buffering the output whole would cost.
$winVerbose = '"$chunk = [string]::new([char]120, 1048576); 1..200 | ForEach-Object { $chunk }"'
$winVerboseStderr = '"Write-Output keep-stdout; $chunk = [string]::new([char]101, 1048576); 1..200 | ForEach-Object { [Console]::Error.Write($chunk) }"'
$winVerboseHang = '"$chunk = [string]::new([char]120, 1048576); 1..200 | ForEach-Object { $chunk }; Start-Sleep -Seconds 60"'
$unixVerbose = '"yes x | head -c 209715200"'
$unixVerboseStderr = '"echo keep-stdout; yes e | head -c 209715200 >&2"'
$unixVerboseHang = '"yes x | head -c 209715200; sleep 60"'
$entries = @(
[ordered]@{
os = 'ubuntu-latest'
binary = 'rewst_agent_config.linux.bin'
it_binary = 'rewst_agent_config.linux.it.bin'
config_dir = '/etc/rewst_remote_agent'
log_file = "/etc/rewst_remote_agent/$orgId/rewst_agent.log"
service = "rewst_remote_agent_$orgId"
success_commands = '"echo \"hello world\""'
failure_commands = '"exit 1"'
timeout_commands = '"sleep 30"'
sweep_commands = '"sleep 180"'
verbose_commands = $unixVerbose
verbose_stderr_commands = $unixVerboseStderr
verbose_hang_commands = $unixVerboseHang
success_patterns = "Command completed`nSending postback`nPostback sent"
no_auto_updates_extra = ''
uninstall_paths = "/etc/rewst_remote_agent/$orgId`n/usr/local/bin/rewst_remote_agent/$orgId`n/tmp/rewst_remote_agent/scripts/$orgId"
service_user = 'rewst-it-svc'
service_username_arg = 'rewst-it-svc'
service_identity = 'rewst-it-svc'
},
[ordered]@{
os = 'windows-latest'
binary = 'rewst_agent_config.win.exe'
it_binary = 'rewst_agent_config.win.it.exe'
config_dir = 'C:\ProgramData\RewstRemoteAgent'
log_file = "C:\ProgramData\RewstRemoteAgent\$orgId\rewst_agent.log"
service = "RewstRemoteAgent_$orgId"
success_commands = $winSuccess
failure_commands = $winFailure
timeout_commands = '"Start-Sleep -Seconds 30"'
sweep_commands = '"Start-Sleep -Seconds 180"'
verbose_commands = $winVerbose
verbose_stderr_commands = $winVerboseStderr
verbose_hang_commands = $winVerboseHang
success_patterns = "Command completed`nSending postback`nPostback already sent"
no_auto_updates_extra = '--disable-agent-postback'
uninstall_paths = "C:\ProgramData\RewstRemoteAgent\$orgId`nC:\Program Files\RewstRemoteAgent\$orgId`nC:\RewstRemoteAgent\scripts\$orgId"
service_user = 'rewst-it-svc'
service_username_arg = '.\rewst-it-svc'
service_identity = '.\rewst-it-svc'
},
[ordered]@{
os = 'macos-latest'
binary = 'rewst_agent_config.mac-os.bin'
it_binary = 'rewst_agent_config.mac-os.it.bin'
config_dir = '/Library/Application Support/rewst_remote_agent'
log_file = "/Library/Application Support/rewst_remote_agent/$orgId/rewst_agent.log"
service = "io.rewst.remote_agent_$orgId"
success_commands = '"echo \"hello world\""'
failure_commands = '"exit 1"'
timeout_commands = '"sleep 30"'
sweep_commands = '"sleep 180"'
verbose_commands = $unixVerbose
verbose_stderr_commands = $unixVerboseStderr
verbose_hang_commands = $unixVerboseHang
success_patterns = "Command completed`nSending postback`nPostback sent"
no_auto_updates_extra = ''
uninstall_paths = "/Library/Application Support/rewst_remote_agent/$orgId`n/usr/local/bin/rewst_remote_agent/$orgId`n`$env:TMPDIR/rewst_remote_agent/scripts/$orgId"
service_user = 'rewst-it-svc'
service_username_arg = 'rewst-it-svc'
service_identity = 'rewst-it-svc'
}
)
if ($env:OS_INPUT -ne 'all') {
$entries = @($entries | Where-Object { $_.os -eq $env:OS_INPUT })
}
$payload = @{ include = $entries }
$json = ConvertTo-Json -InputObject $payload -Depth 10 -Compress
Write-Output $json
"matrix=$json" >> $env:GITHUB_OUTPUT
test:
permissions:
contents: read
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
needs: [build, build-integration-test, set-matrix]
strategy:
fail-fast: false
matrix: ${{ fromJson(needs.set-matrix.outputs.matrix) }}
runs-on: ${{ matrix.os }}
steps:
- name: Checkout code
uses: actions/checkout@v5
- name: Inject PowerShell profile noise
if: matrix.os == 'windows-latest'
id: inject_profile_noise
uses: ./.github/actions/inject-profile-noise
- name: Install agent
id: install_agent
uses: ./.github/actions/install-agent
with:
os: ${{ matrix.os }}
binary: ${{ matrix.binary }}
it_binary: ${{ matrix.it_binary }}
config_url: ${{ vars.IT_CONFIG_URL }}
config_secret: ${{ secrets.IT_CONFIG_SECRET }}
org_id: ${{ vars.IT_ORG_ID }}
github_token: ${{ secrets.GITHUB_TOKEN }}
- name: Check install output for profile noise
if: matrix.os == 'windows-latest'
uses: ./.github/actions/check-profile-noise
with:
install_output_path: ${{ steps.install_agent.outputs.install_output_path }}
noise: ${{ steps.inject_profile_noise.outputs.noise }}
- name: Check service
uses: ./.github/actions/check-service
with:
service: ${{ matrix.service }}
- name: Validate config and get device id
id: config
uses: ./.github/actions/validate-config
with:
config_dir: ${{ matrix.config_dir }}
org_id: ${{ vars.IT_ORG_ID }}
- name: Check subscribed messages log for topic and QoS
uses: ./.github/actions/assert-log-contains
with:
log_file: ${{ matrix.log_file }}
patterns: Subscribed to messages
subscribed_topic_qos: "true"
wait_seconds: "10"
- name: Send success command
uses: ./.github/actions/send-command
with:
trigger_url: ${{ vars.IT_SEND_COMMAND_TRIGGER_URL }}
device_id: ${{ steps.config.outputs.device_id }}
commands: ${{ matrix.success_commands }}
- name: Check logs for successful command
uses: ./.github/actions/assert-log-contains
with:
log_file: ${{ matrix.log_file }}
patterns: ${{ matrix.success_patterns }}
- name: Send failing command
uses: ./.github/actions/send-command
with:
trigger_url: ${{ vars.IT_SEND_COMMAND_TRIGGER_URL }}
device_id: ${{ steps.config.outputs.device_id }}
commands: ${{ matrix.failure_commands }}
- name: Check logs for error handling
uses: ./.github/actions/assert-log-contains
with:
log_file: ${{ matrix.log_file }}
patterns: Command failed
wait_seconds: "15"
- name: Install integration test binary (old version)
uses: ./.github/actions/run-agent
with:
binary: ${{ matrix.it_binary }}
args: --update --org-id ${{ vars.IT_ORG_ID }} --github-token ${{ secrets.GITHUB_TOKEN }}
- name: Wait for auto updater to trigger and update
uses: ./.github/actions/wait-for-log-line
with:
log_file: ${{ matrix.log_file }}
pattern: Updating agent
- name: Verify auto update completed
uses: ./.github/actions/verify-auto-update
with:
log_file: ${{ matrix.log_file }}
- name: Update logging level to debug
uses: ./.github/actions/run-agent
with:
binary: ${{ matrix.binary }}
args: --update --org-id ${{ vars.IT_ORG_ID }} --logging-level debug --github-token ${{ secrets.GITHUB_TOKEN }}
- name: Send test command (debug)
uses: ./.github/actions/send-command
with:
trigger_url: ${{ vars.IT_SEND_COMMAND_TRIGGER_URL }}
device_id: ${{ steps.config.outputs.device_id }}
commands: ${{ matrix.success_commands }}
- name: Check logs for debug level
uses: ./.github/actions/assert-log-contains
with:
log_file: ${{ matrix.log_file }}
patterns: DEBUG
- name: Stop service
uses: ./.github/actions/stop-service
with:
service: ${{ matrix.service }}
- name: Delete log file
uses: ./.github/actions/delete-log
with:
log_file: ${{ matrix.log_file }}
- name: Update agent (no auto updates)
uses: ./.github/actions/run-agent
with:
binary: ${{ matrix.binary }}
args: --update --org-id ${{ vars.IT_ORG_ID }} --no-auto-updates ${{ matrix.no_auto_updates_extra }} --github-token ${{ secrets.GITHUB_TOKEN }}
- name: Check logs for no auto updater
uses: ./.github/actions/assert-log-missing
with:
log_file: ${{ matrix.log_file }}
pattern: Starting auto updater
wait_for_file_seconds: "30"
- name: Send test command (windows postback verification)
if: matrix.os == 'windows-latest'
uses: ./.github/actions/send-command
with:
trigger_url: ${{ vars.IT_SEND_COMMAND_TRIGGER_URL }}
device_id: ${{ steps.config.outputs.device_id }}
commands: ${{ matrix.success_commands }}
- name: Check logs for command received (windows)
if: matrix.os == 'windows-latest'
uses: ./.github/actions/assert-log-contains
with:
log_file: ${{ matrix.log_file }}
patterns: Command completed
- name: Check logs absent postback (windows)
if: matrix.os == 'windows-latest'
uses: ./.github/actions/assert-log-missing
with:
log_file: ${{ matrix.log_file }}
pattern: Postback already sent
- name: Update agent with syslog
uses: ./.github/actions/run-agent
with:
binary: ${{ matrix.binary }}
args: --update --org-id ${{ vars.IT_ORG_ID }} --syslog --github-token ${{ secrets.GITHUB_TOKEN }}
- name: Send test command (syslog)
uses: ./.github/actions/send-command
with:
trigger_url: ${{ vars.IT_SEND_COMMAND_TRIGGER_URL }}
device_id: ${{ steps.config.outputs.device_id }}
commands: ${{ matrix.success_commands }}
- name: Check syslog for command completed
uses: ./.github/actions/assert-syslog-contains
with:
service: ${{ matrix.service }}
pattern: Command completed
# ---- MQTT reconnection scenario ----
# Force a transient broker outage and verify the agent tears down, backs
# off, resubscribes, and resumes command delivery exactly once. Counts are
# captured up front and compared as deltas because the log already contains
# "Subscribed to messages"/"Command completed" lines from earlier cycles
# (the service has restarted several times by now and the log is not reset
# while the service holds it open).
- name: Capture reconnect baseline counts
id: reconnect_baseline
shell: pwsh
env:
LOG_FILE: ${{ matrix.log_file }}
run: |
$content = Get-Content $env:LOG_FILE -Raw
$subscribed = ([regex]::Matches($content, [regex]::Escape("Subscribed to messages"))).Count
$completed = ([regex]::Matches($content, [regex]::Escape("Command completed"))).Count
"subscribed=$subscribed" >> $env:GITHUB_OUTPUT
"completed=$completed" >> $env:GITHUB_OUTPUT
Write-Output "Baseline counts -> subscribed=$subscribed completed=$completed"
- name: Disrupt broker connection
uses: ./.github/actions/disrupt-connection
with:
mode: block
host: ${{ steps.config.outputs.azure_iot_hub_host }}
- name: Wait for connection lost detection
uses: ./.github/actions/wait-for-log-line
with:
log_file: ${{ matrix.log_file }}
pattern: Connection lost
max_attempts: "60"
interval_seconds: "2"
- name: Assert connection lost and reconnect/backoff activity
uses: ./.github/actions/assert-log-contains
with:
log_file: ${{ matrix.log_file }}
patterns: |
Connection lost
Reconnecting in
Reconnecting...
wait_seconds: "10"
- name: Restore broker connection
if: always()
uses: ./.github/actions/disrupt-connection
with:
mode: restore
host: ${{ steps.config.outputs.azure_iot_hub_host }}
- name: Wait for fresh subscription after reconnect
shell: pwsh
env:
LOG_FILE: ${{ matrix.log_file }}
BASELINE: ${{ steps.reconnect_baseline.outputs.subscribed }}
run: |
$baseline = [int]$env:BASELINE
for ($i = 1; $i -le 60; $i++) {
$content = Get-Content $env:LOG_FILE -Raw -ErrorAction SilentlyContinue
$count = if ($content) { ([regex]::Matches($content, [regex]::Escape("Subscribed to messages"))).Count } else { 0 }
if ($count -gt $baseline) {
Write-Output "Agent resubscribed after reconnect (count $count > baseline $baseline) after ~$($i * 2)s"
exit 0
}
Start-Sleep -Seconds 2
}
Write-Error "Agent did not resubscribe after reconnect (subscribed count stayed at $baseline)"
exit 1
- name: Send command after reconnect
uses: ./.github/actions/send-command
with:
trigger_url: ${{ vars.IT_SEND_COMMAND_TRIGGER_URL }}
device_id: ${{ steps.config.outputs.device_id }}
commands: ${{ matrix.success_commands }}
- name: Assert command executed exactly once after reconnect
shell: pwsh
env:
LOG_FILE: ${{ matrix.log_file }}
BASELINE: ${{ steps.reconnect_baseline.outputs.completed }}
run: |
$baseline = [int]$env:BASELINE
$observed = $baseline
# Wait for the post-reconnect command to complete.
for ($i = 1; $i -le 30; $i++) {
Start-Sleep -Seconds 2
$content = Get-Content $env:LOG_FILE -Raw -ErrorAction SilentlyContinue
$observed = if ($content) { ([regex]::Matches($content, [regex]::Escape("Command completed"))).Count } else { 0 }
if ($observed -gt $baseline) { break }
}
if (($observed - $baseline) -lt 1) {
Write-Error "Post-reconnect command never completed (count stayed at $baseline)"
exit 1
}
# Allow a brief window for any duplicate delivery to surface, then
# require the delta to be exactly one - guarding against re-delivery of
# the buffered message on a non-clean reconnected session.
Start-Sleep -Seconds 10
$content = Get-Content $env:LOG_FILE -Raw
$final = ([regex]::Matches($content, [regex]::Escape("Command completed"))).Count
$delta = $final - $baseline
Write-Output "Post-reconnect 'Command completed' delta: $delta (baseline $baseline, final $final)"
if ($delta -ne 1) {
Write-Error "Expected exactly one post-reconnect 'Command completed', got $delta (duplicate delivery?)"
exit 1
}
Write-Output "Confirmed exactly one post-reconnect command execution"
# ---- Withheld-SUBACK scenario (sc-106107) ----
# The reconnection scenario above severs the connection, which keepalive
# detects and the agent handles as an ordinary reconnect. This one covers
# the harder case it cannot reach: a broker that stays alive - completing
# the TLS handshake, answering CONNECT with CONNACK, and answering every
# PINGREQ - while never sending SUBACK. That is what Azure IoT Hub does when
# it throttles a device, and what a middlebox that half-opens a connection
# produces. Before the fix it left the agent connected but never subscribed,
# silently running no commands and unable to honor a stop; now the subscribe
# wait is bounded and stop-interruptible, so the agent fails cleanly, backs
# off, and recovers on a later cycle once the broker starts acknowledging.
# Counts are compared as deltas because the log already carries lines from
# earlier cycles.
- name: Capture SUBACK-withheld baseline counts
id: suback_baseline
shell: pwsh
env:
LOG_FILE: ${{ matrix.log_file }}
run: |
$content = Get-Content $env:LOG_FILE -Raw -ErrorAction SilentlyContinue
function Get-PatternCount($text, $needle) {
if ($text) { ([regex]::Matches($text, [regex]::Escape($needle))).Count } else { 0 }
}
$subscribed = Get-PatternCount $content "Subscribed to messages"
$timedOut = Get-PatternCount $content "Failed to subscribe: timed out waiting for broker acknowledgement"
$backoffs = Get-PatternCount $content "Reconnecting in"
"subscribed=$subscribed" >> $env:GITHUB_OUTPUT
"timed_out=$timedOut" >> $env:GITHUB_OUTPUT
"backoffs=$backoffs" >> $env:GITHUB_OUTPUT
Write-Output "Baseline -> subscribed=$subscribed timed_out=$timedOut backoffs=$backoffs"
# Read off a logged path rather than re-deriving the platform path; see the
# fuller note on the bounded-output scenario's copy of this step.
- name: Resolve the scripts directory (SUBACK scenario)
id: suback_scripts_dir
shell: pwsh
env:
LOG_FILE: ${{ matrix.log_file }}
run: |
$content = Get-Content $env:LOG_FILE -Raw -ErrorAction SilentlyContinue
$found = if ($content) { [regex]::Matches($content, 'Command saved to[^\r\n]*path=(?<p>\S+)') } else { @() }
if ($found.Count -eq 0) {
Write-Error "No 'Command saved to' line in the log; cannot resolve the scripts directory"
exit 1
}
$dir = Split-Path -Parent $found[$found.Count - 1].Groups['p'].Value.Trim('"')
"path=$dir" >> $env:GITHUB_OUTPUT
Write-Output "Scripts directory: $dir"
- name: Snapshot temp script files before the withheld-SUBACK scenario
uses: ./.github/actions/assert-no-orphaned-scripts
with:
mode: snapshot
scripts_dir: ${{ steps.suback_scripts_dir.outputs.path }}
- name: Start stub broker withholding SUBACK
id: stub_broker
uses: ./.github/actions/stub-broker
with:
mode: start
- name: Point agent at the stub broker
id: stub_host
uses: ./.github/actions/set-broker-host
with:
config_dir: ${{ matrix.config_dir }}
org_id: ${{ vars.IT_ORG_ID }}
host: ${{ steps.stub_broker.outputs.host }}
# --update restarts the service, so the rewritten broker host takes effect.
# The short subscribe timeout keeps each wedged cycle to ~10s so several
# backoff slots are observable inside the job.
- name: Restart agent against the stub broker
uses: ./.github/actions/run-agent
with:
binary: ${{ matrix.binary }}
args: --update --org-id ${{ vars.IT_ORG_ID }} --mqtt-subscribe-timeout-seconds 10 --github-token ${{ secrets.GITHUB_TOKEN }}
- name: Assert bounded subscribe failure and growing backoff
id: assert_suback_withheld
shell: pwsh
env:
LOG_FILE: ${{ matrix.log_file }}
BASE_TIMED_OUT: ${{ steps.suback_baseline.outputs.timed_out }}
BASE_BACKOFFS: ${{ steps.suback_baseline.outputs.backoffs }}
BASE_SUBSCRIBED: ${{ steps.suback_baseline.outputs.subscribed }}
run: |
$baseTimedOut = [int]$env:BASE_TIMED_OUT
$baseBackoffs = [int]$env:BASE_BACKOFFS
$baseSubscribed = [int]$env:BASE_SUBSCRIBED
$needle = "Failed to subscribe: timed out waiting for broker acknowledgement"
# Two wedged cycles plus their backoff waits take roughly 10+2+10+4s.
$content = ""
for ($i = 1; $i -le 60; $i++) {
$content = Get-Content $env:LOG_FILE -Raw -ErrorAction SilentlyContinue
$timedOut = if ($content) { ([regex]::Matches($content, [regex]::Escape($needle))).Count } else { 0 }
$backoffs = if ($content) { ([regex]::Matches($content, [regex]::Escape("Reconnecting in"))).Count } else { 0 }
if (($timedOut - $baseTimedOut) -ge 2 -and ($backoffs - $baseBackoffs) -ge 2) { break }
Start-Sleep -Seconds 2
}
$timedOut = if ($content) { ([regex]::Matches($content, [regex]::Escape($needle))).Count } else { 0 }
if (($timedOut - $baseTimedOut) -lt 2) {
Write-Error "Expected at least two bounded subscribe timeouts, got $($timedOut - $baseTimedOut)"
exit 1
}
Write-Output "Bounded subscribe timeouts observed: $($timedOut - $baseTimedOut)"
# The agent must not have subscribed: a withheld SUBACK means no
# subscription, and a "Subscribed to messages" line here would mean the
# stub broker is not the broker the agent reached.
$subscribed = ([regex]::Matches($content, [regex]::Escape("Subscribed to messages"))).Count
if ($subscribed -ne $baseSubscribed) {
Write-Error "Agent reported a subscription against a broker that withholds SUBACK"
exit 1
}
# The backoff must not be cleared by a timed-out subscribe: a throttling
# broker needs progressively longer waits, not a tight reconnect loop.
# Go renders a duration as concatenated unit components ("4.1s",
# "1m4s"), so each component is summed rather than parsed as one number.
function ConvertTo-Seconds([string]$value) {
$total = 0.0
foreach ($m in [regex]::Matches($value, '(?<n>[0-9.]+)(?<u>ms|us|ns|h|m|s)')) {
$n = [double]$m.Groups['n'].Value
switch ($m.Groups['u'].Value) {
'ns' { $total += $n / 1e9 }
'us' { $total += $n / 1e6 }
'ms' { $total += $n / 1e3 }
's' { $total += $n }
'm' { $total += $n * 60 }
'h' { $total += $n * 3600 }
}
}
return $total
}
$waits = [regex]::Matches($content, 'Reconnecting in: timeout=(?<t>[0-9.a-z]+)') |
ForEach-Object { ConvertTo-Seconds $_.Groups['t'].Value }
$new = @($waits | Select-Object -Skip $baseBackoffs)
if ($new.Count -lt 2) {
Write-Error "Expected at least two reconnect waits after the subscribe timeouts, got $($new.Count)"
exit 1
}
Write-Output "Reconnect waits after the subscribe timeouts: $($new -join ', ')"
if ($new[1] -le $new[0]) {
Write-Error "Reconnect backoff did not grow ($($new[0]) then $($new[1])); a timed-out subscribe must not clear it"
exit 1
}
Write-Output "Confirmed the reconnect backoff grows after a withheld SUBACK"
# What the agent actually did against the stub is only visible in its own
# log, and the assertion above deliberately reads counts rather than lines.
# Dumping the tail on failure makes a fixture problem (never reached the
# broker at all) distinguishable from a real regression (reached it and
# blocked) without re-running the job.
- name: Dump agent log on withheld-SUBACK failure
if: failure() && steps.assert_suback_withheld.outcome == 'failure'
shell: pwsh
env:
LOG_FILE: ${{ matrix.log_file }}
run: |
Write-Output "---- last 100 lines of $($env:LOG_FILE) ----"
Get-Content $env:LOG_FILE -Tail 100 -ErrorAction SilentlyContinue
# The original defect made this impossible: with the cycle parked in
# token.Wait() the stop signal was never reached, the platform waited out
# its stop deadline (30s on the Windows SCM) and force-killed the process.
- name: Assert the service stops promptly while wedged on the stub broker
shell: pwsh
env:
LOG_FILE: ${{ matrix.log_file }}
SERVICE: ${{ matrix.service }}
run: |
function Get-StopCount {
$content = Get-Content $env:LOG_FILE -Raw -ErrorAction SilentlyContinue
if ($content) { ([regex]::Matches($content, [regex]::Escape("Service stopped"))).Count } else { 0 }
}
# Counted here rather than reusing the scenario-wide baseline: the
# --update that pointed the agent at the stub broker restarts the
# service, and that restart logs its own "Service stopped". Measured
# against the older baseline the delta was already satisfied before this
# stop was even issued, so the assertion "passed" in 0.2s without
# observing the stop it exists to test.
$before = Get-StopCount
Write-Output "Service stopped lines before issuing the stop: $before"
$sw = [System.Diagnostics.Stopwatch]::StartNew()
if ($IsWindows) {
sc.exe stop $env:SERVICE | Out-Null
} elseif ($IsLinux) {
sudo systemctl stop $env:SERVICE
} else {
# Bare label, not a "system/<label>" service target. launchctl's
# `stop` is a legacy subcommand that resolves a label in the current
# domain, so the target form is taken as a literal label, matches
# nothing, and exits 3 (ESRCH) without ever signalling the agent.
# This mirrors what the agent's own darwinService.Stop does. `stop`
# leaves the job loaded, so the later start-service can run it again.
sudo launchctl stop $env:SERVICE
}
# launchctl exits non-zero in situations that are not failures here -
# the repo's own stop-service action already guards it with `|| true` -
# and the pwsh shell ends by exiting with $LASTEXITCODE, which failed
# this step on macOS even after the assertion below had passed. Report
# the code and clear it; whether the stop was honored is decided by the
# agent's log, not by the service manager's exit status.
Write-Output "Stop command exit code: $LASTEXITCODE"
$global:LASTEXITCODE = 0
# A clean exit runs the agent's deferred teardown, whose last act is the
# "Service stopped" line; a force-kill past the stop deadline never
# produces one.
$stopped = $false
while ($sw.Elapsed.TotalSeconds -lt 30) {
if ((Get-StopCount) -gt $before) { $stopped = $true; break }
Start-Sleep -Milliseconds 500
}
$sw.Stop()
if (-not $stopped) {
# Both halves matter when this fails: the agent log says whether the
# stop was received and ignored, and the service manager says whether
# it was ever delivered.
Write-Output "---- last 60 lines of the agent log ----"
Get-Content $env:LOG_FILE -Tail 60 -ErrorAction SilentlyContinue
Write-Output "---- service manager state ----"
if ($IsWindows) {
sc.exe query $env:SERVICE
} elseif ($IsLinux) {
sudo systemctl status $env:SERVICE --no-pager
} else {
# print, unlike stop, is a modern subcommand and does take the
# system/<label> service target.
sudo launchctl print "system/$($env:SERVICE)"
}
$global:LASTEXITCODE = 0
Write-Error "Service did not log a clean stop within 30s while wedged on a withholding broker"
exit 1
}
Write-Output "Service stopped cleanly after $([math]::Round($sw.Elapsed.TotalSeconds, 1))s while wedged"
exit 0
- name: Assert no orphaned scripts after the wedged stop
uses: ./.github/actions/assert-no-orphaned-scripts
with:
mode: assert
scripts_dir: ${{ steps.suback_scripts_dir.outputs.path }}
- name: Restart the service against the still-withholding broker
uses: ./.github/actions/start-service
with:
service: ${{ matrix.service }}
- name: Wait for the agent to wedge on the stub broker again
uses: ./.github/actions/wait-for-log-line
with:
log_file: ${{ matrix.log_file }}
pattern: "Failed to subscribe: timed out waiting for broker acknowledgement"
max_attempts: "60"
interval_seconds: "2"
# Flipped on the live connection - the stub re-reads its mode per packet -
# so recovery is the agent's own next reconnect cycle, not a restart.
- name: Switch stub broker to acknowledge SUBACK
uses: ./.github/actions/stub-broker
with:
mode: ack
- name: Assert the agent recovers on a later cycle
shell: pwsh
env:
LOG_FILE: ${{ matrix.log_file }}
BASELINE: ${{ steps.suback_baseline.outputs.subscribed }}
run: |
$baseline = [int]$env:BASELINE
for ($i = 1; $i -le 60; $i++) {
$content = Get-Content $env:LOG_FILE -Raw -ErrorAction SilentlyContinue
$count = if ($content) { ([regex]::Matches($content, [regex]::Escape("Subscribed to messages"))).Count } else { 0 }
if ($count -gt $baseline) {
Write-Output "Agent subscribed on a later cycle once SUBACK arrived (count $count > baseline $baseline) after ~$($i * 2)s"
exit 0
}
Start-Sleep -Seconds 2
}
Write-Error "Agent never subscribed after the stub broker started acknowledging"
exit 1
- name: Restore the real broker host
if: always() && steps.stub_host.outputs.previous_host != ''
uses: ./.github/actions/set-broker-host
with:
config_dir: ${{ matrix.config_dir }}
org_id: ${{ vars.IT_ORG_ID }}
host: ${{ steps.stub_host.outputs.previous_host }}
- name: Stop stub broker
if: always()
uses: ./.github/actions/stub-broker
with:
mode: stop
- name: Restart agent against the real broker
if: always() && steps.stub_host.outputs.previous_host != ''
uses: ./.github/actions/run-agent
with:
binary: ${{ matrix.binary }}
args: --update --org-id ${{ vars.IT_ORG_ID }} --mqtt-subscribe-timeout-seconds 30 --github-token ${{ secrets.GITHUB_TOKEN }}
- name: Wait for resubscription to the real broker
if: always() && steps.stub_host.outputs.previous_host != ''
uses: ./.github/actions/wait-for-log-line
with:
log_file: ${{ matrix.log_file }}
pattern: Subscribed to messages
max_attempts: "60"
interval_seconds: "2"
# ---- Per-command execution timeout scenario (sc-103835) ----
# Configure a short per-command timeout, dispatch a script that sleeps well
# beyond it, and confirm the agent kills the command (logging a timeout) and
# that a subsequent ordinary command still completes - i.e. the worker pool
# recovered instead of staying wedged. Counts are compared as deltas because
# the log already carries lines from earlier cycles.
- name: Enable short command timeout
uses: ./.github/actions/run-agent
with:
binary: ${{ matrix.binary }}
args: --update --org-id ${{ vars.IT_ORG_ID }} --command-timeout-seconds 5 --github-token ${{ secrets.GITHUB_TOKEN }}
- name: Wait for fresh subscription after timeout update
uses: ./.github/actions/wait-for-log-line
with:
log_file: ${{ matrix.log_file }}
pattern: Subscribed to messages
max_attempts: "60"
interval_seconds: "2"
- name: Capture command-timeout baseline counts
id: timeout_baseline
shell: pwsh
env:
LOG_FILE: ${{ matrix.log_file }}
run: |
$content = Get-Content $env:LOG_FILE -Raw -ErrorAction SilentlyContinue
$timedOut = if ($content) { ([regex]::Matches($content, [regex]::Escape("Command timed out"))).Count } else { 0 }
$completed = if ($content) { ([regex]::Matches($content, [regex]::Escape("Command completed"))).Count } else { 0 }
"timed_out=$timedOut" >> $env:GITHUB_OUTPUT
"completed=$completed" >> $env:GITHUB_OUTPUT
Write-Output "Baseline counts -> timed_out=$timedOut completed=$completed"
- name: Send hanging command
uses: ./.github/actions/send-command
with:
trigger_url: ${{ vars.IT_SEND_COMMAND_TRIGGER_URL }}
device_id: ${{ steps.config.outputs.device_id }}
commands: ${{ matrix.timeout_commands }}
- name: Assert hanging command was killed by the timeout
shell: pwsh
env:
LOG_FILE: ${{ matrix.log_file }}
BASELINE: ${{ steps.timeout_baseline.outputs.timed_out }}
run: |
$baseline = [int]$env:BASELINE
for ($i = 1; $i -le 30; $i++) {
Start-Sleep -Seconds 2
$content = Get-Content $env:LOG_FILE -Raw -ErrorAction SilentlyContinue
$count = if ($content) { ([regex]::Matches($content, [regex]::Escape("Command timed out"))).Count } else { 0 }
if ($count -gt $baseline) {
Write-Output "Command timed out as expected (count $count > baseline $baseline) after ~$($i * 2)s"
exit 0
}
}
Write-Error "Hanging command was not killed by the per-command timeout (count stayed at $baseline)"
exit 1
- name: Send command after timeout
uses: ./.github/actions/send-command
with:
trigger_url: ${{ vars.IT_SEND_COMMAND_TRIGGER_URL }}
device_id: ${{ steps.config.outputs.device_id }}
commands: ${{ matrix.success_commands }}
- name: Assert worker pool recovered after timeout
shell: pwsh
env:
LOG_FILE: ${{ matrix.log_file }}
BASELINE: ${{ steps.timeout_baseline.outputs.completed }}
run: |
$baseline = [int]$env:BASELINE
for ($i = 1; $i -le 30; $i++) {
Start-Sleep -Seconds 2
$content = Get-Content $env:LOG_FILE -Raw -ErrorAction SilentlyContinue
$count = if ($content) { ([regex]::Matches($content, [regex]::Escape("Command completed"))).Count } else { 0 }
if ($count -gt $baseline) {
Write-Output "Worker pool recovered; a later command completed (count $count > baseline $baseline)"
exit 0
}
}
Write-Error "Worker pool did not process a command after the timeout (count stayed at $baseline)"
exit 1
# ---- SAS token proactive renewal scenario (sc-103969) ----
# The integration test binary is built with a short SAS token lifetime
# (sasTokenLifetimeOverrideStr=90s), so the agent must proactively
# reconnect with a freshly minted token a safety margin BEFORE the token
# expires rather than being forcibly disconnected by the broker on expiry.
# Install the IT binary with auto-updates disabled so it stays the running
# service (otherwise the 30s auto-updater would swap it for the real
# release before renewal fires), then confirm: the renewal fires (distinct
# Info log), the agent re-subscribes with the fresh token, and it is
# graceful - no Error "Connection lost" is produced. Deltas are compared
# because earlier cycles already left "Subscribed to messages"/"Connection
# lost" lines in the log.
- name: Install IT binary with short SAS token lifetime
uses: ./.github/actions/run-agent
with:
binary: ${{ matrix.it_binary }}
args: --update --org-id ${{ vars.IT_ORG_ID }} --no-auto-updates ${{ matrix.no_auto_updates_extra }} --github-token ${{ secrets.GITHUB_TOKEN }}
- name: Wait for fresh subscription after SAS lifetime update
uses: ./.github/actions/wait-for-log-line
with:
log_file: ${{ matrix.log_file }}
pattern: Subscribed to messages
max_attempts: "60"
interval_seconds: "2"
- name: Capture SAS renewal baseline counts
id: sas_renewal_baseline
shell: pwsh
env:
LOG_FILE: ${{ matrix.log_file }}
run: |
$content = Get-Content $env:LOG_FILE -Raw -ErrorAction SilentlyContinue
$renewed = if ($content) { ([regex]::Matches($content, [regex]::Escape("Renewing SAS token before expiry"))).Count } else { 0 }
$subscribed = if ($content) { ([regex]::Matches($content, [regex]::Escape("Subscribed to messages"))).Count } else { 0 }
$lost = if ($content) { ([regex]::Matches($content, [regex]::Escape("Connection lost"))).Count } else { 0 }
$completed = if ($content) { ([regex]::Matches($content, [regex]::Escape("Command completed"))).Count } else { 0 }
"renewed=$renewed" >> $env:GITHUB_OUTPUT
"subscribed=$subscribed" >> $env:GITHUB_OUTPUT
"lost=$lost" >> $env:GITHUB_OUTPUT
"completed=$completed" >> $env:GITHUB_OUTPUT
Write-Output "Baseline counts -> renewed=$renewed subscribed=$subscribed lost=$lost completed=$completed"
- name: Wait for proactive SAS token renewal
uses: ./.github/actions/wait-for-log-line
with:
log_file: ${{ matrix.log_file }}
pattern: Renewing SAS token before expiry
max_attempts: "60"
interval_seconds: "2"
- name: Assert SAS token renewed and agent resubscribed with fresh token
shell: pwsh
env:
LOG_FILE: ${{ matrix.log_file }}
RENEWED_BASELINE: ${{ steps.sas_renewal_baseline.outputs.renewed }}
SUBSCRIBED_BASELINE: ${{ steps.sas_renewal_baseline.outputs.subscribed }}
run: |
$renewedBaseline = [int]$env:RENEWED_BASELINE
$subscribedBaseline = [int]$env:SUBSCRIBED_BASELINE
for ($i = 1; $i -le 60; $i++) {
$content = Get-Content $env:LOG_FILE -Raw -ErrorAction SilentlyContinue
$renewed = if ($content) { ([regex]::Matches($content, [regex]::Escape("Renewing SAS token before expiry"))).Count } else { 0 }
$subscribed = if ($content) { ([regex]::Matches($content, [regex]::Escape("Subscribed to messages"))).Count } else { 0 }
if (($renewed -gt $renewedBaseline) -and ($subscribed -gt $subscribedBaseline)) {
Write-Output "SAS token renewed (count $renewed > baseline $renewedBaseline) and agent resubscribed (count $subscribed > baseline $subscribedBaseline) after ~$($i * 2)s"
exit 0
}
Start-Sleep -Seconds 2
}
Write-Error "Proactive SAS renewal did not fire and resubscribe (renewed stayed <= $renewedBaseline or subscribed stayed <= $subscribedBaseline)"
exit 1
- name: Assert SAS renewal was graceful (no forced disconnect)
shell: pwsh
env:
LOG_FILE: ${{ matrix.log_file }}
LOST_BASELINE: ${{ steps.sas_renewal_baseline.outputs.lost }}
run: |
$baseline = [int]$env:LOST_BASELINE
$content = Get-Content $env:LOG_FILE -Raw
$lost = ([regex]::Matches($content, [regex]::Escape("Connection lost"))).Count
if ($lost -gt $baseline) {
Write-Error "SAS renewal was not graceful: 'Connection lost' count rose from $baseline to $lost (token expired before renewal fired?)"
exit 1
}
Write-Output "Confirmed graceful renewal: no new 'Connection lost' (count stayed at $baseline)"
- name: Send command after SAS renewal
uses: ./.github/actions/send-command
with:
trigger_url: ${{ vars.IT_SEND_COMMAND_TRIGGER_URL }}
device_id: ${{ steps.config.outputs.device_id }}
commands: ${{ matrix.success_commands }}
- name: Assert command delivery continues after SAS renewal
shell: pwsh