-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice.go
More file actions
2818 lines (2517 loc) · 95.7 KB
/
Copy pathservice.go
File metadata and controls
2818 lines (2517 loc) · 95.7 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
package main
import (
"bytes"
"context"
"embed"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"log"
"net"
"net/http"
"os"
"os/signal"
"regexp"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
)
//go:embed public
var publicFS embed.FS
type Config struct {
ListenAddr string
TrustedProxiesCIDR []string
// ClickHouse (primary telemetry store)
CHDSN string // clickhouse://user:pass@host:9000/telemetry_db
// Limits
MaxBodyBytes int64
RateLimitRPM int // requests per minute per key
RateBurst int // burst tokens
RateKeyMode string // "ip" or "header"
RateKeyHeader string // e.g. "X-Telemetry-Key"
RequestTimeout time.Duration // upstream timeout
EnableReqLogging bool // default false (GDPR-friendly)
// RetentionDays sets a TTL on the raw telemetry table: rows older than this
// are dropped by ClickHouse during its normal merges, with no job to run and
// nothing to schedule.
//
// Off by default, and deliberately so. Without it the table grows without
// bound, which is the real state today -- but switching it on deletes
// history irreversibly, and how far back the project wants to see is a
// decision, not a default someone should inherit by upgrading. Set
// TELEMETRY_RETENTION_DAYS when that decision is made; 400 keeps thirteen
// months, which covers the longest window any dashboard offers.
RetentionDays int
// Cache
RedisURL string
EnableRedis bool
CacheTTL time.Duration
CacheEnabled bool
// Alerts (SMTP)
AlertEnabled bool
SMTPHost string
SMTPPort int
SMTPUser string
SMTPPassword string
SMTPFrom string
SMTPTo []string
SMTPUseTLS bool
AlertFailureThreshold float64
AlertCheckInterval time.Duration
AlertCooldown time.Duration
// GitHub Integration
GitHubToken string // Personal access token for creating issues
GitHubOwner string // Repository owner (e.g., "community-scripts")
GitHubRepo string // Repository name (e.g., "ProxmoxVE")
AdminPassword string // Password to protect admin actions (issue creation)
}
// TelemetryIn matches payload from api.func (bash client)
type TelemetryIn struct {
// Required
RandomID string `json:"random_id"` // Session UUID
ExecutionID string `json:"execution_id,omitempty"` // Unique execution ID
Type string `json:"type"` // "lxc", "vm", "turnkey", "pve", "addon"
NSAPP string `json:"nsapp"` // Application name (e.g., "jellyfin")
Status string `json:"status"` // "installing", "success", "failed", "aborted", "unknown"
// Container/VM specs
CTType int `json:"ct_type,omitempty"` // 1=unprivileged, 2=privileged/VM
DiskSize int `json:"disk_size,omitempty"` // GB
CoreCount int `json:"core_count,omitempty"` // CPU cores
RAMSize int `json:"ram_size,omitempty"` // MB
// System info
OsType string `json:"os_type,omitempty"` // "debian", "ubuntu", "alpine", etc.
OsVersion string `json:"os_version,omitempty"` // "12", "24.04", etc.
PveVer string `json:"pve_version,omitempty"`
// Optional
Method string `json:"method,omitempty"` // "default", "advanced"
Error string `json:"error,omitempty"` // Error description (max 120 chars)
ExitCode int `json:"exit_code,omitempty"` // 0-255
// === EXTENDED FIELDS ===
// GPU Passthrough stats
GPUVendor string `json:"gpu_vendor,omitempty"` // "intel", "amd", "nvidia"
GPUModel string `json:"gpu_model,omitempty"` // e.g., "Intel Arc Graphics"
GPUPassthrough string `json:"gpu_passthrough,omitempty"` // "igpu", "dgpu", "vgpu", "none"
// CPU stats
CPUVendor string `json:"cpu_vendor,omitempty"` // "intel", "amd", "arm"
CPUModel string `json:"cpu_model,omitempty"` // e.g., "Intel Core Ultra 7 155H"
// RAM stats
RAMSpeed string `json:"ram_speed,omitempty"` // e.g., "4800" (MT/s)
// Performance metrics
InstallDuration int `json:"install_duration,omitempty"` // Seconds
// Error categorization
ErrorCategory string `json:"error_category,omitempty"` // "network", "storage", "dependency", "permission", "timeout", "unknown"
// Repository source for collection routing
RepoSource string `json:"repo_source,omitempty"` // "ProxmoxVE", "ProxmoxVED", or "external"
// Dynamic repository slug "owner/repo" (e.g. "community-scripts/ProxmoxVE", "MickLesk/ProxmoxVE")
RepoSlug string `json:"repo_slug,omitempty"`
// HasArm is true when the install actually ran on arm64 hardware (only
// possible for scripts that declare var_arm64=yes).
HasArm bool `json:"has_arm,omitempty"`
// Platform is the virtualization platform: "pve" (Proxmox VE) or "incus".
// Derived from pve_version when the client doesn't send it.
Platform string `json:"platform,omitempty"`
// PayloadVersion is the engine's schema version. 0 means a client from
// before it existed, which is the only honest way to say "unknown age" --
// inferring it from which fields happen to be present is guesswork.
PayloadVersion int `json:"payload_version,omitempty"`
// Arch is the CPU architecture, e.g. amd64 or arm64. The engine has always
// sent it; the server dropped it on the floor until payload version 2.
Arch string `json:"arch,omitempty"`
// FailedCommand and FailedLine locate a failure without parsing the
// free-text error string it used to be flattened into.
FailedCommand string `json:"failed_command,omitempty"`
FailedLine int `json:"failed_line,omitempty"`
// KernelVersion and AppVersion were collected by the engine long before
// anything transmitted them.
KernelVersion string `json:"kernel_version,omitempty"`
AppVersion string `json:"app_version,omitempty"`
}
// TelemetryOut is the output shape for telemetry records
type TelemetryOut struct {
RandomID string `json:"random_id"`
ExecutionID string `json:"execution_id,omitempty"`
Type string `json:"type"`
NSAPP string `json:"nsapp"`
Status string `json:"status"`
CTType int `json:"ct_type,omitempty"`
DiskSize int `json:"disk_size,omitempty"`
CoreCount int `json:"core_count,omitempty"`
RAMSize int `json:"ram_size,omitempty"`
OsType string `json:"os_type,omitempty"`
OsVersion string `json:"os_version,omitempty"`
PveVer string `json:"pve_version,omitempty"`
Method string `json:"method,omitempty"`
Error string `json:"error,omitempty"`
ExitCode int `json:"exit_code,omitempty"`
// Extended fields
GPUVendor string `json:"gpu_vendor,omitempty"`
GPUModel string `json:"gpu_model,omitempty"`
GPUPassthrough string `json:"gpu_passthrough,omitempty"`
CPUVendor string `json:"cpu_vendor,omitempty"`
CPUModel string `json:"cpu_model,omitempty"`
RAMSpeed string `json:"ram_speed,omitempty"`
InstallDuration int `json:"install_duration,omitempty"`
ErrorCategory string `json:"error_category,omitempty"`
// Repository source: "ProxmoxVE", "ProxmoxVED", or "external"
RepoSource string `json:"repo_source,omitempty"`
// Dynamic repository slug "owner/repo"
RepoSlug string `json:"repo_slug,omitempty"`
// HasArm is true when the install ran on arm64 hardware.
HasArm bool `json:"has_arm,omitempty"`
// Platform is the virtualization platform: "pve" or "incus".
Platform string `json:"platform,omitempty"`
// Installation pipeline: JSON array [{s:"installing",t:"..."}, ...] (server-built for API responses)
Pipeline string `json:"pipeline,omitempty"`
// Payload version 2 additions. See TelemetryIn for why each exists.
PayloadVersion int `json:"payload_version,omitempty"`
Arch string `json:"arch,omitempty"`
FailedCommand string `json:"failed_command,omitempty"`
FailedLine int `json:"failed_line,omitempty"`
KernelVersion string `json:"kernel_version,omitempty"`
AppVersion string `json:"app_version,omitempty"`
}
// TelemetryStatusUpdate contains only fields needed for status updates
type TelemetryStatusUpdate struct {
Status string `json:"status"`
ExecutionID string `json:"execution_id,omitempty"`
Error string `json:"error,omitempty"`
ExitCode int `json:"exit_code"`
InstallDuration int `json:"install_duration,omitempty"`
ErrorCategory string `json:"error_category,omitempty"`
GPUVendor string `json:"gpu_vendor,omitempty"`
GPUModel string `json:"gpu_model,omitempty"`
GPUPassthrough string `json:"gpu_passthrough,omitempty"`
CPUVendor string `json:"cpu_vendor,omitempty"`
CPUModel string `json:"cpu_model,omitempty"`
RAMSpeed string `json:"ram_speed,omitempty"`
RepoSource string `json:"repo_source,omitempty"`
RepoSlug string `json:"repo_slug,omitempty"`
}
// Allowed values for 'repo_source' field
var allowedRepoSource = map[string]bool{
"ProxmoxVE": true,
"ProxmoxVED": true,
"external": true,
}
// ---------- Write-Ahead Queue ----------
// Decouples HTTP accept from ClickHouse write. The /telemetry handler enqueues
// work and returns 202 immediately. A pool of workers drains the queue with retries.
// WriteItem is a single telemetry payload queued for ClickHouse write.
type WriteItem struct {
Payload TelemetryOut
Attempt int
EnqueueAt time.Time
}
// WriteQueue buffers telemetry writes and processes them via worker goroutines.
type WriteQueue struct {
ch chan WriteItem
client *CHClient
workers int
maxRetry int
index *ExecIndex // in-memory execution_id dedup
inFlight atomic.Int64
}
// NewWriteQueue creates a buffered write queue with the given capacity and worker count.
func NewWriteQueue(client *CHClient, capacity, workers int, index *ExecIndex) *WriteQueue {
wq := &WriteQueue{
ch: make(chan WriteItem, capacity),
client: client,
workers: workers,
maxRetry: 3,
index: index,
}
return wq
}
// Start launches the worker goroutines.
func (wq *WriteQueue) Start() {
for i := 0; i < wq.workers; i++ {
go wq.worker(i)
}
log.Printf("[QUEUE] Started %d write workers (buffer=%d)", wq.workers, cap(wq.ch))
}
// Enqueue adds a payload to the write queue. Returns false if the queue is full.
func (wq *WriteQueue) Enqueue(payload TelemetryOut) bool {
select {
case wq.ch <- WriteItem{Payload: payload, Attempt: 0, EnqueueAt: time.Now()}:
return true
default:
return false
}
}
// Len returns the current queue depth.
func (wq *WriteQueue) Len() int {
return len(wq.ch)
}
// Stop blocks until the queue is fully drained (buffer empty and no in-flight
// writes) or the timeout elapses. Call it after the HTTP server has stopped
// accepting new requests so a deploy/restart doesn't silently lose queued
// telemetry. The channel is intentionally left open so in-flight retries can
// re-enqueue without panicking on a closed channel.
func (wq *WriteQueue) Stop(timeout time.Duration) {
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
if wq.Len() == 0 && wq.inFlight.Load() == 0 {
log.Printf("[QUEUE] drained cleanly")
return
}
time.Sleep(100 * time.Millisecond)
}
log.Printf("[QUEUE] drain timed out after %v (qlen=%d, in-flight=%d) — remaining writes lost",
timeout, wq.Len(), wq.inFlight.Load())
}
func (wq *WriteQueue) worker(id int) {
for item := range wq.ch {
// inFlight stays incremented for the entire iteration (including retry
// backoff and re-enqueue) so Stop() never reports "drained" while a
// worker is still about to put an item back on the queue.
wq.inFlight.Add(1)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
err := wq.processItem(ctx, item)
cancel()
if err != nil {
item.Attempt++
if item.Attempt < wq.maxRetry {
// Exponential backoff: 1s, 2s, 4s
backoff := time.Duration(1<<uint(item.Attempt)) * time.Second
time.Sleep(backoff)
// Re-enqueue for retry (non-blocking — drop if queue full)
select {
case wq.ch <- item:
default:
log.Printf("[QUEUE] worker %d: retry queue full, dropping nsapp=%s status=%s exec=%s (attempt %d)",
id, item.Payload.NSAPP, item.Payload.Status, item.Payload.ExecutionID, item.Attempt)
}
} else {
log.Printf("[QUEUE] worker %d: final failure nsapp=%s status=%s exec=%s: %v",
id, item.Payload.NSAPP, item.Payload.Status, item.Payload.ExecutionID, err)
}
}
wq.inFlight.Add(-1)
}
}
// isTerminalStatus reports whether a status represents a final outcome of an execution.
func isTerminalStatus(status string) bool {
switch status {
case "success", "failed", "aborted", "unknown":
return true
}
return false
}
// processItem performs the ClickHouse INSERT.
// Every event is a new row in ClickHouse (append-only). There is no find+update — every event is a new row.
//
// Deduplication strategy (prevents the over-counting that inflates failure rates):
// - "installing": only the first event per execution_id is written.
// - terminal events (success/failed/aborted/unknown): only the FIRST terminal
// event per execution_id is written. The bash client legitimately reports the
// same failure multiple times (host trap + EXIT trap + container abort), so
// without this guard every failure was counted 2-4×.
func (wq *WriteQueue) processItem(ctx context.Context, item WriteItem) error {
payload := item.Payload
// Dedup: skip duplicate "installing" events for the same execution_id
if payload.Status == "installing" && payload.ExecutionID != "" {
if _, found := wq.index.Get(payload.ExecutionID); found {
return nil
}
}
// Dedup: only the first terminal event per execution_id is persisted.
terminalMarked := false
if isTerminalStatus(payload.Status) && payload.ExecutionID != "" {
// Atomic check-and-set in memory (handles concurrent workers).
if !wq.index.MarkTerminalIfAbsent(payload.ExecutionID) {
return nil // a terminal event for this execution was already handled
}
terminalMarked = true
// In-memory miss: also check the DB (covers process restarts / multi-instance).
if has, err := wq.client.HasTerminalExecutionID(ctx, payload.ExecutionID); err == nil && has {
return nil // a terminal row already exists in ClickHouse — keep it marked
}
}
// INSERT into ClickHouse (all events — installing, configuring, success, failed, etc.)
if err := wq.client.InsertTelemetry(ctx, payload); err != nil {
// Roll back the terminal mark so a retry can still write the row.
if terminalMarked {
wq.index.UnmarkTerminal(payload.ExecutionID)
}
return err
}
// Update in-memory index
if payload.ExecutionID != "" {
switch payload.Status {
case "installing":
wq.index.Set(payload.ExecutionID, payload.ExecutionID)
case "success", "failed", "aborted", "unknown":
wq.index.Delete(payload.ExecutionID)
}
}
return nil
}
// ---------- In-Memory Execution ID Index ----------
// Maps execution_id → PB record_id to avoid repeated FindRecord calls.
type ExecIndex struct {
m sync.Map // execution_id -> record_id (tracks active "installing" executions)
terminal sync.Map // execution_id -> time.Time (tracks executions that already got a terminal row)
}
func NewExecIndex() *ExecIndex {
return &ExecIndex{}
}
func (idx *ExecIndex) Get(executionID string) (string, bool) {
v, ok := idx.m.Load(executionID)
if !ok {
return "", false
}
return v.(string), true
}
func (idx *ExecIndex) Set(executionID, recordID string) {
if executionID != "" && recordID != "" {
idx.m.Store(executionID, recordID)
}
}
func (idx *ExecIndex) Delete(executionID string) {
idx.m.Delete(executionID)
}
// MarkTerminalIfAbsent atomically records that a terminal event for executionID
// is being handled. It returns true if this caller is the first (i.e. the event
// should be written) and false if a terminal event was already seen.
func (idx *ExecIndex) MarkTerminalIfAbsent(executionID string) bool {
if executionID == "" {
return true
}
_, loaded := idx.terminal.LoadOrStore(executionID, time.Now())
return !loaded
}
// UnmarkTerminal removes a terminal mark (used to roll back after a failed write).
func (idx *ExecIndex) UnmarkTerminal(executionID string) {
if executionID != "" {
idx.terminal.Delete(executionID)
}
}
// StartJanitor periodically evicts old terminal marks to bound memory usage.
// Duplicate terminal events for one execution always arrive within seconds, so a
// generous window is safe; anything older is covered by the ClickHouse fallback check.
func (idx *ExecIndex) StartJanitor() {
go func() {
t := time.NewTicker(1 * time.Hour)
defer t.Stop()
for range t.C {
cutoff := time.Now().Add(-48 * time.Hour)
idx.terminal.Range(func(k, v interface{}) bool {
if ts, ok := v.(time.Time); ok && ts.Before(cutoff) {
idx.terminal.Delete(k)
}
return true
})
}
}()
}
// -------- Rate limiter (token bucket / minute window, simple) --------
type bucket struct {
tokens int
reset time.Time
}
type RateLimiter struct {
mu sync.Mutex
buckets map[string]*bucket
rpm int
burst int
window time.Duration
cleanInt time.Duration
}
func NewRateLimiter(rpm, burst int) *RateLimiter {
rl := &RateLimiter{
buckets: make(map[string]*bucket),
rpm: rpm,
burst: burst,
window: time.Minute,
cleanInt: 5 * time.Minute,
}
go rl.cleanupLoop()
return rl
}
func (r *RateLimiter) cleanupLoop() {
t := time.NewTicker(r.cleanInt)
defer t.Stop()
for range t.C {
now := time.Now()
r.mu.Lock()
for k, b := range r.buckets {
if now.After(b.reset.Add(2 * r.window)) {
delete(r.buckets, k)
}
}
r.mu.Unlock()
}
}
func (r *RateLimiter) Allow(key string) bool {
if r.rpm <= 0 {
return true
}
now := time.Now()
r.mu.Lock()
defer r.mu.Unlock()
b, ok := r.buckets[key]
if !ok || now.After(b.reset) {
r.buckets[key] = &bucket{tokens: min(r.burst, r.rpm), reset: now.Add(r.window)}
b = r.buckets[key]
}
if b.tokens <= 0 {
return false
}
b.tokens--
return true
}
// -------- Utility: GDPR-safe key extraction --------
type ProxyTrust struct {
nets []*net.IPNet
}
func NewProxyTrust(cidrs []string) (*ProxyTrust, error) {
var nets []*net.IPNet
for _, c := range cidrs {
_, n, err := net.ParseCIDR(strings.TrimSpace(c))
if err != nil {
return nil, err
}
nets = append(nets, n)
}
return &ProxyTrust{nets: nets}, nil
}
func (pt *ProxyTrust) isTrusted(ip net.IP) bool {
for _, n := range pt.nets {
if n.Contains(ip) {
return true
}
}
return false
}
// isPrivateIP returns true if the IP is in RFC 1918 / RFC 6598 private ranges
// (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 100.64.0.0/10) or loopback.
// These are always trusted as reverse proxy sources.
func isPrivateIP(ip net.IP) bool {
if ip.IsLoopback() {
return true
}
privateRanges := []struct {
start net.IP
end net.IP
}{
{net.ParseIP("10.0.0.0"), net.ParseIP("10.255.255.255")},
{net.ParseIP("172.16.0.0"), net.ParseIP("172.31.255.255")},
{net.ParseIP("192.168.0.0"), net.ParseIP("192.168.255.255")},
{net.ParseIP("100.64.0.0"), net.ParseIP("100.127.255.255")},
}
ip4 := ip.To4()
if ip4 == nil {
return false
}
for _, r := range privateRanges {
if bytes.Compare(ip4, r.start.To4()) >= 0 && bytes.Compare(ip4, r.end.To4()) <= 0 {
return true
}
}
return false
}
func getClientIP(r *http.Request, pt *ProxyTrust) net.IP {
// If behind reverse proxy, trust X-Forwarded-For if remote is a configured
// trusted proxy OR a private/RFC1918 IP (common Docker/K8s/reverse proxy setup).
host, _, _ := net.SplitHostPort(r.RemoteAddr)
remote := net.ParseIP(host)
if remote == nil {
return nil
}
trusted := (pt != nil && pt.isTrusted(remote)) || isPrivateIP(remote)
if trusted {
xff := r.Header.Get("X-Forwarded-For")
if xff != "" {
parts := strings.Split(xff, ",")
ip := net.ParseIP(strings.TrimSpace(parts[0]))
if ip != nil {
return ip
}
}
}
return remote
}
// -------- Validation (strict allowlist) --------
var (
// Allowed values for 'type' field
allowedType = map[string]bool{"lxc": true, "vm": true, "turnkey": true, "pve": true, "addon": true, "tool": true}
// Allowed values for 'status' field
allowedStatus = map[string]bool{"installing": true, "validation": true, "configuring": true, "success": true, "failed": true, "aborted": true, "unknown": true}
// Allowed values for 'os_type' field
allowedOsType = map[string]bool{
"debian": true, "ubuntu": true, "alpine": true, "devuan": true,
"fedora": true, "rocky": true, "alma": true, "centos": true,
"opensuse": true, "gentoo": true, "openeuler": true,
// VM-specific OS types
"homeassistant": true, "opnsense": true, "openwrt": true,
"mikrotik": true, "umbrel-os": true, "pimox-haos": true,
"owncloud": true, "turnkey-nextcloud": true, "arch-linux": true,
}
// Allowed values for 'gpu_vendor' field
allowedGPUVendor = map[string]bool{"intel": true, "amd": true, "nvidia": true, "unknown": true, "": true}
// Allowed values for 'gpu_passthrough' field
allowedGPUPassthrough = map[string]bool{"igpu": true, "dgpu": true, "vgpu": true, "none": true, "unknown": true, "": true}
// Allowed values for 'cpu_vendor' field
allowedCPUVendor = map[string]bool{"intel": true, "amd": true, "arm": true, "apple": true, "qualcomm": true, "unknown": true, "": true}
// Allowed values for 'error_category' field
allowedErrorCategory = map[string]bool{
"network": true, "storage": true, "dependency": true, "permission": true,
"timeout": true, "config": true, "resource": true, "unknown": true, "": true,
"user_aborted": true, "apt": true, "command_not_found": true,
"service": true, "database": true, "signal": true, "proxmox": true,
"shell": true, "build": true, "preflight": true, "runtime": true,
}
// exitCodeInfo consolidates description and category for all known exit codes.
// This is the single source of truth — dashboard.go and all other code should
// use getExitCodeDescription() / getExitCodeCategory() instead of duplicating.
exitCodeInfo = map[int]struct {
Desc string
Category string
}{
// --- Generic / Shell ---
0: {"Success", ""},
1: {"General error", "unknown"},
2: {"Misuse of shell builtins", "unknown"},
3: {"General syntax or argument error", "unknown"},
// --- curl / wget ---
4: {"curl: Feature not supported or protocol error", "network"},
5: {"curl: Could not resolve proxy", "network"},
6: {"curl: DNS resolution failed", "network"},
7: {"curl: Connection refused / host down", "network"},
8: {"curl: Server reply error", "network"},
16: {"curl: HTTP/2 framing layer error", "network"},
18: {"curl: Partial file (transfer incomplete)", "network"},
22: {"curl: HTTP error (404/500 etc.)", "network"},
23: {"curl: Write error (disk full?)", "storage"},
24: {"curl: Write to local file failed", "storage"},
25: {"curl: Upload failed", "network"},
26: {"curl: Read error on local file (I/O)", "storage"},
27: {"curl: Out of memory", "resource"},
28: {"curl: Connection timed out", "timeout"},
30: {"curl: FTP port command failed", "network"},
32: {"curl: FTP SIZE command failed", "network"},
33: {"curl: HTTP range error", "network"},
34: {"curl: HTTP post error", "network"},
35: {"curl: SSL/TLS handshake failed", "network"},
36: {"curl: FTP bad download resume", "network"},
47: {"curl: Too many redirects", "network"},
51: {"curl: SSL peer certificate verification failed", "network"},
52: {"curl: Empty reply from server", "network"},
55: {"curl: Failed sending network data", "network"},
56: {"curl: Receive error (connection reset)", "network"},
59: {"curl: Couldn't use specified SSL cipher", "network"},
75: {"Temporary failure (retry later)", "network"},
78: {"curl: Remote file not found (404)", "network"},
92: {"curl: HTTP/2 stream error", "network"},
95: {"curl: HTTP/3 layer error", "network"},
// --- Docker / Privileged ---
10: {"Docker / privileged mode required", "config"},
// --- BSD sysexits.h (64-78) ---
64: {"Usage error (wrong arguments)", "config"},
65: {"Data format error (bad input data)", "unknown"},
66: {"Input file not found", "unknown"},
67: {"User not found", "unknown"},
68: {"Host not found", "network"},
69: {"Service unavailable", "service"},
70: {"Internal software error", "unknown"},
71: {"System error (OS-level failure)", "unknown"},
72: {"Critical OS file missing", "unknown"},
73: {"Cannot create output file", "storage"},
74: {"I/O error", "storage"},
76: {"Remote protocol error", "network"},
77: {"Permission denied", "permission"},
// --- APT / DPKG ---
100: {"APT: Package manager error (broken packages)", "apt"},
// Not apt. apt reports its problems as 100; 101 is what cargo returns for
// any failure at all, and in fourteen days of data every single exit-101
// signature was a Rust build -- scanopy 48, vaultwarden 27, oxicloud 25,
// a hundred of the hundred and twenty. Calling that "APT: Configuration
// error (bad sources)" sent people to look at sources.list for a
// compiler error. Left to the evidence below, like exit 1.
101: {"Build or configuration error", "unknown"},
102: {"APT: Lock held by another process", "apt"},
// --- Script Validation & Setup (103-123) ---
103: {"Validation: Shell is not Bash", "preflight"},
104: {"Validation: Not running as root", "preflight"},
105: {"Validation: PVE version not supported", "preflight"},
106: {"Validation: Architecture not supported (ARM/PiMox)", "preflight"},
107: {"Validation: Kernel key parameters unreadable", "preflight"},
108: {"Validation: Kernel key limits exceeded", "preflight"},
109: {"Proxmox: No available container ID", "proxmox"},
110: {"Proxmox: Failed to apply default.vars", "proxmox"},
111: {"Proxmox: App defaults file not available", "proxmox"},
112: {"Proxmox: Invalid install menu option", "config"},
113: {"LXC: Under-provisioned — user aborted", "user_aborted"},
114: {"LXC: Storage too low — user aborted", "user_aborted"},
115: {"Download: install.func failed or incomplete", "network"},
116: {"Proxmox: Default bridge vmbr0 not found", "config"},
117: {"LXC: Container did not reach running state", "proxmox"},
118: {"LXC: No IP assigned after timeout", "timeout"},
119: {"Proxmox: No valid storage for rootdir", "storage"},
120: {"Proxmox: No valid storage for vztmpl", "storage"},
121: {"LXC: Container network not ready", "network"},
122: {"LXC: No internet — user declined", "user_aborted"},
123: {"LXC: Local IP detection failed", "network"},
// --- Common shell/system errors ---
124: {"Command timed out", "timeout"},
125: {"Docker daemon error / command failed to start", "config"},
126: {"Command cannot execute (permission problem)", "permission"},
127: {"Command not found", "command_not_found"},
128: {"Invalid argument to exit", "signal"},
129: {"Killed by SIGHUP (terminal closed)", "user_aborted"},
130: {"Script terminated by Ctrl+C (SIGINT)", "user_aborted"},
131: {"Killed by SIGQUIT (core dump)", "signal"},
132: {"Killed by SIGILL (illegal instruction)", "signal"},
134: {"Process aborted (SIGABRT)", "signal"},
137: {"Process killed (SIGKILL) — likely OOM", "resource"},
139: {"Segmentation fault (SIGSEGV)", "unknown"},
141: {"Broken pipe (SIGPIPE)", "signal"},
143: {"Process terminated (SIGTERM)", "signal"},
144: {"Killed by signal 16 (SIGUSR1/SIGSTKFLT)", "signal"},
146: {"Killed by signal 18 (SIGTSTP)", "signal"},
// --- Systemd / Service errors (150-154) ---
150: {"Systemd: Service failed to start", "service"},
151: {"Systemd: Service unit not found", "service"},
152: {"Permission denied (EACCES)", "permission"},
153: {"Build/compile failed (make/gcc/cmake)", "build"},
154: {"Node.js: Native addon build failed (node-gyp)", "build"},
// --- Python / pip / uv (160-162) ---
160: {"Python: Virtualenv/uv environment missing or broken", "dependency"},
161: {"Python: Dependency resolution failed", "dependency"},
162: {"Python: Installation aborted (EXTERNALLY-MANAGED)", "dependency"},
// --- PostgreSQL (170-173) ---
170: {"PostgreSQL: Connection failed", "database"},
171: {"PostgreSQL: Authentication failed", "database"},
172: {"PostgreSQL: Database does not exist", "database"},
173: {"PostgreSQL: Fatal error in query", "database"},
// --- MySQL / MariaDB (180-183) ---
180: {"MySQL/MariaDB: Connection failed", "database"},
181: {"MySQL/MariaDB: Authentication failed", "database"},
182: {"MySQL/MariaDB: Database does not exist", "database"},
183: {"MySQL/MariaDB: Fatal error in query", "database"},
// --- MongoDB (190-193) ---
190: {"MongoDB: Connection failed", "database"},
191: {"MongoDB: Authentication failed", "database"},
192: {"MongoDB: Database not found", "database"},
193: {"MongoDB: Fatal query error", "database"},
// --- Proxmox Custom Codes (200-231) ---
200: {"Proxmox: Failed to create lock file", "proxmox"},
203: {"Proxmox: Missing CTID variable", "config"},
204: {"Proxmox: Missing PCT_OSTYPE variable", "config"},
205: {"Proxmox: Invalid CTID (<100)", "config"},
206: {"Proxmox: CTID already in use", "config"},
207: {"Proxmox: Password contains unescaped special chars", "config"},
208: {"Proxmox: Invalid configuration (DNS/MAC/Network)", "config"},
209: {"Proxmox: Container creation failed", "proxmox"},
210: {"Proxmox: Cluster not quorate", "proxmox"},
211: {"Proxmox: Timeout waiting for template lock", "timeout"},
212: {"Proxmox: Storage 'iscsidirect' does not support containers", "proxmox"},
213: {"Proxmox: Storage does not support 'rootdir' content", "proxmox"},
214: {"Proxmox: Not enough storage space", "storage"},
215: {"Proxmox: Container created but not listed (ghost state)", "proxmox"},
216: {"Proxmox: RootFS entry missing in config", "proxmox"},
217: {"Proxmox: Storage not accessible", "storage"},
218: {"Proxmox: Template file corrupted or incomplete", "proxmox"},
219: {"Proxmox: CephFS does not support containers", "storage"},
220: {"Proxmox: Unable to resolve template path", "proxmox"},
221: {"Proxmox: Template file not readable", "proxmox"},
222: {"Proxmox: Template download failed", "proxmox"},
223: {"Proxmox: Template not available after download", "proxmox"},
224: {"Proxmox: PBS storage is for backups only", "storage"},
225: {"Proxmox: No template available for OS/Version", "proxmox"},
226: {"Proxmox: VM disk import or post-creation setup failed", "proxmox"},
231: {"Proxmox: LXC stack upgrade failed", "proxmox"},
// --- Tools & Addon Scripts (232-238) ---
232: {"Tools: Wrong execution environment", "config"},
233: {"Tools: Application not installed (update prerequisite missing)", "config"},
234: {"Tools: No LXC containers found", "proxmox"},
235: {"Tools: Backup or restore operation failed", "storage"},
236: {"Tools: Required hardware not detected", "config"},
237: {"Tools: Dependency package installation failed", "dependency"},
238: {"Tools: OS or distribution not supported", "config"},
// --- Node.js / npm (239-249) ---
239: {"npm/Node.js: Unexpected runtime error", "dependency"},
243: {"Node.js: Out of memory (heap overflow)", "resource"},
245: {"Node.js: Invalid command-line option", "config"},
246: {"Node.js: Internal JavaScript Parse Error", "unknown"},
247: {"Node.js: Fatal internal error", "unknown"},
248: {"Node.js: Invalid C++ addon / N-API failure", "unknown"},
249: {"npm/pnpm/yarn: Unknown fatal error", "unknown"},
// --- Application Install/Update Errors (250-254) ---
250: {"App: Download failed or version not determined", "network"},
251: {"App: File extraction failed (corrupt/incomplete)", "storage"},
252: {"App: Required file or resource not found", "unknown"},
253: {"App: Data migration required — update aborted", "config"},
254: {"App: User declined prompt or input timed out", "user_aborted"},
// --- DPKG ---
255: {"DPKG: Fatal internal error / set -e triggered", "apt"},
}
)
// getExitCodeDescription returns the human-readable description for an exit code.
// Falls back to signal-based description for codes 128-191, or "Unknown" otherwise.
func getExitCodeDescription(code int) string {
if info, ok := exitCodeInfo[code]; ok {
return info.Desc
}
if code > 128 && code < 192 {
sigNum := code - 128
sigNames := map[int]string{
1: "SIGHUP", 2: "SIGINT", 3: "SIGQUIT", 6: "SIGABRT",
9: "SIGKILL", 11: "SIGSEGV", 13: "SIGPIPE", 15: "SIGTERM",
24: "SIGXCPU", 25: "SIGXFSZ",
}
if name, ok := sigNames[sigNum]; ok {
return fmt.Sprintf("Killed by %s (signal %d)", name, sigNum)
}
return fmt.Sprintf("Killed by signal %d", sigNum)
}
return fmt.Sprintf("Unknown (exit code %d)", code)
}
// getExitCodeCategory returns the error category for an exit code.
// Falls back to "signal" for codes 128-191, or "unknown" otherwise.
func getExitCodeCategory(code int) string {
if info, ok := exitCodeInfo[code]; ok {
return info.Category
}
if code > 128 && code < 192 {
return "signal"
}
return "unknown"
}
func containsAny(haystack string, needles ...string) bool {
for _, n := range needles {
if strings.Contains(haystack, n) {
return true
}
}
return false
}
// errDiagnosticHeader matches the header the engine puts in front of the real
// error text. It comes in two shapes, and both have to be handled:
//
// exit_code=1 | General error / Operation not permitted | at line 23: npm …
// exit_code=1 | General error / Operation not permitted\n---\nCreating filesyst…
//
// The second occurs whenever the ERR trap had no command to record, and it is
// common: five of eighteen exit-1 samples pulled from the live API. Requiring
// the third field would have left those still matching on the description.
var errDiagnosticHeader = regexp.MustCompile(`^exit_code=\d+\s*\|[^|\n]*(\|\s*)?`)
// stripDiagnosticHeader removes that header before any keyword matching below.
//
// The middle field is our own description of the exit code, not evidence about
// what happened, and matching keywords against it was actively wrong. Exit 1 is
// described as "General error / Operation not permitted", which contains
// "operation not permitted" -- so every exit-1 failure was filed as a permission
// problem. Over fourteen days that was 944 of 5165 errors, the largest single
// category on the dashboard, and none of them had anything to do with
// permissions; the record that surfaced it was a failing `npm install -g`.
func stripDiagnosticHeader(s string) string {
return errDiagnosticHeader.ReplaceAllString(s, "")
}
// deriveErrorCategory is the authoritative server-side error categorization.
// It first trusts the exit code (single source of truth via exitCodeInfo). For
// generic codes (1/2/exit-from-set-e) where the exit code says "unknown", it
// inspects the error text for well-known root causes so that exit_code=1 failures
// don't all collapse into the meaningless "unknown" bucket.
func deriveErrorCategory(code int, errText string) string {
if cat := getExitCodeCategory(code); cat != "unknown" && cat != "" {
return cat
}
e := strings.ToLower(stripDiagnosticHeader(errText))
switch {
case containsAny(e, "out of memory", "oom-kill", "cannot allocate memory", "killed process", "memory exhausted"):
return "resource"
case containsAny(e, "no space left", "disk full", "quota exceeded", "write error"):
return "storage"
case containsAny(e, "could not resolve", "connection refused", "connection timed out", "network is unreachable",
"temporary failure in name resolution", "failed to connect", "tls handshake", "ssl certificate", "curl:", "wget:"):
return "network"
case containsAny(e, "permission denied", "operation not permitted", "eacces", "must be run as root"):
return "permission"
case containsAny(e, "unable to locate package", "broken packages", "unmet dependencies", "dpkg was interrupted",
"held broken packages", "e: package", "apt-get", "dpkg:"):
return "apt"
// Compiling from source is its own failure mode and its own fix -- more
// memory, a toolchain version, a dependency the crate needs -- so it does
// not belong in "runtime" with things that failed while running. Checked
// after apt on purpose: a build that died because a -dev package was
// missing is an apt problem, and that evidence should win.
case containsAny(e, "cargo build", "error: could not compile", "rustc", "cargo:",
"go build", "cmake error", "make: ***", "ninja: build stopped", "c++: fatal error"):
return "build"
case containsAny(e, "command not found"):
return "command_not_found"
case containsAny(e, "timed out", "timeout"):
return "timeout"
case containsAny(e, "prisma", "migration.sql", "datasource", "sqlite database", "could not find the migration"):
return "database"
}
return "unknown"
}
// isAbortSignal reports whether a "failed" outcome is really a user-initiated
// abort (Ctrl+C / SIGINT, terminal close / SIGHUP, or an explicit user-cancel
// message) and should be reclassified as "aborted" rather than counted as a
// failure. Used both at ingest time and when reading records back, so the two
// paths can never diverge.
func isAbortSignal(exitCode int, errText string) bool {
if exitCode == 129 || exitCode == 130 {
return true
}
e := strings.ToLower(errText)
return containsAny(e, "sigint", "ctrl+c", "ctrl-c", "sighup",
"aborted by user", "user abort", "cancelled by user", "no changes have been made")
}
// parseRepoFilters reads repo_source (repo) and repo_slug (slug) query parameters.
func parseRepoFilters(r *http.Request) (repoSource, repoSlug string) {
// repo_source is OPTIONAL: no param (or "all") means all sources.
repoSource = r.URL.Query().Get("repo")
if repoSource == "all" {
repoSource = ""
}
repoSlug = strings.TrimSpace(r.URL.Query().Get("slug"))
return
}
// parsePlatform reads the optional platform filter ("pve" | "incus"), "" = all.
func parsePlatform(r *http.Request) string {
p := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("platform")))
if p == "pve" || p == "incus" {
return p
}
return ""
}
func telemetryCacheKey(prefix string, days int, repoSource, repoSlug string) string {
key := fmt.Sprintf("%s:%d:%s", prefix, days, repoSource)
if repoSlug != "" {
key += ":" + repoSlug