forked from kubernetes/test-infra
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
227 lines (193 loc) · 7.72 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
/*
Copyright 2017 The Kubernetes Authors.
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.
*/
package main
import (
"context"
"flag"
"net/http"
"os"
"strconv"
"time"
"github.com/sirupsen/logrus"
"k8s.io/test-infra/prow/pjutil/pprof"
"sigs.k8s.io/controller-runtime/pkg/manager"
"k8s.io/test-infra/pkg/flagutil"
prowflagutil "k8s.io/test-infra/prow/flagutil"
configflagutil "k8s.io/test-infra/prow/flagutil/config"
"k8s.io/test-infra/prow/git/v2"
"k8s.io/test-infra/prow/interrupts"
"k8s.io/test-infra/prow/logrusutil"
"k8s.io/test-infra/prow/metrics"
"k8s.io/test-infra/prow/tide"
)
type options struct {
port int
config configflagutil.ConfigOptions
syncThrottle int
statusThrottle int
dryRun bool
runOnce bool
kubernetes prowflagutil.KubernetesOptions
github prowflagutil.GitHubOptions
storage prowflagutil.StorageClientOptions
instrumentationOptions prowflagutil.InstrumentationOptions
maxRecordsPerPool int
// historyURI where Tide should store its action history.
// Can be /local/path, gs://path/to/object or s3://path/to/object.
// GCS writes will use the bucket's default acl for new objects. Ensure both that
// a) the gcs credentials can write to this bucket
// b) the default acls do not expose any private info
historyURI string
// statusURI where Tide store status update state.
// Can be a /local/path, gs://path/to/object or s3://path/to/object.
// GCS writes will use the bucket's default acl for new objects. Ensure both that
// a) the gcs credentials can write to this bucket
// b) the default acls do not expose any private info
statusURI string
}
func (o *options) Validate() error {
for _, group := range []flagutil.OptionGroup{&o.kubernetes, &o.github, &o.storage, &o.config} {
if err := group.Validate(o.dryRun); err != nil {
return err
}
}
return nil
}
func gatherOptions(fs *flag.FlagSet, args ...string) options {
var o options
fs.IntVar(&o.port, "port", 8888, "Port to listen on.")
fs.BoolVar(&o.dryRun, "dry-run", true, "Whether to mutate any real-world state.")
fs.BoolVar(&o.runOnce, "run-once", false, "If true, run only once then quit.")
o.github.AddCustomizedFlags(fs, prowflagutil.DisableThrottlerOptions())
for _, group := range []flagutil.OptionGroup{&o.kubernetes, &o.storage, &o.instrumentationOptions, &o.config} {
group.AddFlags(fs)
}
fs.IntVar(&o.syncThrottle, "sync-hourly-tokens", 800, "The maximum number of tokens per hour to be used by the sync controller.")
fs.IntVar(&o.statusThrottle, "status-hourly-tokens", 400, "The maximum number of tokens per hour to be used by the status controller.")
fs.IntVar(&o.maxRecordsPerPool, "max-records-per-pool", 1000, "The maximum number of history records stored for an individual Tide pool.")
fs.StringVar(&o.historyURI, "history-uri", "", "The /local/path,gs://path/to/object or s3://path/to/object to store tide action history. GCS writes will use the default object ACL for the bucket")
fs.StringVar(&o.statusURI, "status-path", "", "The /local/path, gs://path/to/object or s3://path/to/object to store status controller state. GCS writes will use the default object ACL for the bucket.")
fs.Parse(args)
return o
}
func main() {
logrusutil.ComponentInit()
defer interrupts.WaitForGracefulShutdown()
o := gatherOptions(flag.NewFlagSet(os.Args[0], flag.ExitOnError), os.Args[1:]...)
if err := o.Validate(); err != nil {
logrus.WithError(err).Fatal("Invalid options")
}
pprof.Instrument(o.instrumentationOptions)
opener, err := o.storage.StorageClient(context.Background())
if err != nil {
logrus.WithError(err).Fatal("Cannot create opener")
}
configAgent, err := o.config.ConfigAgent()
if err != nil {
logrus.WithError(err).Fatal("Error starting config agent.")
}
cfg := configAgent.Config
githubSync, err := o.github.GitHubClientWithLogFields(o.dryRun, logrus.Fields{"controller": "sync"})
if err != nil {
logrus.WithError(err).Fatal("Error getting GitHub client for sync.")
}
githubStatus, err := o.github.GitHubClientWithLogFields(o.dryRun, logrus.Fields{"controller": "status-update"})
if err != nil {
logrus.WithError(err).Fatal("Error getting GitHub client for status.")
}
// The sync loop should be allowed more tokens than the status loop because
// it has to list all PRs in the pool every loop while the status loop only
// has to list changed PRs every loop.
// The sync loop should have a much lower burst allowance than the status
// loop which may need to update many statuses upon restarting Tide after
// changing the context format or starting Tide on a new repo.
githubSync.Throttle(o.syncThrottle, 3*tokensPerIteration(o.syncThrottle, cfg().Tide.SyncPeriod.Duration))
githubStatus.Throttle(o.statusThrottle, o.statusThrottle/2)
gitClient, err := o.github.GitClient(o.dryRun)
if err != nil {
logrus.WithError(err).Fatal("Error getting Git client.")
}
kubeCfg, err := o.kubernetes.InfrastructureClusterConfig(o.dryRun)
if err != nil {
logrus.WithError(err).Fatal("Error getting kubeconfig.")
}
// Do not activate leader election here, as we do not use the `mgr` to control the lifecylcle of our cotrollers,
// this would just be a no-op.
mgr, err := manager.New(kubeCfg, manager.Options{Namespace: cfg().ProwJobNamespace, MetricsBindAddress: "0"})
if err != nil {
logrus.WithError(err).Fatal("Error constructing mgr.")
}
c, err := tide.NewController(
githubSync,
githubStatus,
mgr,
cfg,
git.ClientFactoryFrom(gitClient),
o.maxRecordsPerPool,
opener,
o.historyURI,
o.statusURI,
nil,
o.github.AppPrivateKeyPath != "",
)
if err != nil {
logrus.WithError(err).Fatal("Error creating Tide controller.")
}
interrupts.Run(func(ctx context.Context) {
if err := mgr.Start(ctx); err != nil {
logrus.WithError(err).Fatal("Mgr failed.")
}
logrus.Info("Mgr finished gracefully.")
})
mgrSyncCtx, mgrSyncCtxCancel := context.WithTimeout(context.Background(), 30*time.Second)
defer mgrSyncCtxCancel()
if synced := mgr.GetCache().WaitForCacheSync(mgrSyncCtx); !synced {
logrus.Fatal("Timed out waiting for cachesync")
}
interrupts.OnInterrupt(func() {
c.Shutdown()
if err := gitClient.Clean(); err != nil {
logrus.WithError(err).Error("Could not clean up git client cache.")
}
})
// Deck consumes these endpoints
controllerMux := http.NewServeMux()
controllerMux.Handle("/", c)
controllerMux.Handle("/history", c.History())
server := &http.Server{Addr: ":" + strconv.Itoa(o.port), Handler: controllerMux}
// Push metrics to the configured prometheus pushgateway endpoint or serve them
metrics.ExposeMetrics("tide", cfg().PushGateway, o.instrumentationOptions.MetricsPort)
start := time.Now()
sync(c)
if o.runOnce {
return
}
// serve data
interrupts.ListenAndServe(server, 10*time.Second)
// run the controller, but only after one sync period expires after our first run
time.Sleep(time.Until(start.Add(cfg().Tide.SyncPeriod.Duration)))
interrupts.Tick(func() {
sync(c)
}, func() time.Duration {
return cfg().Tide.SyncPeriod.Duration
})
}
func sync(c *tide.Controller) {
if err := c.Sync(); err != nil {
logrus.WithError(err).Error("Error syncing.")
}
}
func tokensPerIteration(hourlyTokens int, iterPeriod time.Duration) int {
tokenRate := float64(hourlyTokens) / float64(time.Hour)
return int(tokenRate * float64(iterPeriod))
}