forked from kubernetes/git-sync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
2494 lines (2184 loc) · 84.1 KB
/
main.go
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
/*
Copyright 2014 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// git-sync is a command that pulls a git repository to a local directory.
package main // import "k8s.io/git-sync/cmd/git-sync"
import (
"context"
"crypto/md5"
"errors"
"fmt"
"io"
"io/fs"
"net"
"net/http"
"net/http/pprof"
"net/url"
"os"
"os/exec"
"os/signal"
"os/user"
"path/filepath"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/spf13/pflag"
"golang.org/x/sys/unix"
"k8s.io/git-sync/pkg/cmd"
"k8s.io/git-sync/pkg/hook"
"k8s.io/git-sync/pkg/logging"
"k8s.io/git-sync/pkg/pid1"
"k8s.io/git-sync/pkg/version"
)
var (
metricSyncDuration = prometheus.NewSummaryVec(prometheus.SummaryOpts{
Name: "git_sync_duration_seconds",
Help: "Summary of git_sync durations",
}, []string{"status"})
metricSyncCount = prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "git_sync_count_total",
Help: "How many git syncs completed, partitioned by state (success, error, noop)",
}, []string{"status"})
metricFetchCount = prometheus.NewCounter(prometheus.CounterOpts{
Name: "git_fetch_count_total",
Help: "How many git fetches were run",
})
metricAskpassCount = prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "git_sync_askpass_calls",
Help: "How many git askpass calls completed, partitioned by state (success, error)",
}, []string{"status"})
)
func init() {
prometheus.MustRegister(metricSyncDuration)
prometheus.MustRegister(metricSyncCount)
prometheus.MustRegister(metricFetchCount)
prometheus.MustRegister(metricAskpassCount)
}
const (
metricKeySuccess = "success"
metricKeyError = "error"
metricKeyNoOp = "noop"
)
type submodulesMode string
const (
submodulesRecursive submodulesMode = "recursive"
submodulesShallow submodulesMode = "shallow"
submodulesOff submodulesMode = "off"
)
type gcMode string
const (
gcAuto = "auto"
gcAlways = "always"
gcAggressive = "aggressive"
gcOff = "off"
)
const defaultDirMode = os.FileMode(0775) // subject to umask
// repoSync represents the remote repo and the local sync of it.
type repoSync struct {
cmd string // the git command to run
root absPath // absolute path to the root directory
repo string // remote repo to sync
ref string // the ref to sync
depth int // for shallow sync
submodules submodulesMode // how to handle submodules
gc gcMode // garbage collection
link absPath // absolute path to the symlink to publish
authURL string // a URL to re-fetch credentials, or ""
sparseFile string // path to a sparse-checkout file
syncCount int // how many times have we synced?
log *logging.Logger
run cmd.Runner
staleTimeout time.Duration // time for worktrees to be cleaned up
}
func main() {
// In case we come up as pid 1, act as init.
if os.Getpid() == 1 {
fmt.Fprintf(os.Stderr, "INFO: detected pid 1, running init handler\n")
code, err := pid1.ReRun()
if err == nil {
os.Exit(code)
}
fmt.Fprintf(os.Stderr, "FATAL: unhandled pid1 error: %v\n", err)
os.Exit(127)
}
//
// Declare flags inside main() so they are not used as global variables.
//
flVersion := pflag.Bool("version", false, "print the version and exit")
flHelp := pflag.BoolP("help", "h", false, "print help text and exit")
pflag.BoolVarP(flHelp, "__?", "?", false, "print help text and exit") // support -? as an alias to -h
mustMarkHidden("__?")
flManual := pflag.Bool("man", false, "print the full manual and exit")
flVerbose := pflag.IntP("verbose", "v",
envInt(0, "GITSYNC_VERBOSE"),
"logs at this V level and lower will be printed")
flRepo := pflag.String("repo",
envString("", "GITSYNC_REPO", "GIT_SYNC_REPO"),
"the git repository to sync (required)")
flRef := pflag.String("ref",
envString("HEAD", "GITSYNC_REF"),
"the git revision (branch, tag, or hash) to sync")
flDepth := pflag.Int("depth",
envInt(1, "GITSYNC_DEPTH", "GIT_SYNC_DEPTH"),
"create a shallow clone with history truncated to the specified number of commits")
flSubmodules := pflag.String("submodules",
envString("recursive", "GITSYNC_SUBMODULES", "GIT_SYNC_SUBMODULES"),
"git submodule behavior: one of 'recursive', 'shallow', or 'off'")
flSparseCheckoutFile := pflag.String("sparse-checkout-file",
envString("", "GITSYNC_SPARSE_CHECKOUT_FILE", "GIT_SYNC_SPARSE_CHECKOUT_FILE"),
"the path to a sparse-checkout file")
flRoot := pflag.String("root",
envString("", "GITSYNC_ROOT", "GIT_SYNC_ROOT"),
"the root directory for git-sync operations (required)")
flLink := pflag.String("link",
envString("", "GITSYNC_LINK", "GIT_SYNC_LINK"),
"the path (absolute or relative to --root) at which to create a symlink to the directory holding the checked-out files (defaults to the leaf dir of --repo)")
flErrorFile := pflag.String("error-file",
envString("", "GITSYNC_ERROR_FILE", "GIT_SYNC_ERROR_FILE"),
"the path (absolute or relative to --root) to an optional file into which errors will be written (defaults to disabled)")
flPeriod := pflag.Duration("period",
envDuration(10*time.Second, "GITSYNC_PERIOD", "GIT_SYNC_PERIOD"),
"how long to wait between syncs, must be >= 10ms; --wait overrides this")
flSyncTimeout := pflag.Duration("sync-timeout",
envDuration(120*time.Second, "GITSYNC_SYNC_TIMEOUT", "GIT_SYNC_SYNC_TIMEOUT"),
"the total time allowed for one complete sync, must be >= 10ms; --timeout overrides this")
flOneTime := pflag.Bool("one-time",
envBool(false, "GITSYNC_ONE_TIME", "GIT_SYNC_ONE_TIME"),
"exit after the first sync")
flSyncOnSignal := pflag.String("sync-on-signal",
envString("", "GITSYNC_SYNC_ON_SIGNAL", "GIT_SYNC_SYNC_ON_SIGNAL"),
"sync on receipt of the specified signal (e.g. SIGHUP)")
flMaxFailures := pflag.Int("max-failures",
envInt(0, "GITSYNC_MAX_FAILURES", "GIT_SYNC_MAX_FAILURES"),
"the number of consecutive failures allowed before aborting (-1 will retry forever")
flTouchFile := pflag.String("touch-file",
envString("", "GITSYNC_TOUCH_FILE", "GIT_SYNC_TOUCH_FILE"),
"the path (absolute or relative to --root) to an optional file which will be touched whenever a sync completes (defaults to disabled)")
flAddUser := pflag.Bool("add-user",
envBool(false, "GITSYNC_ADD_USER", "GIT_SYNC_ADD_USER"),
"add a record to /etc/passwd for the current UID/GID (needed to use SSH with an arbitrary UID)")
flGroupWrite := pflag.Bool("group-write",
envBool(false, "GITSYNC_GROUP_WRITE", "GIT_SYNC_GROUP_WRITE"),
"ensure that all data (repo, worktrees, etc.) is group writable")
flStaleWorktreeTimeout := pflag.Duration("stale-worktree-timeout", envDuration(0, "GITSYNC_STALE_WORKTREE_TIMEOUT"),
"how long to retain non-current worktrees")
flExechookCommand := pflag.String("exechook-command",
envString("", "GITSYNC_EXECHOOK_COMMAND", "GIT_SYNC_EXECHOOK_COMMAND"),
"an optional command to be run when syncs complete (must be idempotent)")
flExechookTimeout := pflag.Duration("exechook-timeout",
envDuration(30*time.Second, "GITSYNC_EXECHOOK_TIMEOUT", "GIT_SYNC_EXECHOOK_TIMEOUT"),
"the timeout for the exechook")
flExechookBackoff := pflag.Duration("exechook-backoff",
envDuration(3*time.Second, "GITSYNC_EXECHOOK_BACKOFF", "GIT_SYNC_EXECHOOK_BACKOFF"),
"the time to wait before retrying a failed exechook")
flWebhookURL := pflag.String("webhook-url",
envString("", "GITSYNC_WEBHOOK_URL", "GIT_SYNC_WEBHOOK_URL"),
"a URL for optional webhook notifications when syncs complete (must be idempotent)")
flWebhookMethod := pflag.String("webhook-method",
envString("POST", "GITSYNC_WEBHOOK_METHOD", "GIT_SYNC_WEBHOOK_METHOD"),
"the HTTP method for the webhook")
flWebhookStatusSuccess := pflag.Int("webhook-success-status",
envInt(200, "GITSYNC_WEBHOOK_SUCCESS_STATUS", "GIT_SYNC_WEBHOOK_SUCCESS_STATUS"),
"the HTTP status code indicating a successful webhook (0 disables success checks")
flWebhookTimeout := pflag.Duration("webhook-timeout",
envDuration(1*time.Second, "GITSYNC_WEBHOOK_TIMEOUT", "GIT_SYNC_WEBHOOK_TIMEOUT"),
"the timeout for the webhook")
flWebhookBackoff := pflag.Duration("webhook-backoff",
envDuration(3*time.Second, "GITSYNC_WEBHOOK_BACKOFF", "GIT_SYNC_WEBHOOK_BACKOFF"),
"the time to wait before retrying a failed webhook")
flUsername := pflag.String("username",
envString("", "GITSYNC_USERNAME", "GIT_SYNC_USERNAME"),
"the username to use for git auth")
flPassword := pflag.String("password",
envString("", "GITSYNC_PASSWORD", "GIT_SYNC_PASSWORD"),
"the password or personal access token to use for git auth (prefer --password-file or this env var)")
flPasswordFile := pflag.String("password-file",
envString("", "GITSYNC_PASSWORD_FILE", "GIT_SYNC_PASSWORD_FILE"),
"the file from which the password or personal access token for git auth will be sourced")
flCredentials := pflagCredentialSlice("credential", envString("", "GITSYNC_CREDENTIAL"), "one or more credentials (see --man for details) available for authentication")
flSSHKeyFiles := pflag.StringArray("ssh-key-file",
envStringArray("/etc/git-secret/ssh", "GITSYNC_SSH_KEY_FILE", "GIT_SYNC_SSH_KEY_FILE", "GIT_SSH_KEY_FILE"),
"the SSH key(s) to use")
flSSHKnownHosts := pflag.Bool("ssh-known-hosts",
envBool(true, "GITSYNC_SSH_KNOWN_HOSTS", "GIT_SYNC_KNOWN_HOSTS", "GIT_KNOWN_HOSTS"),
"enable SSH known_hosts verification")
flSSHKnownHostsFile := pflag.String("ssh-known-hosts-file",
envString("/etc/git-secret/known_hosts", "GITSYNC_SSH_KNOWN_HOSTS_FILE", "GIT_SYNC_SSH_KNOWN_HOSTS_FILE", "GIT_SSH_KNOWN_HOSTS_FILE"),
"the known_hosts file to use")
flCookieFile := pflag.Bool("cookie-file",
envBool(false, "GITSYNC_COOKIE_FILE", "GIT_SYNC_COOKIE_FILE", "GIT_COOKIE_FILE"),
"use a git cookiefile (/etc/git-secret/cookie_file) for authentication")
flAskPassURL := pflag.String("askpass-url",
envString("", "GITSYNC_ASKPASS_URL", "GIT_SYNC_ASKPASS_URL", "GIT_ASKPASS_URL"),
"a URL to query for git credentials (username=<value> and password=<value>)")
flGitCmd := pflag.String("git",
envString("git", "GITSYNC_GIT", "GIT_SYNC_GIT"),
"the git command to run (subject to PATH search, mostly for testing)")
flGitConfig := pflag.String("git-config",
envString("", "GITSYNC_GIT_CONFIG", "GIT_SYNC_GIT_CONFIG"),
"additional git config options in 'section.var1:val1,\"section.sub.var2\":\"val2\"' format")
flGitGC := pflag.String("git-gc",
envString("always", "GITSYNC_GIT_GC", "GIT_SYNC_GIT_GC"),
"git garbage collection behavior: one of 'auto', 'always', 'aggressive', or 'off'")
flHTTPBind := pflag.String("http-bind",
envString("", "GITSYNC_HTTP_BIND", "GIT_SYNC_HTTP_BIND"),
"the bind address (including port) for git-sync's HTTP endpoint")
flHTTPMetrics := pflag.Bool("http-metrics",
envBool(false, "GITSYNC_HTTP_METRICS", "GIT_SYNC_HTTP_METRICS"),
"enable metrics on git-sync's HTTP endpoint")
flHTTPprof := pflag.Bool("http-pprof",
envBool(false, "GITSYNC_HTTP_PPROF", "GIT_SYNC_HTTP_PPROF"),
"enable the pprof debug endpoints on git-sync's HTTP endpoint")
// Obsolete flags, kept for compat.
flDeprecatedBranch := pflag.String("branch", envString("", "GIT_SYNC_BRANCH"),
"DEPRECATED: use --ref instead")
mustMarkDeprecated("branch", "use --ref instead")
flDeprecatedChmod := pflag.Int("change-permissions", envInt(0, "GIT_SYNC_PERMISSIONS"),
"DEPRECATED: use --group-write instead")
mustMarkDeprecated("change-permissions", "use --group-write instead")
flDeprecatedDest := pflag.String("dest", envString("", "GIT_SYNC_DEST"),
"DEPRECATED: use --link instead")
mustMarkDeprecated("dest", "use --link instead")
flDeprecatedMaxSyncFailures := pflag.Int("max-sync-failures", envInt(0, "GIT_SYNC_MAX_SYNC_FAILURES"),
"DEPRECATED: use --max-failures instead")
mustMarkDeprecated("max-sync-failures", "use --max-failures instead")
flDeprecatedRev := pflag.String("rev", envString("", "GIT_SYNC_REV"),
"DEPRECATED: use --ref instead")
mustMarkDeprecated("rev", "use --ref instead")
_ = pflag.Bool("ssh", false,
"DEPRECATED: this flag is no longer necessary")
mustMarkDeprecated("ssh", "no longer necessary")
flDeprecatedSyncHookCommand := pflag.String("sync-hook-command", envString("", "GIT_SYNC_HOOK_COMMAND"),
"DEPRECATED: use --exechook-command instead")
mustMarkDeprecated("sync-hook-command", "use --exechook-command instead")
flDeprecatedTimeout := pflag.Int("timeout", envInt(0, "GIT_SYNC_TIMEOUT"),
"DEPRECATED: use --sync-timeout instead")
mustMarkDeprecated("timeout", "use --sync-timeout instead")
flDeprecatedV := pflag.Int("v", -1,
"DEPRECATED: use -v or --verbose instead")
mustMarkDeprecated("v", "use -v or --verbose instead")
flDeprecatedWait := pflag.Float64("wait", envFloat(0, "GIT_SYNC_WAIT"),
"DEPRECATED: use --period instead")
mustMarkDeprecated("wait", "use --period instead")
// For whatever reason pflag hardcodes stderr for the "usage" line when
// using the default FlagSet. We tweak the output a bit anyway.
usage := func(out io.Writer, msg string) {
// When pflag parsing hits an error, it prints a message before and
// after the usage, which makes for nice reading.
if msg != "" {
fmt.Fprintln(out, msg)
}
fmt.Fprintln(out, "Usage:")
pflag.CommandLine.SetOutput(out)
pflag.PrintDefaults()
if msg != "" {
fmt.Fprintln(out, msg)
}
}
pflag.Usage = func() { usage(os.Stderr, "") }
//
// Parse and verify flags. Errors here are fatal.
//
pflag.Parse()
// Handle print-and-exit cases.
if *flVersion {
fmt.Println(version.VERSION)
os.Exit(0)
}
if *flHelp {
usage(os.Stdout, "")
os.Exit(0)
}
if *flManual {
printManPage()
os.Exit(0)
}
// Make sure we have a root dir in which to work.
if *flRoot == "" {
usage(os.Stderr, "required flag: --root must be specified")
os.Exit(1)
}
var absRoot absPath
if abs, err := absPath(*flRoot).Canonical(); err != nil {
fmt.Fprintf(os.Stderr, "FATAL: can't absolutize --root: %v\n", err)
os.Exit(1)
} else {
absRoot = abs
}
// Init logging very early, so most errors can be written to a file.
if *flDeprecatedV >= 0 {
// Back-compat
*flVerbose = *flDeprecatedV
}
log := func() *logging.Logger {
dir, file := makeAbsPath(*flErrorFile, absRoot).Split()
return logging.New(dir.String(), file, *flVerbose)
}()
cmdRunner := cmd.NewRunner(log)
if *flRepo == "" {
fatalConfigError(log, true, "required flag: --repo must be specified")
}
switch {
case *flDeprecatedBranch != "" && (*flDeprecatedRev == "" || *flDeprecatedRev == "HEAD"):
// Back-compat
log.V(0).Info("setting --ref from deprecated --branch")
*flRef = *flDeprecatedBranch
case *flDeprecatedRev != "" && *flDeprecatedBranch == "":
// Back-compat
log.V(0).Info("setting --ref from deprecated --rev")
*flRef = *flDeprecatedRev
case *flDeprecatedBranch != "" && *flDeprecatedRev != "":
fatalConfigError(log, true, "deprecated flag combo: can't set --ref from deprecated --branch and --rev (one or the other is OK)")
}
if *flRef == "" {
fatalConfigError(log, true, "required flag: --ref must be specified")
}
if *flDepth < 0 { // 0 means "no limit"
fatalConfigError(log, true, "invalid flag: --depth must be greater than or equal to 0")
}
switch submodulesMode(*flSubmodules) {
case submodulesRecursive, submodulesShallow, submodulesOff:
default:
fatalConfigError(log, true, "invalid flag: --submodules must be one of %q, %q, or %q", submodulesRecursive, submodulesShallow, submodulesOff)
}
switch *flGitGC {
case gcAuto, gcAlways, gcAggressive, gcOff:
default:
fatalConfigError(log, true, "invalid flag: --git-gc must be one of %q, %q, %q, or %q", gcAuto, gcAlways, gcAggressive, gcOff)
}
if *flDeprecatedDest != "" {
// Back-compat
log.V(0).Info("setting --link from deprecated --dest")
*flLink = *flDeprecatedDest
}
if *flLink == "" {
parts := strings.Split(strings.Trim(*flRepo, "/"), "/")
*flLink = parts[len(parts)-1]
}
if *flDeprecatedWait != 0 {
// Back-compat
log.V(0).Info("setting --period from deprecated --wait")
*flPeriod = time.Duration(int(*flDeprecatedWait*1000)) * time.Millisecond
}
if *flPeriod < 10*time.Millisecond {
fatalConfigError(log, true, "invalid flag: --period must be at least 10ms")
}
if *flDeprecatedChmod != 0 {
fatalConfigError(log, true, "deprecated flag: --change-permissions is no longer supported")
}
var syncSig syscall.Signal
if *flSyncOnSignal != "" {
if num, err := strconv.ParseInt(*flSyncOnSignal, 0, 0); err == nil {
// sync-on-signal value is a number
syncSig = syscall.Signal(num)
} else {
// sync-on-signal value is a name
syncSig = unix.SignalNum(*flSyncOnSignal)
if syncSig == 0 {
// last resort - maybe they said "HUP", meaning "SIGHUP"
syncSig = unix.SignalNum("SIG" + *flSyncOnSignal)
}
}
if syncSig == 0 {
fatalConfigError(log, true, "invalid flag: --sync-on-signal must be a valid signal name or number")
}
}
if *flDeprecatedTimeout != 0 {
// Back-compat
log.V(0).Info("setting --sync-timeout from deprecated --timeout")
*flSyncTimeout = time.Duration(*flDeprecatedTimeout) * time.Second
}
if *flSyncTimeout < 10*time.Millisecond {
fatalConfigError(log, true, "invalid flag: --sync-timeout must be at least 10ms")
}
if *flDeprecatedMaxSyncFailures != 0 {
// Back-compat
log.V(0).Info("setting --max-failures from deprecated --max-sync-failures")
*flMaxFailures = *flDeprecatedMaxSyncFailures
}
if *flDeprecatedSyncHookCommand != "" {
// Back-compat
log.V(0).Info("setting --exechook-command from deprecated --sync-hook-command")
*flExechookCommand = *flDeprecatedSyncHookCommand
}
if *flExechookCommand != "" {
if *flExechookTimeout < time.Second {
fatalConfigError(log, true, "invalid flag: --exechook-timeout must be at least 1s")
}
if *flExechookBackoff < time.Second {
fatalConfigError(log, true, "invalid flag: --exechook-backoff must be at least 1s")
}
}
if *flWebhookURL != "" {
if *flWebhookStatusSuccess == -1 {
// Back-compat: -1 and 0 mean the same things
*flWebhookStatusSuccess = 0
}
if *flWebhookStatusSuccess < 0 {
fatalConfigError(log, true, "invalid flag: --webhook-success-status must be a valid HTTP code or 0")
}
if *flWebhookTimeout < time.Second {
fatalConfigError(log, true, "invalid flag: --webhook-timeout must be at least 1s")
}
if *flWebhookBackoff < time.Second {
fatalConfigError(log, true, "invalid flag: --webhook-backoff must be at least 1s")
}
}
if *flUsername != "" {
if *flPassword == "" && *flPasswordFile == "" {
fatalConfigError(log, true, "required flag: --password or --password-file must be specified when --username is specified")
}
if *flPassword != "" && *flPasswordFile != "" {
fatalConfigError(log, true, "invalid flag: only one of --password and --password-file may be specified")
}
if u, err := url.Parse(*flRepo); err == nil { // it may not even parse as a URL, that's OK
if u.User != nil {
fatalConfigError(log, true, "invalid flag: credentials may not be specified in --repo when --username is specified")
}
}
} else {
if *flPassword != "" {
fatalConfigError(log, true, "invalid flag: --password may only be specified when --username is specified")
}
if *flPasswordFile != "" {
fatalConfigError(log, true, "invalid flag: --password-file may only be specified when --username is specified")
}
}
if len(*flCredentials) > 0 {
for _, cred := range *flCredentials {
if cred.URL == "" {
fatalConfigError(log, true, "invalid flag: --credential URL must be specified")
}
if cred.Username == "" {
fatalConfigError(log, true, "invalid flag: --credential username must be specified")
}
if cred.Password == "" && cred.PasswordFile == "" {
fatalConfigError(log, true, "invalid flag: --credential password or password-file must be specified")
}
if cred.Password != "" && cred.PasswordFile != "" {
fatalConfigError(log, true, "invalid flag: only one of --credential password and password-file may be specified")
}
}
}
if *flHTTPBind == "" {
if *flHTTPMetrics {
fatalConfigError(log, true, "required flag: --http-bind must be specified when --http-metrics is set")
}
if *flHTTPprof {
fatalConfigError(log, true, "required flag: --http-bind must be specified when --http-pprof is set")
}
}
//
// From here on, output goes through logging.
//
log.V(0).Info("starting up",
"version", version.VERSION,
"pid", os.Getpid(),
"uid", os.Getuid(),
"gid", os.Getgid(),
"home", os.Getenv("HOME"),
"flags", logSafeFlags(*flVerbose))
if _, err := exec.LookPath(*flGitCmd); err != nil {
log.Error(err, "FATAL: git executable not found", "git", *flGitCmd)
os.Exit(1)
}
// If the user asked for group-writable data, make sure the umask allows it.
if *flGroupWrite {
syscall.Umask(0002)
} else {
syscall.Umask(0022)
}
// Make sure the root exists. defaultDirMode ensures that this is usable
// as a volume when the consumer isn't running as the same UID. We do this
// very early so that we can normalize the path even when there are
// symlinks in play.
if err := os.MkdirAll(absRoot.String(), defaultDirMode); err != nil {
log.Error(err, "FATAL: can't make root dir", "path", absRoot)
os.Exit(1)
}
// Get rid of symlinks in the root path to avoid getting confused about
// them later. The path must exist for EvalSymlinks to work.
if delinked, err := filepath.EvalSymlinks(absRoot.String()); err != nil {
log.Error(err, "FATAL: can't normalize root path", "path", absRoot)
os.Exit(1)
} else {
absRoot = absPath(delinked)
}
if absRoot.String() != *flRoot {
log.V(0).Info("normalized root path", "root", *flRoot, "result", absRoot)
}
// Convert files into an absolute paths.
absLink := makeAbsPath(*flLink, absRoot)
absTouchFile := makeAbsPath(*flTouchFile, absRoot)
// Merge credential sources.
if *flUsername == "" {
// username and user@host URLs are validated as mutually exclusive
if u, err := url.Parse(*flRepo); err == nil { // it may not even parse as a URL, that's OK
// Note that `ssh://user@host/path` URLs need to retain the user
// field. Out of caution, we only handle HTTP(S) URLs here.
if u.User != nil && (u.Scheme == "http" || u.Scheme == "https") {
if user := u.User.Username(); user != "" {
*flUsername = user
}
if pass, found := u.User.Password(); found {
*flPassword = pass
}
u.User = nil
*flRepo = u.String()
}
}
}
if *flUsername != "" {
cred := credential{
URL: *flRepo,
Username: *flUsername,
Password: *flPassword,
PasswordFile: *flPasswordFile,
}
*flCredentials = append([]credential{cred}, (*flCredentials)...)
}
if *flAddUser {
if err := addUser(); err != nil {
log.Error(err, "FATAL: can't add user")
os.Exit(1)
}
}
// Capture the various git parameters.
git := &repoSync{
cmd: *flGitCmd,
root: absRoot,
repo: *flRepo,
ref: *flRef,
depth: *flDepth,
submodules: submodulesMode(*flSubmodules),
gc: gcMode(*flGitGC),
link: absLink,
authURL: *flAskPassURL,
sparseFile: *flSparseCheckoutFile,
log: log,
run: cmdRunner,
staleTimeout: *flStaleWorktreeTimeout,
}
// This context is used only for git credentials initialization. There are
// no long-running operations like `git fetch`, so hopefully 30 seconds will be enough.
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
// Log the git version.
if ver, _, err := cmdRunner.Run(ctx, "", nil, *flGitCmd, "version"); err != nil {
log.Error(err, "can't get git version")
os.Exit(1)
} else {
log.V(0).Info("git version", "version", ver)
}
// Don't pollute the user's .gitconfig if this is being run directly.
if f, err := os.CreateTemp("", "git-sync.gitconfig.*"); err != nil {
log.Error(err, "FATAL: can't create gitconfig file")
os.Exit(1)
} else {
gitConfig := f.Name()
f.Close()
os.Setenv("GIT_CONFIG_GLOBAL", gitConfig)
os.Setenv("GIT_CONFIG_NOSYSTEM", "true")
log.V(2).Info("created private gitconfig file", "path", gitConfig)
}
// Set various configs we want, but users might override.
if err := git.SetupDefaultGitConfigs(ctx); err != nil {
log.Error(err, "can't set default git configs")
os.Exit(1)
}
// Finish populating credentials.
for i := range *flCredentials {
cred := &(*flCredentials)[i]
if cred.PasswordFile != "" {
passwordFileBytes, err := os.ReadFile(cred.PasswordFile)
if err != nil {
log.Error(err, "can't read password file", "file", cred.PasswordFile)
os.Exit(1)
}
cred.Password = string(passwordFileBytes)
}
}
// If the --repo or any submodule uses SSH, we need to know which keys.
if err := git.SetupGitSSH(*flSSHKnownHosts, *flSSHKeyFiles, *flSSHKnownHostsFile); err != nil {
log.Error(err, "can't set up git SSH", "keyFile", *flSSHKeyFiles, "knownHosts", *flSSHKnownHosts, "knownHostsFile", *flSSHKnownHostsFile)
os.Exit(1)
}
if *flCookieFile {
if err := git.SetupCookieFile(ctx); err != nil {
log.Error(err, "can't set up git cookie file")
os.Exit(1)
}
}
// This needs to be after all other git-related config flags.
if *flGitConfig != "" {
if err := git.SetupExtraGitConfigs(ctx, *flGitConfig); err != nil {
log.Error(err, "can't set additional git configs", "configs", *flGitConfig)
os.Exit(1)
}
}
// The scope of the initialization context ends here, so we call cancel to release resources associated with it.
cancel()
if *flHTTPBind != "" {
ln, err := net.Listen("tcp", *flHTTPBind)
if err != nil {
log.Error(err, "can't bind HTTP endpoint", "endpoint", *flHTTPBind)
os.Exit(1)
}
mux := http.NewServeMux()
reasons := []string{}
// This is a dumb liveliness check endpoint. Currently this checks
// nothing and will always return 200 if the process is live.
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if !getRepoReady() {
http.Error(w, "repo is not ready", http.StatusServiceUnavailable)
}
// Otherwise success
})
reasons = append(reasons, "liveness")
if *flHTTPMetrics {
mux.Handle("/metrics", promhttp.Handler())
reasons = append(reasons, "metrics")
}
if *flHTTPprof {
mux.HandleFunc("/debug/pprof/", pprof.Index)
mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
reasons = append(reasons, "pprof")
}
log.V(0).Info("serving HTTP", "endpoint", *flHTTPBind, "reasons", reasons)
go func() {
err := http.Serve(ln, mux)
log.Error(err, "HTTP server terminated")
os.Exit(1)
}()
}
// Startup webhooks goroutine
var webhookRunner *hook.HookRunner
if *flWebhookURL != "" {
log := log.WithName("webhook")
webhook := hook.NewWebhook(
*flWebhookURL,
*flWebhookMethod,
*flWebhookStatusSuccess,
*flWebhookTimeout,
log,
)
webhookRunner = hook.NewHookRunner(
webhook,
*flWebhookBackoff,
hook.NewHookData(),
log,
*flOneTime,
)
go webhookRunner.Run(context.Background())
}
// Startup exechooks goroutine
var exechookRunner *hook.HookRunner
if *flExechookCommand != "" {
log := log.WithName("exechook")
exechook := hook.NewExechook(
cmd.NewRunner(log),
*flExechookCommand,
func(hash string) string {
return git.worktreeFor(hash).Path().String()
},
[]string{},
*flExechookTimeout,
log,
)
exechookRunner = hook.NewHookRunner(
exechook,
*flExechookBackoff,
hook.NewHookData(),
log,
*flOneTime,
)
go exechookRunner.Run(context.Background())
}
// Setup signal notify channel
sigChan := make(chan os.Signal, 1)
if syncSig != 0 {
log.V(1).Info("installing signal handler", "signal", unix.SignalName(syncSig))
signal.Notify(sigChan, syncSig)
}
// Craft a function that can be called to refresh credentials when needed.
refreshCreds := func(ctx context.Context) error {
// These should all be mutually-exclusive configs.
for _, cred := range *flCredentials {
if err := git.StoreCredentials(ctx, cred.URL, cred.Username, cred.Password); err != nil {
return err
}
}
if *flAskPassURL != "" {
// When using an auth URL, the credentials can be dynamic, and need
// to be re-fetched each time.
if err := git.CallAskPassURL(ctx); err != nil {
metricAskpassCount.WithLabelValues(metricKeyError).Inc()
return err
}
metricAskpassCount.WithLabelValues(metricKeySuccess).Inc()
}
return nil
}
failCount := 0
syncCount := uint64(0)
for {
start := time.Now()
ctx, cancel := context.WithTimeout(context.Background(), *flSyncTimeout)
if changed, hash, err := git.SyncRepo(ctx, refreshCreds); err != nil {
failCount++
updateSyncMetrics(metricKeyError, start)
if *flMaxFailures >= 0 && failCount >= *flMaxFailures {
// Exit after too many retries, maybe the error is not recoverable.
log.Error(err, "too many failures, aborting", "failCount", failCount)
os.Exit(1)
}
log.Error(err, "error syncing repo, will retry", "failCount", failCount)
} else {
// this might have been called before, but also might not have
setRepoReady()
// We treat the first loop as a sync, including sending hooks.
if changed || syncCount == 0 {
if absTouchFile != "" {
if err := touch(absTouchFile); err != nil {
log.Error(err, "failed to touch touch-file", "path", absTouchFile)
} else {
log.V(3).Info("touched touch-file", "path", absTouchFile)
}
}
if webhookRunner != nil {
webhookRunner.Send(hash)
}
if exechookRunner != nil {
exechookRunner.Send(hash)
}
updateSyncMetrics(metricKeySuccess, start)
} else {
updateSyncMetrics(metricKeyNoOp, start)
}
syncCount++
// Clean up old worktree(s) and run GC.
if err := git.cleanup(ctx); err != nil {
log.Error(err, "git cleanup failed")
}
// Determine if git-sync should terminate for one of several reasons
if *flOneTime {
// Wait for hooks to complete at least once, if not nil, before
// checking whether to stop program.
// Assumes that if hook channels are not nil, they will have at
// least one value before getting closed
exitCode := 0 // is 0 if all hooks succeed, else is 1
if exechookRunner != nil {
if err := exechookRunner.WaitForCompletion(); err != nil {
exitCode = 1
}
}
if webhookRunner != nil {
if err := webhookRunner.WaitForCompletion(); err != nil {
exitCode = 1
}
}
log.DeleteErrorFile()
log.V(0).Info("exiting after one sync", "status", exitCode)
os.Exit(exitCode)
}
if hash == git.ref {
log.V(0).Info("ref appears to be a git hash, no further sync needed", "ref", git.ref)
log.DeleteErrorFile()
sleepForever()
}
if failCount > 0 {
log.V(4).Info("resetting failure count", "failCount", failCount)
failCount = 0
}
log.DeleteErrorFile()
}
log.V(3).Info("next sync", "waitTime", flPeriod.String(), "syncCount", syncCount)
cancel()
// Sleep until the next sync. If syncSig is set then the sleep may
// be interrupted by that signal.
t := time.NewTimer(*flPeriod)
select {
case <-t.C:
case <-sigChan:
log.V(1).Info("caught signal", "signal", unix.SignalName(syncSig))
t.Stop()
}
}
}
// mustMarkDeprecated is a helper around pflag.CommandLine.MarkDeprecated.
// It panics if there is an error (as these indicate a coding issue).
// This makes it easier to keep the linters happy.
func mustMarkDeprecated(name string, usageMessage string) {
err := pflag.CommandLine.MarkDeprecated(name, usageMessage)
if err != nil {
panic(fmt.Sprintf("error marking flag %q as deprecated: %v", name, err))
}
}
// mustMarkHidden is a helper around pflag.CommandLine.MarkHidden.
// It panics if there is an error (as these indicate a coding issue).
// This makes it easier to keep the linters happy.
func mustMarkHidden(name string) {
err := pflag.CommandLine.MarkHidden(name)
if err != nil {
panic(fmt.Sprintf("error marking flag %q as hidden: %v", name, err))
}
}
// makeAbsPath makes an absolute path from a path which might be absolute
// or relative. If the path is already absolute, it will be used. If it is
// not absolute, it will be joined with the provided root. If the path is
// empty, the result will be empty.
func makeAbsPath(path string, root absPath) absPath {
if path == "" {
return ""
}
if filepath.IsAbs(path) {
return absPath(path)
}
return root.Join(path)
}
// touch will try to ensure that the file at the specified path exists and that
// its timestamps are updated.
func touch(path absPath) error {
dir := path.Dir()
if err := os.MkdirAll(dir, defaultDirMode); err != nil {
return err
}
if err := os.Chtimes(path.String(), time.Now(), time.Now()); errors.Is(err, fs.ErrNotExist) {
file, createErr := os.Create(path.String())
if createErr != nil {
return createErr
}
return file.Close()
} else {
return err
}
}
const redactedString = "REDACTED"
func redactURL(urlstr string) string {
u, err := url.Parse(urlstr)
if err != nil {
// May be something like [email protected]:path/to/repo
return urlstr
}
if u.User != nil {
if _, found := u.User.Password(); found {
u.User = url.UserPassword(u.User.Username(), redactedString)
}
}
return u.String()
}
// logSafeFlags makes sure any sensitive args (e.g. passwords) are redacted
// before logging. This returns a slice rather than a map so it is always
// sorted.
func logSafeFlags(v int) []string {
ret := []string{}
pflag.VisitAll(func(fl *pflag.Flag) {
// Don't log hidden flags
if fl.Hidden {
return
}
// Don't log unchanged values
if !fl.Changed && v <= 3 {
return
}
arg := fl.Name
val := fl.Value.String()