-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclickhouse.go
More file actions
1844 lines (1716 loc) · 64.4 KB
/
Copy pathclickhouse.go
File metadata and controls
1844 lines (1716 loc) · 64.4 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 (
"context"
"crypto/rand"
"database/sql"
"encoding/hex"
"encoding/json"
"fmt"
"log"
"strings"
"time"
_ "github.com/ClickHouse/clickhouse-go/v2"
)
// CHClient wraps a ClickHouse database/sql connection for telemetry reads and writes.
type CHClient struct {
db *sql.DB
}
// NewCHClient connects to ClickHouse using a DSN like
// "clickhouse://user:pass@host:9000/telemetry_db" or "http://user:pass@host:8123/telemetry_db".
// Automatically converts clickhouse:// to http:// with port 8123 for better compatibility.
// Retries with exponential backoff for up to ~60s to handle container startup ordering.
func NewCHClient(dsn string) (*CHClient, error) {
// Convert native protocol DSN to HTTP for better compatibility
if strings.HasPrefix(dsn, "clickhouse://") {
dsn = convertToHTTPDSN(dsn)
log.Printf("[CH] Converted DSN to HTTP protocol")
}
db, err := sql.Open("clickhouse", dsn)
if err != nil {
return nil, fmt.Errorf("clickhouse open: %w", err)
}
db.SetMaxOpenConns(20)
db.SetMaxIdleConns(10)
db.SetConnMaxLifetime(time.Hour)
// Retry ping with exponential backoff (containers may start before ClickHouse is ready)
backoff := []time.Duration{1, 2, 4, 8, 16, 30}
var pingErr error
for i, wait := range backoff {
if pingErr = db.PingContext(context.Background()); pingErr == nil {
break
}
log.Printf("[CH] ping attempt %d/%d failed: %v (retry in %ds)", i+1, len(backoff), pingErr, wait)
time.Sleep(wait * time.Second)
}
if pingErr != nil {
db.Close()
return nil, fmt.Errorf("clickhouse ping (after %d retries): %w", len(backoff), pingErr)
}
log.Println("[CH] Connected to ClickHouse")
ch := &CHClient{db: db}
ch.migrate()
return ch, nil
}
// convertToHTTPDSN converts a clickhouse:// native protocol DSN to http:// protocol DSN
// Example: "clickhouse://admin:pass@10.0.1.11:9000/db" → "http://admin:pass@10.0.1.11:8123/db"
func convertToHTTPDSN(dsn string) string {
// Replace clickhouse:// with http://
dsn = strings.Replace(dsn, "clickhouse://", "http://", 1)
// Replace :9000 with :8123 (native protocol port to HTTP port)
// Be careful to only replace the port after the host, not in any other field
dsn = strings.Replace(dsn, ":9000/", ":8123/", 1)
return dsn
}
// migrate creates the database, tables, and materialized views if they don't exist.
func (ch *CHClient) migrate() {
ctx := context.Background()
stmts := []string{
`CREATE DATABASE IF NOT EXISTS telemetry_db`,
// ── Main telemetry table ──
`CREATE TABLE IF NOT EXISTS telemetry_db.telemetry (
id String,
nsapp String,
type String,
status String,
method String,
created DateTime64(3),
core_count UInt8,
ct_type UInt8,
disk_size UInt32,
ram_size UInt32,
exit_code Int16,
error String,
error_category String,
os_type String,
os_version String,
pve_version String,
random_id String,
execution_id String,
repo_source String,
repo_slug String,
cpu_vendor String,
cpu_model String,
gpu_vendor String,
gpu_model String,
gpu_passthrough String,
ram_speed String,
install_duration UInt32,
has_arm UInt8
) ENGINE = MergeTree()
ORDER BY (created, nsapp)
PARTITION BY toYYYYMM(created)`,
// ── Materialized view: daily stats per app ──
// Pre-aggregates counts per (date, nsapp, type, status, repo_source).
// Queries GROUP BY date/app become instant.
`CREATE TABLE IF NOT EXISTS telemetry_db.mv_daily_stats (
day Date,
nsapp String,
type String,
repo_source String,
total UInt64,
success UInt64,
failed UInt64,
aborted UInt64,
installing UInt64
) ENGINE = SummingMergeTree()
ORDER BY (day, nsapp, type, repo_source)
PARTITION BY toYYYYMM(day)`,
`CREATE MATERIALIZED VIEW IF NOT EXISTS telemetry_db.mv_daily_stats_view
TO telemetry_db.mv_daily_stats AS
SELECT
toDate(created) AS day,
nsapp,
type,
repo_source,
count() AS total,
countIf(status='success') AS success,
countIf(status='failed') AS failed,
countIf(status='aborted') AS aborted,
countIf(status IN ('installing','validation','configuring')) AS installing
FROM telemetry_db.telemetry
GROUP BY day, nsapp, type, repo_source`,
// ── Materialized view: daily OS distribution ──
`CREATE TABLE IF NOT EXISTS telemetry_db.mv_daily_os (
day Date,
repo_source String,
os_type String,
cnt UInt64
) ENGINE = SummingMergeTree()
ORDER BY (day, repo_source, os_type)
PARTITION BY toYYYYMM(day)`,
`CREATE MATERIALIZED VIEW IF NOT EXISTS telemetry_db.mv_daily_os_view
TO telemetry_db.mv_daily_os AS
SELECT
toDate(created) AS day,
repo_source,
os_type,
count() AS cnt
FROM telemetry_db.telemetry
WHERE os_type != '' AND status IN ('success','failed','aborted','unknown')
GROUP BY day, repo_source, os_type`,
// ── Materialized view: daily method distribution ──
`CREATE TABLE IF NOT EXISTS telemetry_db.mv_daily_method (
day Date,
repo_source String,
method String,
cnt UInt64
) ENGINE = SummingMergeTree()
ORDER BY (day, repo_source, method)
PARTITION BY toYYYYMM(day)`,
`CREATE MATERIALIZED VIEW IF NOT EXISTS telemetry_db.mv_daily_method_view
TO telemetry_db.mv_daily_method AS
SELECT
toDate(created) AS day,
repo_source,
method,
count() AS cnt
FROM telemetry_db.telemetry
WHERE method != '' AND status IN ('success','failed','aborted','unknown')
GROUP BY day, repo_source, method`,
// ── Materialized view: daily PVE version distribution ──
`CREATE TABLE IF NOT EXISTS telemetry_db.mv_daily_pve (
day Date,
repo_source String,
pve_version String,
cnt UInt64
) ENGINE = SummingMergeTree()
ORDER BY (day, repo_source, pve_version)
PARTITION BY toYYYYMM(day)`,
`CREATE MATERIALIZED VIEW IF NOT EXISTS telemetry_db.mv_daily_pve_view
TO telemetry_db.mv_daily_pve AS
SELECT
toDate(created) AS day,
repo_source,
pve_version,
count() AS cnt
FROM telemetry_db.telemetry
WHERE pve_version != '' AND status IN ('success','failed','aborted','unknown')
GROUP BY day, repo_source, pve_version`,
// ── Materialized view: daily errors (excludes user_aborted) ──
// Pre-aggregates real failures per (date, app, exit_code, error_category).
// user_aborted (SIGHUP/SIGINT from closed terminals) is noise, not errors.
`CREATE TABLE IF NOT EXISTS telemetry_db.mv_daily_errors (
day Date,
nsapp String,
type String,
exit_code Int16,
error_category String,
repo_source String,
cnt UInt64
) ENGINE = SummingMergeTree()
ORDER BY (day, nsapp, exit_code, error_category, repo_source)
PARTITION BY toYYYYMM(day)`,
`CREATE MATERIALIZED VIEW IF NOT EXISTS telemetry_db.mv_daily_errors_view
TO telemetry_db.mv_daily_errors AS
SELECT
toDate(created) AS day,
nsapp,
type,
exit_code,
error_category,
repo_source,
count() AS cnt
FROM telemetry_db.telemetry
WHERE status = 'failed'
AND error_category != 'user_aborted'
AND exit_code != 0
GROUP BY day, nsapp, type, exit_code, error_category, repo_source`,
}
for _, s := range stmts {
if _, err := ch.db.ExecContext(ctx, s); err != nil {
log.Printf("[CH-MIGRATE] %v", err)
}
}
// Additive column migrations for tables that predate the column (idempotent).
alters := []string{
`ALTER TABLE telemetry_db.telemetry ADD COLUMN IF NOT EXISTS repo_slug String`,
`ALTER TABLE telemetry_db.telemetry ADD COLUMN IF NOT EXISTS has_arm UInt8`,
// Virtualization platform: 'pve' (Proxmox VE) or 'incus'. Old rows have ''
// and are derived at query time from pve_version (see platformExpr).
`ALTER TABLE telemetry_db.telemetry ADD COLUMN IF NOT EXISTS platform LowCardinality(String)`,
}
for _, s := range alters {
if _, err := ch.db.ExecContext(ctx, s); err != nil {
log.Printf("[CH-MIGRATE] alter: %v", err)
}
}
// Backfill materialized views from existing data if they're empty
var mvCount uint64
_ = ch.db.QueryRowContext(ctx, "SELECT count() FROM telemetry_db.mv_daily_stats").Scan(&mvCount)
if mvCount == 0 {
var srcCount uint64
_ = ch.db.QueryRowContext(ctx, "SELECT count() FROM telemetry_db.telemetry").Scan(&srcCount)
if srcCount > 0 {
log.Printf("[CH-MIGRATE] Backfilling materialized views from %d existing rows...", srcCount)
backfills := []string{
`INSERT INTO telemetry_db.mv_daily_stats
SELECT toDate(created), nsapp, type, repo_source,
count(), countIf(status='success'), countIf(status='failed'),
countIf(status='aborted'),
countIf(status IN ('installing','validation','configuring'))
FROM telemetry_db.telemetry GROUP BY toDate(created), nsapp, type, repo_source`,
`INSERT INTO telemetry_db.mv_daily_os
SELECT toDate(created), repo_source, os_type, count()
FROM telemetry_db.telemetry
WHERE os_type != '' AND status IN ('success','failed','aborted','unknown')
GROUP BY toDate(created), repo_source, os_type`,
`INSERT INTO telemetry_db.mv_daily_method
SELECT toDate(created), repo_source, method, count()
FROM telemetry_db.telemetry
WHERE method != '' AND status IN ('success','failed','aborted','unknown')
GROUP BY toDate(created), repo_source, method`,
`INSERT INTO telemetry_db.mv_daily_pve
SELECT toDate(created), repo_source, pve_version, count()
FROM telemetry_db.telemetry
WHERE pve_version != '' AND status IN ('success','failed','aborted','unknown')
GROUP BY toDate(created), repo_source, pve_version`,
}
for _, q := range backfills {
if _, err := ch.db.ExecContext(ctx, q); err != nil {
log.Printf("[CH-MIGRATE] backfill error: %v", err)
}
}
log.Println("[CH-MIGRATE] Backfill complete")
}
}
// Backfill mv_daily_errors separately (may be added after initial deploy)
var errMVCount uint64
_ = ch.db.QueryRowContext(ctx, "SELECT count() FROM telemetry_db.mv_daily_errors").Scan(&errMVCount)
if errMVCount == 0 {
var srcCount uint64
_ = ch.db.QueryRowContext(ctx, "SELECT count() FROM telemetry_db.telemetry WHERE status='failed' AND error_category!='user_aborted' AND exit_code!=0").Scan(&srcCount)
if srcCount > 0 {
log.Printf("[CH-MIGRATE] Backfilling mv_daily_errors from %d error rows...", srcCount)
_, err := ch.db.ExecContext(ctx, `INSERT INTO telemetry_db.mv_daily_errors
SELECT toDate(created), nsapp, type, exit_code, error_category, repo_source, count()
FROM telemetry_db.telemetry
WHERE status = 'failed' AND error_category != 'user_aborted' AND exit_code != 0
GROUP BY toDate(created), nsapp, type, exit_code, error_category, repo_source`)
if err != nil {
log.Printf("[CH-MIGRATE] mv_daily_errors backfill error: %v", err)
} else {
log.Println("[CH-MIGRATE] mv_daily_errors backfill complete")
}
}
}
log.Println("[CH-MIGRATE] Schema ready")
}
func (ch *CHClient) Close() error { return ch.db.Close() }
func (ch *CHClient) Ping(ctx context.Context) error { return ch.db.PingContext(ctx) }
func generateRecordID() string {
b := make([]byte, 15)
_, _ = rand.Read(b)
return hex.EncodeToString(b)
}
// ══════════════════════════════════════════════════════════════
// WRITE OPERATIONS
// ══════════════════════════════════════════════════════════════
func (ch *CHClient) InsertTelemetry(ctx context.Context, p TelemetryOut) error {
const q = `INSERT INTO telemetry_db.telemetry (
id, nsapp, type, status, method, created,
core_count, ct_type, disk_size, ram_size,
exit_code, error, error_category,
os_type, os_version, pve_version,
random_id, execution_id, repo_source, repo_slug,
cpu_vendor, cpu_model,
gpu_vendor, gpu_model, gpu_passthrough,
ram_speed, install_duration, has_arm, platform
) VALUES (
?, ?, ?, ?, ?, now64(3),
?, ?, ?, ?,
?, ?, ?,
?, ?, ?,
?, ?, ?, ?,
?, ?,
?, ?, ?,
?, ?, ?, ?
)`
_, err := ch.db.ExecContext(ctx, q,
generateRecordID(), p.NSAPP, p.Type, p.Status, p.Method,
uint8(p.CoreCount), uint8(p.CTType), uint32(p.DiskSize), uint32(p.RAMSize),
int16(p.ExitCode), p.Error, p.ErrorCategory,
p.OsType, p.OsVersion, p.PveVer,
p.RandomID, p.ExecutionID, p.RepoSource, p.RepoSlug,
p.CPUVendor, p.CPUModel,
p.GPUVendor, p.GPUModel, p.GPUPassthrough,
p.RAMSpeed, uint32(p.InstallDuration), boolToUint8(p.HasArm), p.Platform,
)
return err
}
// boolToUint8 maps a Go bool to ClickHouse's UInt8 (0/1) representation.
func boolToUint8(b bool) uint8 {
if b {
return 1
}
return 0
}
// HasTerminalExecutionID reports whether a terminal-status row already exists for
// the given execution_id. Used by the write queue to deduplicate the multiple
// failure reports a single bash execution can emit.
func (ch *CHClient) HasTerminalExecutionID(ctx context.Context, eid string) (bool, error) {
if eid == "" {
return false, nil
}
var cnt uint64
err := ch.db.QueryRowContext(ctx,
"SELECT count() FROM telemetry_db.telemetry WHERE execution_id = ? AND status IN ('success','failed','aborted','unknown')", eid,
).Scan(&cnt)
return cnt > 0, err
}
func (ch *CHClient) HasExecutionID(ctx context.Context, eid string) (bool, error) {
var cnt uint64
err := ch.db.QueryRowContext(ctx,
"SELECT count() FROM telemetry_db.telemetry WHERE execution_id = ?", eid,
).Scan(&cnt)
return cnt > 0, err
}
// ══════════════════════════════════════════════════════════════
// QUERY HELPERS
// ══════════════════════════════════════════════════════════════
func chSinceTime(days int) time.Time {
if days == 1 {
return time.Now().UTC().Truncate(24 * time.Hour)
}
return time.Now().UTC().AddDate(0, 0, -(days - 1)).Truncate(24 * time.Hour)
}
// repoSourcePred returns a SQL predicate (and args) for a repo_source filter.
//
// Legacy rows created before repo_source existed have an empty repo_source.
// Since the production client's fallback is "ProxmoxVE" (CI rewrites
// ProxmoxVED→ProxmoxVE on promotion), those untagged historical installs are
// overwhelmingly production traffic. The "ProxmoxVE" filter therefore also
// includes empty repo_source so the count reflects real production volume
// instead of dropping ~70% of historical records into an invisible bucket.
//
// An empty repoSource means "all" (no predicate). Other values match exactly.
func repoSourcePred(repoSource string) (string, []interface{}) {
switch repoSource {
case "":
return "", nil
case "ProxmoxVE":
return "repo_source IN ('ProxmoxVE','')", nil
default:
return "repo_source = ?", []interface{}{repoSource}
}
}
// platformExpr derives the virtualization platform for every row, including
// legacy rows written before the platform column existed:
// - explicit platform column wins
// - pve_version starting with "incus" (client sends "incus-x.y") → incus
// - any other non-empty pve_version → pve
// - otherwise unknown ('')
const platformExpr = `multiIf(platform != '', platform, pve_version LIKE 'incus%', 'incus', pve_version != '', 'pve', '')`
// platformPred returns a SQL predicate for a platform filter ("" = no filter).
// Values are allowlisted by the HTTP layer, so inlining is safe.
func platformPred(platform string) string {
switch platform {
case "pve", "incus":
return platformExpr + " = '" + platform + "'"
}
return ""
}
// chWhere builds a WHERE clause from days, repoSource, optional repoSlug,
// optional platform, and extra predicates.
// Always starts with "1=1" so callers can freely AND-chain.
func chWhere(days int, repoSource, repoSlug, platform string, extras ...string) (string, []interface{}) {
parts := []string{"1=1"}
var args []interface{}
if days > 0 {
parts = append(parts, "created >= ?")
args = append(args, chSinceTime(days))
}
if pred, pArgs := repoSourcePred(repoSource); pred != "" {
parts = append(parts, pred)
args = append(args, pArgs...)
}
if repoSlug != "" {
parts = append(parts, "repo_slug = ?")
args = append(args, repoSlug)
}
if pred := platformPred(platform); pred != "" {
parts = append(parts, pred)
}
for _, e := range extras {
parts = append(parts, e)
}
return strings.Join(parts, " AND "), args
}
// chSinceDate returns the date for filtering materialized views (Date column, not DateTime64).
func chSinceDate(days int) string {
if days == 1 {
return time.Now().UTC().Truncate(24 * time.Hour).Format("2006-01-02")
}
return time.Now().UTC().AddDate(0, 0, -(days - 1)).Truncate(24 * time.Hour).Format("2006-01-02")
}
// chMVWhere builds a WHERE clause for materialized view tables (uses "day" Date column).
func chMVWhere(days int, repoSource string) (string, []interface{}) {
parts := []string{"1=1"}
var args []interface{}
if days > 0 {
parts = append(parts, "day >= ?")
args = append(args, chSinceDate(days))
}
if pred, pArgs := repoSourcePred(repoSource); pred != "" {
parts = append(parts, pred)
args = append(args, pArgs...)
}
return strings.Join(parts, " AND "), args
}
// scanRecords reads TelemetryRecord rows from a *sql.Rows.
func scanRecords(rows *sql.Rows) []TelemetryRecord {
var out []TelemetryRecord
for rows.Next() {
var r TelemetryRecord
var coreCount, ctType, hasArm uint8
var diskSize, ramSize, installDur uint32
var exitCode int16
err := rows.Scan(
&r.NSAPP, &r.Type, &r.Status, &r.Method,
&coreCount, &ctType, &diskSize, &ramSize,
&exitCode, &r.Error, &r.ErrorCategory,
&r.OsType, &r.OsVersion, &r.PveVer,
&r.RandomID, &r.ExecutionID, &r.RepoSource, &r.RepoSlug,
&r.CPUVendor, &r.CPUModel,
&r.GPUVendor, &r.GPUModel, &r.GPUPassthrough,
&r.RAMSpeed, &installDur, &hasArm,
&r.Platform,
&r.Created,
)
if err != nil {
log.Printf("[CH] row scan: %v", err)
continue
}
r.CoreCount = int(coreCount)
r.CTType = int(ctType)
r.DiskSize = int(diskSize)
r.RAMSize = int(ramSize)
r.ExitCode = int(exitCode)
r.InstallDuration = int(installDur)
r.HasArm = hasArm != 0
out = append(out, r)
}
return out
}
// recordSelectCols is the column list shared by all queries that return TelemetryRecord.
const recordSelectCols = `nsapp, type, status, method,
core_count, ct_type, disk_size, ram_size,
exit_code, error, error_category,
os_type, os_version, pve_version,
random_id, execution_id, repo_source, repo_slug,
cpu_vendor, cpu_model,
gpu_vendor, gpu_model, gpu_passthrough,
ram_speed, install_duration, has_arm,
` + platformExpr + ` AS platform_resolved,
toString(created)`
// ══════════════════════════════════════════════════════════════
// DASHBOARD DATA (SQL aggregation — replaces PB pagination)
// ══════════════════════════════════════════════════════════════
// FetchRepoSlugs returns distinct owner/repo slugs with install counts for the filter dropdown.
func (ch *CHClient) FetchRepoSlugs(ctx context.Context, days int, repoSource string) ([]RepoSlugCount, error) {
w, a := chWhere(days, repoSource, "", "", "repo_slug != ''")
rows, err := ch.db.QueryContext(ctx, fmt.Sprintf(
"SELECT repo_slug, count() c FROM telemetry_db.telemetry WHERE %s GROUP BY repo_slug ORDER BY c DESC LIMIT 50", w), a...)
if err != nil {
return nil, fmt.Errorf("CH repo slugs: %w", err)
}
defer rows.Close()
var out []RepoSlugCount
for rows.Next() {
var rs RepoSlugCount
var c uint64
if rows.Scan(&rs.Slug, &c) == nil {
rs.Count = int(c)
out = append(out, rs)
}
}
return out, nil
}
func (ch *CHClient) FetchDashboardData(ctx context.Context, days int, repoSource, repoSlug, platform string) (*DashboardData, error) {
data := &DashboardData{}
mw, ma := chMVWhere(days, repoSource)
tw, ta := chWhere(days, repoSource, repoSlug, platform, "status IN ('success','failed','aborted','unknown')")
// Materialized views have no platform column — platform filters need raw-table aggregation.
rawAgg := repoSlug != "" || platform != ""
// ── 1. Main counts ──
// "Total" counts DISTINCT installations (one per execution), not raw event
// rows. Every progress ping (validation/configuring) is its own ClickHouse
// row, so a plain count() inflated the number ~5x vs success+failed+aborted
// (e.g. "10,455 created" while only ~1,900 installs actually finished).
var total, sc, fc, ac uint64
var err error
rw, ra := chWhere(days, repoSource, repoSlug, platform)
err = ch.db.QueryRowContext(ctx, fmt.Sprintf(`
SELECT
uniqExact(if(execution_id = '', random_id, execution_id)),
countIf(status='success'), countIf(status='failed'), countIf(status='aborted')
FROM telemetry_db.telemetry WHERE %s`, rw), ra...,
).Scan(&total, &sc, &fc, &ac)
if err != nil {
return nil, fmt.Errorf("CH dashboard counts: %w", err)
}
data.TotalInstalls = int(total)
data.SuccessCount = int(sc)
data.FailedCount = int(fc)
data.AbortedCount = int(ac)
if sc+fc > 0 {
data.SuccessRate = float64(sc) / float64(sc+fc) * 100
}
// Avg install duration (needs raw table — only non-zero durations)
var avgDur float64
_ = ch.db.QueryRowContext(ctx, fmt.Sprintf(`
SELECT if(countIf(install_duration>0)>0,
toFloat64(sumIf(install_duration, install_duration>0))/countIf(install_duration>0), 0)
FROM telemetry_db.telemetry WHERE %s`, tw), ta...,
).Scan(&avgDur)
data.AvgInstallDuration = avgDur
// Total all-time: distinct installations across the whole table.
// uniq() is approximate (<1% error) but fast enough for a headline number.
var tat uint64
_ = ch.db.QueryRowContext(ctx,
"SELECT uniq(if(execution_id = '', random_id, execution_id)) FROM telemetry_db.telemetry",
).Scan(&tat)
data.TotalAllTime = int(tat)
data.SampleSize = data.TotalInstalls
// ── 2. Installing count (raw table — execution_id subquery) ──
stuckW, stuckA := chWhere(1, repoSource, repoSlug, platform,
"status IN ('installing','validation','configuring')",
`(execution_id = '' OR execution_id NOT IN (
SELECT execution_id FROM telemetry_db.telemetry
WHERE status IN ('success','failed','aborted','unknown') AND execution_id != ''))`)
var ic uint64
_ = ch.db.QueryRowContext(ctx, fmt.Sprintf(
"SELECT count() FROM telemetry_db.telemetry WHERE %s", stuckW), stuckA...,
).Scan(&ic)
data.InstallingCount = int(ic)
// ── 3. Top apps ──
if rawAgg {
if rows, err := ch.db.QueryContext(ctx, fmt.Sprintf(
"SELECT nsapp, count() c FROM telemetry_db.telemetry WHERE %s AND nsapp!='' GROUP BY nsapp ORDER BY c DESC LIMIT 20", rw), ra...); err == nil {
defer rows.Close()
for rows.Next() {
var a AppCount
var c uint64
if rows.Scan(&a.App, &c) == nil {
a.Count = int(c)
data.TopApps = append(data.TopApps, a)
}
}
}
} else if rows, err := ch.db.QueryContext(ctx, fmt.Sprintf(
"SELECT nsapp, sum(total) c FROM telemetry_db.mv_daily_stats WHERE %s AND nsapp!='' GROUP BY nsapp ORDER BY c DESC LIMIT 20", mw), ma...); err == nil {
defer rows.Close()
for rows.Next() {
var a AppCount
var c uint64
if rows.Scan(&a.App, &c) == nil {
a.Count = int(c)
data.TopApps = append(data.TopApps, a)
}
}
}
// ── 4. OS distribution ──
if rawAgg {
osW, osA := chWhere(days, repoSource, repoSlug, platform, "os_type != ''", "status IN ('success','failed','aborted','unknown')")
if rows, err := ch.db.QueryContext(ctx, fmt.Sprintf(
"SELECT os_type, count() c FROM telemetry_db.telemetry WHERE %s GROUP BY os_type ORDER BY c DESC LIMIT 15", osW), osA...); err == nil {
defer rows.Close()
for rows.Next() {
var o OsCount
var c uint64
if rows.Scan(&o.Os, &c) == nil {
o.Count = int(c)
data.OsDistribution = append(data.OsDistribution, o)
}
}
}
} else if rows, err := ch.db.QueryContext(ctx, fmt.Sprintf(
"SELECT os_type, sum(cnt) c FROM telemetry_db.mv_daily_os WHERE %s AND os_type!='' GROUP BY os_type ORDER BY c DESC LIMIT 15", mw), ma...); err == nil {
defer rows.Close()
for rows.Next() {
var o OsCount
var c uint64
if rows.Scan(&o.Os, &c) == nil {
o.Count = int(c)
data.OsDistribution = append(data.OsDistribution, o)
}
}
}
// ── 5. Method stats ──
if rawAgg {
methW, methA := chWhere(days, repoSource, repoSlug, platform, "method != ''", "status IN ('success','failed','aborted','unknown')")
if rows, err := ch.db.QueryContext(ctx, fmt.Sprintf(
"SELECT method, count() c FROM telemetry_db.telemetry WHERE %s GROUP BY method ORDER BY c DESC LIMIT 10", methW), methA...); err == nil {
defer rows.Close()
for rows.Next() {
var m MethodCount
var c uint64
if rows.Scan(&m.Method, &c) == nil {
m.Count = int(c)
data.MethodStats = append(data.MethodStats, m)
}
}
}
} else if rows, err := ch.db.QueryContext(ctx, fmt.Sprintf(
"SELECT method, sum(cnt) c FROM telemetry_db.mv_daily_method WHERE %s AND method!='' GROUP BY method ORDER BY c DESC LIMIT 10", mw), ma...); err == nil {
defer rows.Close()
for rows.Next() {
var m MethodCount
var c uint64
if rows.Scan(&m.Method, &c) == nil {
m.Count = int(c)
data.MethodStats = append(data.MethodStats, m)
}
}
}
// ── 6. PVE versions ──
if rawAgg {
pveW, pveA := chWhere(days, repoSource, repoSlug, platform, "pve_version != ''", "status IN ('success','failed','aborted','unknown')")
if rows, err := ch.db.QueryContext(ctx, fmt.Sprintf(
"SELECT pve_version, count() c FROM telemetry_db.telemetry WHERE %s GROUP BY pve_version ORDER BY c DESC LIMIT 15", pveW), pveA...); err == nil {
defer rows.Close()
for rows.Next() {
var p PveCount
var c uint64
if rows.Scan(&p.Version, &c) == nil {
p.Count = int(c)
data.PveVersions = append(data.PveVersions, p)
}
}
}
} else if rows, err := ch.db.QueryContext(ctx, fmt.Sprintf(
"SELECT pve_version, sum(cnt) c FROM telemetry_db.mv_daily_pve WHERE %s AND pve_version!='' GROUP BY pve_version ORDER BY c DESC LIMIT 15", mw), ma...); err == nil {
defer rows.Close()
for rows.Next() {
var p PveCount
var c uint64
if rows.Scan(&p.Version, &c) == nil {
p.Count = int(c)
data.PveVersions = append(data.PveVersions, p)
}
}
}
// ── 7. Type stats ──
if rawAgg {
if rows, err := ch.db.QueryContext(ctx, fmt.Sprintf(
"SELECT type, count() c FROM telemetry_db.telemetry WHERE %s AND type!='' GROUP BY type ORDER BY c DESC LIMIT 10", rw), ra...); err == nil {
defer rows.Close()
for rows.Next() {
var t TypeCount
var c uint64
if rows.Scan(&t.Type, &c) == nil {
t.Count = int(c)
data.TypeStats = append(data.TypeStats, t)
}
}
}
} else if rows, err := ch.db.QueryContext(ctx, fmt.Sprintf(
"SELECT type, sum(total) c FROM telemetry_db.mv_daily_stats WHERE %s AND type!='' GROUP BY type ORDER BY c DESC LIMIT 10", mw), ma...); err == nil {
defer rows.Close()
for rows.Next() {
var t TypeCount
var c uint64
if rows.Scan(&t.Type, &c) == nil {
t.Count = int(c)
data.TypeStats = append(data.TypeStats, t)
}
}
}
// ── 8. Error analysis (needs raw table — text pattern matching, excludes user_aborted) ──
fwErr, faErr := chWhere(days, repoSource, repoSlug, platform, "status='failed'", "error!=''", "error_category!='user_aborted'")
if rows, err := ch.db.QueryContext(ctx, fmt.Sprintf(`
SELECT
multiIf(
positionCaseInsensitive(error,'connection refused')>0,'connection refused',
positionCaseInsensitive(error,'timeout')>0,'timeout',
positionCaseInsensitive(error,'no space left')>0,'disk full',
positionCaseInsensitive(error,'permission denied')>0,'permission denied',
positionCaseInsensitive(error,'not found')>0,'not found',
positionCaseInsensitive(error,'apt')>0,'apt error',
positionCaseInsensitive(error,'dpkg')>0,'dpkg error',
positionCaseInsensitive(error,'curl')>0,'network error',
positionCaseInsensitive(error,'wget')>0,'network error',
positionCaseInsensitive(error,'docker')>0,'docker error',
positionCaseInsensitive(error,'systemctl')>0,'systemd error',
substring(lower(error),1,40)
) as pat,
count() as cnt,
uniqExact(nsapp) as ua,
arrayStringConcat(arraySlice(groupUniqArray(nsapp),1,5),', ') as apps
FROM telemetry_db.telemetry
WHERE %s GROUP BY pat ORDER BY cnt DESC LIMIT 15`, fwErr), faErr...); err == nil {
defer rows.Close()
for rows.Next() {
var eg ErrorGroup
var cnt, ua uint64
if rows.Scan(&eg.Pattern, &cnt, &ua, &eg.Apps) == nil {
eg.Count = int(cnt)
eg.UniqueApps = int(ua)
data.ErrorAnalysis = append(data.ErrorAnalysis, eg)
}
}
}
// ── 9. Failed apps with failure rates ──
minInstalls := 10
switch {
case days <= 1:
minInstalls = 5
case days <= 7:
minInstalls = 15
case days <= 30:
minInstalls = 40
default:
minInstalls = 100
}
if rawAgg {
if rows, err := ch.db.QueryContext(ctx, fmt.Sprintf(`
SELECT nsapp, anyLast(type), count() t, countIf(status='failed') f
FROM telemetry_db.telemetry
WHERE %s AND nsapp!=''
GROUP BY nsapp
HAVING f > 0 AND t >= %d
ORDER BY toFloat64(f)/t DESC LIMIT 50`, rw, minInstalls), ra...); err == nil {
defer rows.Close()
appTotal := make(map[string]int)
appFailed := make(map[string]int)
for rows.Next() {
var nsapp, typ string
var t, f uint64
if rows.Scan(&nsapp, &typ, &t, &f) == nil {
key := nsapp + "|" + typ
appTotal[key] = int(t)
appFailed[key] = int(f)
}
}
data.FailedApps = buildFailedApps(appTotal, appFailed, 16, minInstalls)
}
} else if rows, err := ch.db.QueryContext(ctx, fmt.Sprintf(`
SELECT nsapp, anyLast(type), sum(total) t, sum(failed) f
FROM telemetry_db.mv_daily_stats
WHERE %s AND nsapp!=''
GROUP BY nsapp
HAVING f > 0 AND t >= %d
ORDER BY toFloat64(f)/t DESC LIMIT 50`, mw, minInstalls), ma...); err == nil {
defer rows.Close()
appTotal := make(map[string]int)
appFailed := make(map[string]int)
for rows.Next() {
var nsapp, typ string
var t, f uint64
if rows.Scan(&nsapp, &typ, &t, &f) == nil {
key := nsapp + "|" + typ
appTotal[key] = int(t)
appFailed[key] = int(f)
}
}
data.FailedApps = buildFailedApps(appTotal, appFailed, 16, minInstalls)
}
// ── 10. Daily stats ──
if rawAgg {
if rows, err := ch.db.QueryContext(ctx, fmt.Sprintf(`
SELECT toString(toDate(created)) d, countIf(status='success') s, countIf(status='failed') f
FROM telemetry_db.telemetry WHERE %s
GROUP BY toDate(created) ORDER BY toDate(created)`, rw), ra...); err == nil {
defer rows.Close()
sMap := make(map[string]int)
fMap := make(map[string]int)
for rows.Next() {
var d string
var s, f uint64
if rows.Scan(&d, &s, &f) == nil {
sMap[d] = int(s)
fMap[d] = int(f)
}
}
actualDays := days
if actualDays <= 0 {
actualDays = 365
}
data.DailyStats = buildDailyStats(sMap, fMap, actualDays)
}
} else if rows, err := ch.db.QueryContext(ctx, fmt.Sprintf(`
SELECT toString(day) d, sum(success) s, sum(failed) f
FROM telemetry_db.mv_daily_stats WHERE %s
GROUP BY day ORDER BY day`, mw), ma...); err == nil {
defer rows.Close()
sMap := make(map[string]int)
fMap := make(map[string]int)
for rows.Next() {
var d string
var s, f uint64
if rows.Scan(&d, &s, &f) == nil {
sMap[d] = int(s)
fMap[d] = int(f)
}
}
actualDays := days
if actualDays <= 0 {
actualDays = 365
}
data.DailyStats = buildDailyStats(sMap, fMap, actualDays)
}
// ── 11. GPU stats (raw table — not materialized, low volume) ──
gpuW, gpuA := chWhere(days, repoSource, repoSlug, platform, "status IN ('success','failed','aborted','unknown')", "gpu_vendor!=''", "gpu_vendor!='unknown'")
if rows, err := ch.db.QueryContext(ctx, fmt.Sprintf(
"SELECT gpu_vendor, gpu_passthrough, count() c FROM telemetry_db.telemetry WHERE %s GROUP BY gpu_vendor, gpu_passthrough ORDER BY c DESC", gpuW), gpuA...); err == nil {
defer rows.Close()
for rows.Next() {
var g GPUCount
var c uint64
if rows.Scan(&g.Vendor, &g.Passthrough, &c) == nil {
g.Count = int(c)
data.GPUStats = append(data.GPUStats, g)
}
}
}
// ── 12. Error categories (raw table — excludes user_aborted) ──
catW, catA := chWhere(days, repoSource, repoSlug, platform, "status='failed'", "error_category NOT IN ('','user_aborted')")
if rows, err := ch.db.QueryContext(ctx, fmt.Sprintf(
"SELECT error_category, count() c FROM telemetry_db.telemetry WHERE %s GROUP BY error_category ORDER BY c DESC", catW), catA...); err == nil {
defer rows.Close()
for rows.Next() {
var e ErrorCatCount
var c uint64
if rows.Scan(&e.Category, &c) == nil {
e.Count = int(c)
data.ErrorCategories = append(data.ErrorCategories, e)
}
}
}
// ── 13. Top tools ──
if rawAgg {
if rows, err := ch.db.QueryContext(ctx, fmt.Sprintf(
"SELECT nsapp, count() c FROM telemetry_db.telemetry WHERE %s AND type='pve' AND nsapp!='' GROUP BY nsapp ORDER BY c DESC LIMIT 15", rw), ra...); err == nil {
defer rows.Close()
for rows.Next() {
var t ToolCount
var c uint64
if rows.Scan(&t.Tool, &c) == nil {
t.Count = int(c)
data.TopTools = append(data.TopTools, t)
data.TotalTools += int(c)
}
}
}
} else if rows, err := ch.db.QueryContext(ctx, fmt.Sprintf(
"SELECT nsapp, sum(total) c FROM telemetry_db.mv_daily_stats WHERE %s AND type='pve' AND nsapp!='' GROUP BY nsapp ORDER BY c DESC LIMIT 15", mw), ma...); err == nil {
defer rows.Close()
for rows.Next() {
var t ToolCount
var c uint64
if rows.Scan(&t.Tool, &c) == nil {
t.Count = int(c)
data.TopTools = append(data.TopTools, t)
data.TotalTools += int(c)
}
}
}
// ── 14. Top addons ──
if rawAgg {
if rows, err := ch.db.QueryContext(ctx, fmt.Sprintf(
"SELECT nsapp, count() c FROM telemetry_db.telemetry WHERE %s AND type='addon' AND nsapp!='' GROUP BY nsapp ORDER BY c DESC LIMIT 15", rw), ra...); err == nil {
defer rows.Close()
for rows.Next() {
var a AddonCount
var c uint64
if rows.Scan(&a.Addon, &c) == nil {
a.Count = int(c)
data.TopAddons = append(data.TopAddons, a)
data.TotalAddons += int(c)
}
}
}
} else if rows, err := ch.db.QueryContext(ctx, fmt.Sprintf(
"SELECT nsapp, sum(total) c FROM telemetry_db.mv_daily_stats WHERE %s AND type='addon' AND nsapp!='' GROUP BY nsapp ORDER BY c DESC LIMIT 15", mw), ma...); err == nil {
defer rows.Close()
for rows.Next() {
var a AddonCount
var c uint64
if rows.Scan(&a.Addon, &c) == nil {
a.Count = int(c)
data.TopAddons = append(data.TopAddons, a)
data.TotalAddons += int(c)
}
}
}