-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPoolManager.cs
More file actions
1584 lines (1354 loc) · 66.1 KB
/
PoolManager.cs
File metadata and controls
1584 lines (1354 loc) · 66.1 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
using System.Diagnostics;
using System.Reflection.Metadata.Ecma335;
using GithubActionsOrchestrator.CloudControllers;
using GithubActionsOrchestrator.Database;
using GithubActionsOrchestrator.GitHub;
using GithubActionsOrchestrator.Models;
using HetznerCloudApi.Object.Server;
using Microsoft.EntityFrameworkCore;
using Prometheus;
namespace GithubActionsOrchestrator;
public class PoolManager : BackgroundService
{
private readonly List<ICloudController> _cc;
private readonly ILogger<PoolManager> _logger;
private static readonly Counter MachineCreatedCount = Metrics
.CreateCounter("github_autoscaler_machines_created", "Number of created machines", labelNames: ["org","size"]);
private static readonly Gauge CreateQueueSize = Metrics
.CreateGauge("github_autoscaler_create_queue", "Number of queued runner create tasks");
private static readonly Gauge GithubRunnersGauge = Metrics
.CreateGauge("github_registered_runners", "Number of runners registered to github actions", labelNames: ["org", "status"]);
private static readonly Gauge DeleteQueueSize = Metrics
.CreateGauge("github_autoscaler_delete_queue", "Number of queued runner delete tasks");
private static readonly Gauge ProvisionQueueSize = Metrics
.CreateGauge("github_autoscaler_runners_provisioning", "Number of runners currently provisioning");
private static readonly Gauge CspRunnerCount = Metrics
.CreateGauge("github_autoscaler_csp_runners", "Number of runners currently on the CSP", labelNames: ["csp"]);
private static readonly Gauge StuckJobsCount = Metrics
.CreateGauge("github_autoscaler_job_stuck", "Number of jobs not picked up after 15min");
private static readonly Gauge ThrottledJobsCount = Metrics
.CreateGauge("github_autoscaler_job_throttled", "Number of jobs waiting due to runner quota limit");
private static readonly Gauge QueuedJobsCount = Metrics
.CreateGauge("github_autoscaler_job_queued", "Total Number of jobs queued");
private static readonly Gauge CompletedJobsCount = Metrics
.CreateGauge("github_autoscaler_job_completed", "Total Number of jobs completed");
private static readonly Gauge InProgressJobsCount = Metrics
.CreateGauge("github_autoscaler_job_inprogress", "Total Number of jobs inprogress");
private static readonly Gauge DanglingRunnersCount = Metrics
.CreateGauge("github_autoscaler_runners_dangling", "Number of provisioned runners that never picked up a job");
private static readonly Gauge RunnersWithCompletedJobsCount = Metrics
.CreateGauge("github_autoscaler_runners_completed_jobs", "Number of runners with completed jobs awaiting cleanup");
private readonly RunnerQueue _queues;
private List<CloudBan> _bannedClouds = new List<CloudBan>();
public PoolManager(IEnumerable<ICloudController> cc, ILogger<PoolManager> logger, RunnerQueue queues)
{
List<ICloudController> cloudControllers = cc.ToList();
_cc = cloudControllers;
_logger = logger;
_queues = queues;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
// Do init shit
_logger.LogInformation("PoolManager online.");
_logger.LogInformation("Queuing base load runner start...");
List<GithubTargetConfiguration> targetConfig = Program.Config.TargetConfigs;
await CleanUpRunners(targetConfig);
await StartPoolRunners(targetConfig);
_logger.LogInformation("Poolmanager init done.");
// Kick the PoolManager into background
await Task.Yield();
DateTime crudeTimer = DateTime.UtcNow;
DateTime crudeStatsTimer = DateTime.UtcNow;
int cullMinutes = 1;
int statsSeconds = 10;
while (!stoppingToken.IsCancellationRequested)
{
if (DateTime.UtcNow - crudeStatsTimer > TimeSpan.FromSeconds(statsSeconds))
{
// Update config
Program.LoadConfiguration();
targetConfig = Program.Config.TargetConfigs;
// Grab some stats
await ProcessStats(targetConfig);
crudeStatsTimer = DateTime.UtcNow;
}
// check for culling interval
if (DateTime.UtcNow - crudeTimer > TimeSpan.FromMinutes(cullMinutes))
{
_logger.LogInformation("Cleaning runners...");
var staleRemoved = _queues.CreatedRunners.RemoveStale(TimeSpan.FromMinutes(15));
if (staleRemoved > 0)
_logger.LogWarning("Removed {Count} stale entries from CreatedRunnersTracking", staleRemoved);
var checkInId = SentrySdk.CaptureCheckIn("CheckForStuckRunners", CheckInStatus.InProgress);
try
{
await CheckForStuckRunners(targetConfig);
SentrySdk.CaptureCheckIn("CheckForStuckRunners", CheckInStatus.Ok, checkInId);
}
catch (Exception ex)
{
_logger.LogError($"Unable to check for stuck runners: {ex.GetFullExceptionDetails()}");
SentrySdk.CaptureCheckIn("CheckForStuckRunners", CheckInStatus.Error, checkInId);
SentrySdk.CaptureException(ex);
}
try
{
await CleanUpRunners(targetConfig);
}
catch (Exception ex)
{
_logger.LogError($"Unable to clean up runners: {ex.GetFullExceptionDetails()}");
SentrySdk.CaptureException(ex);
}
try
{
await StartPoolRunners(targetConfig);
}
catch (Exception ex)
{
_logger.LogError($"Unable to start pool runners: {ex.GetFullExceptionDetails()}");
SentrySdk.CaptureException(ex);
}
await CheckForStuckJobs(targetConfig);
await CleanupDatabase();
foreach (var ban in _bannedClouds.ToList())
{
if (ban.UnbanTime < DateTime.UtcNow)
{
_logger.LogInformation($"Unbanned {ban.Size} on {ban.Cloud}...");
_bannedClouds.Remove(ban);
}
}
crudeTimer = DateTime.UtcNow;
}
int deleteQueueSize = _queues.DeleteTasks.Count;
var deletionTasks = new List<Task>();
// Run down the deletion queue in completion to potentially free up resources on HTZ cloud
for (int i = 0; i < deleteQueueSize; i++)
{
if (!_queues.DeleteTasks.TryDequeue(out DeleteRunnerTask dtask)) continue;
if (dtask != null)
{
var deletionTask = DeleteRunner(dtask);
deletionTasks.Add(deletionTask);
await Task.Delay(250, stoppingToken);
}
}
Task.WaitAll(deletionTasks, stoppingToken);
// Process creation tasks in parallel with delay between starts
var runningTasks = new List<Task>();
var lastTaskStartTime = DateTime.UtcNow;
while (runningTasks.Count < Program.Config.ParallelOperations && _queues.CreateTasks.TryDequeue(out CreateRunnerTask task))
{
if (task == null) continue;
// Ensure 500ms spacing between task starts
var timeSinceLastStart = DateTime.UtcNow - lastTaskStartTime;
if (timeSinceLastStart < TimeSpan.FromMilliseconds(500))
{
await Task.Delay(TimeSpan.FromMilliseconds(500) - timeSinceLastStart, stoppingToken);
}
// Start new task and add to running tasks
runningTasks.Add(Task.Run(async () =>
{
bool success = await CreateRunner(task);
if (!success)
{
_logger.LogWarning($"Encountered a problem creating runner for {task.RepoName}.");
}
}, stoppingToken));
lastTaskStartTime = DateTime.UtcNow;
}
// Wait for all running tasks to complete
if (runningTasks.Any())
{
try
{
await Task.WhenAll(runningTasks);
}
catch (Exception ex)
{
_logger.LogError($"Error while processing creation tasks: {ex.Message}");
}
}
/*if (_queues.CreateTasks.TryDequeue(out CreateRunnerTask task))
{
if (task != null)
{
bool success = await CreateRunner(task);
if (!success)
{
// Creation didn't succeed. Let's hold of creating new runners for a minute
_logger.LogWarning($"Encountered a problem creating runner for {task.RepoName}. Will hold queue processing for 10 seconds.");
await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken);
}
}
}*/
await Task.Delay(250, stoppingToken);
}
}
private async Task CleanupDatabase()
{
await using var db = new ActionsRunnerContext();
var cutoffTime = DateTime.UtcNow - TimeSpan.FromDays(30);
// Remove old runners - find runners where their earliest lifecycle event is older than 30 days
var oldRunnerIds = await db.RunnerLifecycles
.GroupBy(rl => rl.RunnerId)
.Select(g => new { RunnerId = g.Key, LatestEvent = g.Max(rl => rl.EventTimeUtc) })
.Where(r => r.LatestEvent < cutoffTime)
.Select(r => r.RunnerId)
.ToListAsync();
if (oldRunnerIds.Count > 0)
{
_logger.LogInformation($"Removing {oldRunnerIds.Count} runners older than 30 days from database");
// Delete RunnerLifecycles first (they reference runners)
var oldLifecycles = await db.RunnerLifecycles.Where(rl => oldRunnerIds.Contains(rl.RunnerId)).ToListAsync();
db.RunnerLifecycles.RemoveRange(oldLifecycles);
await db.SaveChangesAsync();
// Break circular dependencies by nulling out foreign keys
var oldRunners = await db.Runners.Where(r => oldRunnerIds.Contains(r.RunnerId)).ToListAsync();
var oldJobs = await db.Jobs.Where(j => oldRunnerIds.Contains(j.RunnerId.Value)).ToListAsync();
// Null out the foreign keys to break circular reference
foreach (var runner in oldRunners)
{
runner.JobId = null;
}
foreach (var job in oldJobs)
{
job.RunnerId = null;
}
await db.SaveChangesAsync();
// Now delete the runners and jobs
db.Runners.RemoveRange(oldRunners);
db.Jobs.RemoveRange(oldJobs);
await db.SaveChangesAsync();
}
// Remove old completed jobs - only remove completed jobs older than 30 days
var oldCompletedJobs = await db.Jobs
.Where(j => j.CompleteTime < cutoffTime && j.CompleteTime != DateTime.MinValue && j.RunnerId == null)
.ToListAsync();
if (oldCompletedJobs.Count > 0)
{
_logger.LogInformation($"Removing {oldCompletedJobs.Count} completed jobs older than 30 days from database");
db.Jobs.RemoveRange(oldCompletedJobs);
await db.SaveChangesAsync();
}
}
private async Task CheckForStuckRunners(List<GithubTargetConfiguration> targetConfig)
{
using var activity = Program.OrchestratorActivitySource.StartActivity("maintenance.check_stuck_runners");
// check the database for runners that are in "created" state for more then 5 minutes.
await using var db = new ActionsRunnerContext();
var cutoffTime = DateTime.UtcNow - TimeSpan.FromMinutes(10);
// Query stuck runners by joining with lifecycle table
var stuckRunners = await db.Runners
.AsNoTracking()
.Where(r => db.RunnerLifecycles
.Where(rl => rl.RunnerId == r.RunnerId && rl.Status == RunnerStatus.Created)
.Any(rl => rl.EventTimeUtc < cutoffTime) &&
db.RunnerLifecycles
.Where(rl => rl.RunnerId == r.RunnerId)
.OrderByDescending(rl => rl.EventTimeUtc)
.First().Status == RunnerStatus.Created)
.Select(r => new { r.RunnerId, r.CloudServerId, r.Hostname, r.Cloud })
.ToListAsync();
activity?.SetTag("stuck_runners.count", stuckRunners.Count);
if (stuckRunners.Count == 0)
return;
// Process stuck runners and create lifecycle entries
var lifecycleEntries = new List<RunnerLifecycle>();
foreach(var stuckRunner in stuckRunners)
{
// Add to deletion queue
_queues.DeleteTasks.Enqueue(new DeleteRunnerTask
{
ServerId = stuckRunner.CloudServerId,
RunnerDbId = stuckRunner.RunnerId
});
// Create lifecycle entry for batch insert
lifecycleEntries.Add(new RunnerLifecycle
{
RunnerId = stuckRunner.RunnerId,
Event = "Stuck in provisioning. Killing.",
EventTimeUtc = DateTime.UtcNow,
Status = RunnerStatus.Failure
});
_logger.LogWarning($"Killing Runner stuck in provisioning: {stuckRunner.Hostname} on {stuckRunner.Cloud}");
}
// Batch insert lifecycle entries without change tracking
if (lifecycleEntries.Count > 0)
{
db.ChangeTracker.AutoDetectChangesEnabled = false;
db.RunnerLifecycles.AddRange(lifecycleEntries);
await db.SaveChangesAsync();
}
}
private async Task ProcessStats(List<GithubTargetConfiguration> targetConfig)
{
CreateQueueSize.Set(_queues.CreateTasks.Count);
DeleteQueueSize.Set(_queues.DeleteTasks.Count);
ProvisionQueueSize.Set(_queues.CreatedRunners.Count);
foreach(ICloudController cc in _cc)
{
try
{
CspRunnerCount.Labels(cc.CloudIdentifier).Set(await cc.GetServerCountFromCsp());
}
catch(Exception ex)
{
_logger.LogWarning($"Unable to get runner count from CSP {cc.CloudIdentifier}: {ex.GetFullExceptionDetails()}");
SentrySdk.CaptureException(ex, scope =>
{
scope.SetTag("csp", cc.CloudIdentifier);
});
}
}
// Grab job state counts
await using var db = new ActionsRunnerContext();
var stuckTime = DateTime.UtcNow - TimeSpan.FromMinutes(15);
// Count stuck jobs (queued for >15min, excluding throttled jobs)
var stuckJobs = await db.Jobs.CountAsync(x => x.State == JobState.Queued && x.RunnerId == null && x.QueueTime < stuckTime);
StuckJobsCount.Set(stuckJobs);
// Count throttled jobs
var throttledJobs = await db.Jobs.CountAsync(x => x.State == JobState.Throttled);
ThrottledJobsCount.Set(throttledJobs);
var jobsByState = await db.Jobs.GroupBy(x => x.State).Select(x => new { x.Key, Count = x.Count() }).ToListAsync();
QueuedJobsCount.Set(jobsByState.FirstOrDefault(x => x.Key == JobState.Queued)?.Count ?? 0);
CompletedJobsCount.Set(jobsByState.FirstOrDefault(x => x.Key == JobState.Completed)?.Count ?? 0);
InProgressJobsCount.Set(jobsByState.FirstOrDefault(x => x.Key == JobState.InProgress)?.Count ?? 0);
// Calculate dangling runners metric - idle runners with no job assignment older than 30 min
var danglingCutoff = DateTime.UtcNow - TimeSpan.FromMinutes(30);
var danglingRunners = await db.Runners
.Where(r => r.IsOnline &&
r.JobId == null &&
db.RunnerLifecycles
.Any(rl => rl.RunnerId == r.RunnerId && rl.Status == RunnerStatus.CreationQueued && rl.EventTimeUtc < danglingCutoff))
.CountAsync();
DanglingRunnersCount.Set(danglingRunners);
// Calculate runners with completed jobs
var runnersWithCompletedJobs = await db.Runners
.Where(r => r.IsOnline &&
r.JobId != null &&
(r.Job.State == JobState.Completed || r.Job.State == JobState.Cancelled || r.Job.State == JobState.Vanished))
.CountAsync();
RunnersWithCompletedJobsCount.Set(runnersWithCompletedJobs);
// grab runner state counts
// Github runner stats
try
{
foreach (GithubTargetConfiguration tgt in targetConfig)
{
GithubRunnersGauge.Labels(tgt.Name, "active").Set(0);
GithubRunnersGauge.Labels(tgt.Name, "idle").Set(0);
GithubRunnersGauge.Labels(tgt.Name, "offline").Set(0);
List<GitHubRunner> orgRunners = tgt.Target switch
{
TargetType.Repository => await GitHubApi.GetRunnersForRepo(tgt.GitHubToken, tgt.Name),
TargetType.Organization => await GitHubApi.GetRunnersForOrg(tgt.GitHubToken, tgt.Name),
_ => throw new ArgumentOutOfRangeException()
};
var ghStatus = orgRunners.Where(x => x.Name.StartsWith(Program.Config.RunnerPrefix)).GroupBy(x =>
{
if (x.Busy)
{
return "active";
}
if (x.Status == "online")
{
return "idle";
}
return x.Status;
}).Select(x => new { Status = x.Key, Count = x.Count() });
foreach (var ghs in ghStatus)
{
GithubRunnersGauge.Labels(tgt.Name, ghs.Status).Set(ghs.Count);
}
}
}
catch (Exception ex)
{
SentrySdk.CaptureException(ex);
_logger.LogError($"Unable to get stats: {ex.Message}");
}
}
/// <summary>
/// Checks if the runner quota has been reached for the given owner
/// </summary>
/// <param name="owner">The GitHub target configuration</param>
/// <param name="db">Database context</param>
/// <returns>True if quota is reached and no more runners should be created, false otherwise</returns>
private async Task<bool> IsQuotaReached(GithubTargetConfiguration owner, ActionsRunnerContext db)
{
// If no quota is set, unlimited runners are allowed
if (!owner.RunnerQuota.HasValue)
{
return false;
}
// Count all runners that are actively consuming resources (not deleted/failed/cancelled)
// This includes: CreationQueued, Created, Provisioned, Processing (states 1-4)
// Excludes: DeletionQueued, Deleted, Failure, VanishedOnCloud, Cleanup, Cancelled (states 5+)
var runners = await db.Runners
.Include(x => x.Lifecycle)
.Where(x => x.Owner == owner.Name)
.ToListAsync();
int currentRunnerCount = runners.Count(x => x.LastState < RunnerStatus.DeletionQueued);
bool quotaReached = currentRunnerCount >= owner.RunnerQuota.Value;
if (quotaReached)
{
_logger.LogWarning($"Runner quota reached for {owner.Name}: {currentRunnerCount}/{owner.RunnerQuota.Value} (includes queued/provisioning runners)");
}
return quotaReached;
}
private async Task StartPoolRunners(List<GithubTargetConfiguration> targetConfig)
{
// Start pool runners
await using var db = new ActionsRunnerContext();
foreach (GithubTargetConfiguration owner in targetConfig)
{
_logger.LogInformation($"Checking pool runners for {owner.Name}");
// Check if quota is reached for this owner
if (await IsQuotaReached(owner, db))
{
_logger.LogWarning($"Skipping pool runner creation for {owner.Name} - quota reached");
continue;
}
List<Runner> activeRunners = await db.Runners
.Include(x => x.Lifecycle)
.Where(x => x.Owner == owner.Name)
.ToListAsync();
// Count runners that are still alive (not yet deleted/failed/cancelled)
activeRunners = activeRunners.Where(x => x.LastState < RunnerStatus.DeletionQueued).ToList();
foreach (Pool pool in owner.Pools)
{
int existCt = activeRunners.Count(x => x.Size == pool.Size);
int missingCt = pool.NumRunners - existCt;
string arch = Program.Config.Sizes.FirstOrDefault(x => x.Name == pool.Size)?.Arch;
_logger.LogInformation($"Checking pool {pool.Size} [{arch}]: Existing={existCt} Requested={pool.NumRunners} Missing={missingCt}");
for (int i = 0; i < missingCt; i++)
{
// Check quota again before each runner creation
if (await IsQuotaReached(owner, db))
{
_logger.LogWarning($"Quota reached while creating pool runners for {owner.Name} - stopping at {i}/{missingCt}");
break;
}
// Queue VM creation
var profile = pool.Profile ?? "default";
Runner newRunner = new()
{
Size = pool.Size,
Cloud = "htz",
Hostname = "Unknown",
Profile = profile,
Lifecycle =
[
new RunnerLifecycle
{
EventTimeUtc = DateTime.UtcNow,
Status = RunnerStatus.CreationQueued,
Event = "Created as pool runner"
}
],
IsOnline = false,
Arch = arch,
IPv4 = string.Empty,
IsCustom = profile != "default",
Owner = owner.Name
};
await db.Runners.AddAsync(newRunner);
await db.SaveChangesAsync();
_queues.CreateTasks.Enqueue(new CreateRunnerTask
{
RepoName = owner.Name,
TargetType = owner.Target,
RunnerDbId = newRunner.RunnerId
});
_logger.LogInformation($"[{i+1}/{missingCt}] Queued {pool.Size} runner for {owner.Name}");
}
}
}
}
private async Task CheckForStuckJobs(List<GithubTargetConfiguration> targetConfig)
{
using var activity = Program.OrchestratorActivitySource.StartActivity("maintenance.check_stuck_jobs");
await using var db = new ActionsRunnerContext();
var stuckTime = DateTime.UtcNow - TimeSpan.FromMinutes(10);
// Check both Queued and Throttled jobs that have been waiting >10min without a runner
var stuckJobs = await db.Jobs
.Where(x => (x.State == JobState.Queued || x.State == JobState.Throttled) && x.RunnerId == null && x.QueueTime < stuckTime)
.ToListAsync();
activity?.SetTag("stuck_jobs.candidate_count", stuckJobs.Count);
// First pass: verify with GitHub which jobs are actually still queued
var confirmedStuckJobs = new List<Job>();
foreach (var stuckJob in stuckJobs)
{
var owner = targetConfig.FirstOrDefault(x => x.Name == stuckJob.Owner);
if (owner == null)
{
_logger.LogError($"Unable to get owner for stuck job. {stuckJob.JobId}");
continue;
}
// Check if quota is reached
bool quotaReached = await IsQuotaReached(owner, db);
if (quotaReached)
{
// Mark job as Throttled if it isn't already
if (stuckJob.State != JobState.Throttled)
{
_logger.LogInformation($"Job {stuckJob.JobId} in {stuckJob.Repository} is throttled due to runner quota limit.");
stuckJob.State = JobState.Throttled;
await db.SaveChangesAsync();
}
continue;
}
else
{
// Quota is available - if job was throttled, move it back to queued
if (stuckJob.State == JobState.Throttled)
{
_logger.LogInformation($"Quota now available for throttled job {stuckJob.JobId}. Moving to queued state.");
stuckJob.State = JobState.Queued;
await db.SaveChangesAsync();
}
}
// Verify job is still queued on GitHub before treating it as stuck
var (ghJob, ghStatusCode) = await GitHubApi.GetJobInfoForRepo(stuckJob.GithubJobId, stuckJob.Repository , owner.GitHubToken);
if (ghJob == null || ghJob.Status != "queued")
{
if (ghJob == null && ghStatusCode == System.Net.HttpStatusCode.NotFound)
{
_logger.LogWarning($"Job {stuckJob.GithubJobId} not found on GitHub (404) - marking as vanished.");
stuckJob.State = JobState.Vanished;
stuckJob.CompleteTime = DateTime.UtcNow;
await db.SaveChangesAsync();
}
else if (ghJob == null)
{
_logger.LogWarning($"Unable to verify job {stuckJob.JobId} on GitHub (HTTP {(int)ghStatusCode}) - skipping this cycle");
}
else if (ghJob.Status == "completed")
{
_logger.LogInformation($"Job {stuckJob.JobId} already completed on GitHub - updating local state");
stuckJob.State = JobState.Completed;
stuckJob.CompleteTime = DateTime.UtcNow;
await db.SaveChangesAsync();
}
else
{
_logger.LogInformation($"Job {stuckJob.JobId} has GitHub status '{ghJob.Status}' - not queued");
if (stuckJob.QueueTime + TimeSpan.FromHours(2) < DateTime.UtcNow)
{
_logger.LogWarning($"Marking job {stuckJob.GithubJobId} as vanished - no longer queued on GitHub for over 2h.");
stuckJob.State = JobState.Vanished;
stuckJob.CompleteTime = DateTime.UtcNow;
await db.SaveChangesAsync();
}
}
continue;
}
// Job is confirmed stuck on GitHub
confirmedStuckJobs.Add(stuckJob);
}
activity?.SetTag("stuck_jobs.confirmed_count", confirmedStuckJobs.Count);
// Second pass: create replacement runners for confirmed stuck jobs
foreach (var stuckJob in confirmedStuckJobs)
{
var owner = targetConfig.First(x => x.Name == stuckJob.Owner);
_logger.LogWarning($"Found stuck Job: {stuckJob.JobId} in {stuckJob.Repository}. Starting new runner to compensate...");
// Check if there is already a runner in queue to unstuck
if (_queues.CreateTasks.Any(x => x.IsStuckReplacement && x.StuckJobId == stuckJob.JobId))
{
_logger.LogWarning($"Creating queue already has a task for jobs {stuckJob.JobId}");
continue;
}
// Count-based check: compare matching runners in pipeline vs confirmed stuck jobs needing them
var profile = stuckJob.RequestedProfile ?? "default";
int matchingRunnersInPipeline =
_queues.CreateTasks.CountMatchingRunners(stuckJob.RequestedSize, stuckJob.Owner, profile)
+ _queues.CreatedRunners.CountMatchingRunners(stuckJob.RequestedSize, stuckJob.Owner, profile);
int stuckJobsWithSameRequirements = confirmedStuckJobs.Count(j =>
j.RequestedSize == stuckJob.RequestedSize
&& j.Owner == stuckJob.Owner
&& (j.RequestedProfile ?? "default") == profile);
if (matchingRunnersInPipeline >= stuckJobsWithSameRequirements)
{
_logger.LogInformation(
"Enough runners in pipeline ({RunnerCount}) for stuck jobs ({JobCount}) with Size={Size}, Owner={Owner}, Profile={Profile}. Skipping replacement for job {JobId}.",
matchingRunnersInPipeline, stuckJobsWithSameRequirements,
stuckJob.RequestedSize, stuckJob.Owner, profile, stuckJob.JobId);
continue;
}
int replacementsInQueue = _queues.CreateTasks.CountWhere(x => x.IsStuckReplacement);
if (replacementsInQueue > 25)
{
_logger.LogWarning($"Creating queue already has {replacementsInQueue} stuck jobs replacements. Not adding more strain.");
continue;
}
string arch = Program.Config.Sizes.FirstOrDefault(x => x.Name == stuckJob.RequestedSize)?.Arch;
Runner newRunner = new()
{
Size = stuckJob.RequestedSize,
Cloud = "htz",
Hostname = "Unknown",
Profile = profile,
Lifecycle =
[
new RunnerLifecycle
{
EventTimeUtc = DateTime.UtcNow,
Status = RunnerStatus.CreationQueued,
Event = $"Created for stuck job {stuckJob.JobId}"
}
],
IsOnline = false,
Arch = arch,
IPv4 = string.Empty,
IsCustom = profile != "default",
Owner = stuckJob.Owner,
StuckJobReplacement = true
};
await db.Runners.AddAsync(newRunner);
await db.SaveChangesAsync();
_queues.CreateTasks.Enqueue(new CreateRunnerTask
{
RepoName = stuckJob.Repository,
TargetType = owner.Target,
RunnerDbId = newRunner.RunnerId,
IsStuckReplacement = true,
StuckJobId = stuckJob.JobId
});
}
}
// Helper methods for cleanup process
/// <summary>
/// Gets the creation time for a runner. Prefers CreatedTime from database, falls back to CSP time.
/// Automatically loads Lifecycle if not already loaded.
/// </summary>
private async Task<DateTime> GetRunnerCreationTime(Runner runner, CspServer cspServer = null, ActionsRunnerContext db = null)
{
// Ensure Lifecycle is loaded
if (runner.Lifecycle == null || !runner.Lifecycle.Any())
{
if (db != null)
{
try
{
await db.Entry(runner).Collection(r => r.Lifecycle).LoadAsync();
}
catch (Exception ex)
{
_logger.LogWarning($"Unable to load Lifecycle for runner {runner.RunnerId}: {ex.Message}");
}
}
else
{
_logger.LogWarning($"GetRunnerCreationTime called without Lifecycle loaded and no DbContext provided for runner {runner.RunnerId}");
}
}
// First choice: Use the Created lifecycle event time (when VM was actually created)
if (runner.Lifecycle?.Any() == true && runner.CreatedTime != DateTime.MaxValue)
return runner.CreatedTime;
// Fallback: Use CSP creation time if available
if (cspServer != null)
return cspServer.CreatedAt.ToUniversalTime();
// Last resort: Use queue time if lifecycle is available
if (runner.Lifecycle?.Any() == true)
return runner.CreationQueuedTime;
// Ultimate fallback: current time minus 1 hour (safe default)
_logger.LogWarning($"Unable to determine creation time for runner {runner.RunnerId} - using default");
return DateTime.UtcNow - TimeSpan.FromHours(1);
}
/// <summary>
/// Checks if a runner's job is complete by checking database state and optionally GitHub API.
/// </summary>
private bool IsJobComplete(Runner runner, GitHubApiWorkflowRun githubJob = null)
{
// No job assigned = never processed = can cleanup
if (runner.Job == null)
return true;
// Check database job state
if (runner.Job.State == JobState.Completed ||
runner.Job.State == JobState.Cancelled ||
runner.Job.State == JobState.Vanished)
return true;
// Cross-check with GitHub API if available
if (githubJob != null &&
(githubJob.Status == "completed" ||
githubJob.Conclusion != null))
return true;
return false;
}
/// <summary>
/// Checks if it's safe to queue a runner for deletion (not already queued recently).
/// </summary>
private bool SafeToQueueDeletion(Runner runner)
{
// Check for recent deletion queue events (within last 5 minutes)
var recentDeletionQueue = runner.Lifecycle
.Where(x => x.Status == RunnerStatus.DeletionQueued)
.OrderByDescending(x => x.EventTimeUtc)
.FirstOrDefault();
if (recentDeletionQueue != null)
{
// If queued within last 5 minutes, don't re-queue
if (DateTime.UtcNow - recentDeletionQueue.EventTimeUtc < TimeSpan.FromMinutes(5))
{
return false;
}
// If queued more than 10 times, something is wrong - force retry
int queueCount = runner.Lifecycle.Count(x => x.Status == RunnerStatus.DeletionQueued);
if (queueCount > 10)
{
_logger.LogError($"Runner {runner.Hostname} has been queued {queueCount} times for deletion - forcing retry");
return true;
}
}
return true;
}
/// <summary>
/// Final safety check before deletion - ensures runner is not actively working.
/// </summary>
private async Task<bool> IsSafeToDelete(Runner runner, GitHubRunner ghRunner = null, ActionsRunnerContext db = null)
{
// NEVER delete if currently processing
if (runner.LastState == RunnerStatus.Processing)
return false;
// NEVER delete if job is in progress
if (runner.Job != null && runner.Job.State == JobState.InProgress)
return false;
// NEVER delete if GitHub shows busy
if (ghRunner != null && ghRunner.Busy)
return false;
// NEVER delete very fresh runners (< 5 minutes) - protect against race conditions
var age = DateTime.UtcNow - await GetRunnerCreationTime(runner, null, db);
if (age < TimeSpan.FromMinutes(5))
return false;
return true;
}
private async Task CleanUpRunners(List<GithubTargetConfiguration> targetConfigs)
{
using var activity = Program.OrchestratorActivitySource.StartActivity("maintenance.cleanup_runners");
List<string> registeredServerNames = new();
await using var db = new ActionsRunnerContext();
foreach (GithubTargetConfiguration githubTarget in targetConfigs)
{
_logger.LogInformation($"Cleaning runners for {githubTarget.Name}...");
// Get runner info from GitHub
List<GitHubRunner> githubRunners = githubTarget.Target switch
{
TargetType.Organization => await GitHubApi.GetRunnersForOrg(githubTarget.GitHubToken, githubTarget.Name),
TargetType.Repository => await GitHubApi.GetRunnersForRepo(githubTarget.GitHubToken, githubTarget.Name),
_ => throw new ArgumentOutOfRangeException()
};
// CATEGORY 1: Offline Runners (Already Dead)
// These runners are offline on GitHub - quick cleanup after 10 minutes
List<GitHubRunner> ghOfflineRunners = githubRunners
.Where(x => x.Name.StartsWith(Program.Config.RunnerPrefix) && x.Status == "offline")
.ToList();
foreach (GitHubRunner ghRunner in ghOfflineRunners)
{
var runner = await db.Runners.Include(x => x.Lifecycle).Include(x => x.Job).FirstOrDefaultAsync(x => x.Hostname == ghRunner.Name);
if (runner == null)
{
// Orphaned GitHub runner - remove immediately
_logger.LogWarning($"Found offline runner on GitHub not in database: {ghRunner.Name} - Removing");
_ = githubTarget.Target switch
{
TargetType.Organization => await GitHubApi.RemoveRunnerFromOrg(githubTarget.Name, githubTarget.GitHubToken, ghRunner.Id),
TargetType.Repository => await GitHubApi.RemoveRunnerFromRepo(githubTarget.Name, githubTarget.GitHubToken, ghRunner.Id),
_ => throw new ArgumentOutOfRangeException()
};
continue;
}
// Protection: Must be at least 10 minutes old
var runnerAge = DateTime.UtcNow - await GetRunnerCreationTime(runner, null, db);
if (runnerAge < TimeSpan.FromMinutes(10))
{
continue;
}
// Protection: Never delete if still processing
if (runner.LastState == RunnerStatus.Processing)
{
_logger.LogWarning($"Runner {runner.Hostname} is offline but in Processing state - protecting");
continue;
}
// Protection: Check safety before deletion
if (!await IsSafeToDelete(runner, ghRunner, db))
{
continue;
}
_logger.LogInformation($"[OFFLINE] Removing offline runner {ghRunner.Name} (age: {runnerAge.TotalMinutes:F1} min)");
// Remove from GitHub
_ = githubTarget.Target switch
{
TargetType.Organization => await GitHubApi.RemoveRunnerFromOrg(githubTarget.Name, githubTarget.GitHubToken, ghRunner.Id),
TargetType.Repository => await GitHubApi.RemoveRunnerFromRepo(githubTarget.Name, githubTarget.GitHubToken, ghRunner.Id),
_ => throw new ArgumentOutOfRangeException()
};
// Mark offline and queue deletion
runner.IsOnline = false;
if (SafeToQueueDeletion(runner))
{
runner.Lifecycle.Add(new()
{
Status = RunnerStatus.DeletionQueued,
EventTimeUtc = DateTime.UtcNow,
Event = $"Offline runner cleanup - age: {runnerAge.TotalMinutes:F1} min"
});
await db.SaveChangesAsync();
_queues.DeleteTasks.Enqueue(new()
{
ServerId = runner.CloudServerId,
RunnerDbId = runner.RunnerId
});
}
else
{
await db.SaveChangesAsync();
_logger.LogDebug($"Skipping deletion queue for {runner.Hostname} - recently queued");
}
}
// CATEGORY 2: Runners with Completed Jobs
// If a job is complete, the runner should be removed quickly (5 min grace)
List<GitHubRunner> ghOnlineRunners = githubRunners
.Where(x => x.Name.StartsWith(Program.Config.RunnerPrefix) && x.Status == "online")
.ToList();
foreach (GitHubRunner ghRunner in ghOnlineRunners)
{
var runner = await db.Runners.Include(x => x.Lifecycle).Include(x => x.Job).FirstOrDefaultAsync(x => x.Hostname == ghRunner.Name);
if (runner == null || runner.Job == null)
{
continue;
}
// Check if job is completed
if (!IsJobComplete(runner))
{
continue;
}
// Protection: 5 minute grace period after job completion
var completionTime = runner.Job.CompleteTime;
if (completionTime != DateTime.MinValue && DateTime.UtcNow - completionTime < TimeSpan.FromMinutes(5))
{
continue;
}
// Protection: Check safety
if (!await IsSafeToDelete(runner, ghRunner, db))
{
continue;
}
_logger.LogInformation($"[COMPLETED JOB] Removing runner {ghRunner.Name} - job {runner.Job.JobId} is complete");
// Remove from GitHub
_ = githubTarget.Target switch
{
TargetType.Organization => await GitHubApi.RemoveRunnerFromOrg(githubTarget.Name, githubTarget.GitHubToken, ghRunner.Id),
TargetType.Repository => await GitHubApi.RemoveRunnerFromRepo(githubTarget.Name, githubTarget.GitHubToken, ghRunner.Id),
_ => throw new ArgumentOutOfRangeException()
};
runner.IsOnline = false;
if (SafeToQueueDeletion(runner))
{