forked from IBM/test-infra
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
201 lines (178 loc) · 4.94 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
/*
Copyright 2019 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"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"strings"
"time"
"github.com/sirupsen/logrus"
"k8s.io/test-infra/prow/interrupts"
"sigs.k8s.io/yaml"
prowapi "k8s.io/test-infra/prow/apis/prowjobs/v1"
)
type options struct {
keepGoing bool
printCmd bool
priv bool
timeout time.Duration
totalTimeout time.Duration
grace time.Duration
jobs []string
}
func gatherOptions() options {
var o options
fs := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
fs.BoolVar(&o.keepGoing, "keep-going", false, "Continue running jobs after one fails if set")
fs.BoolVar(&o.printCmd, "print", false, "Just print the command it would run")
fs.BoolVar(&o.priv, "privileged", false, "Allow privileged local runs")
fs.DurationVar(&o.timeout, "timeout", time.Hour, "Maximum duration for each job (0 for unlimited)")
fs.DurationVar(&o.totalTimeout, "total-timeout", 0, "Maximum duration for all jobs (0 for unlimited)")
fs.DurationVar(&o.grace, "grace", 10*time.Second, "Terminate timed out jobs after this grace period (1s minimum)")
fs.Parse(os.Args[1:])
o.jobs = fs.Args()
return o
}
func validate(pj prowapi.ProwJob) error {
switch {
case pj.Kind != "ProwJob":
return fmt.Errorf("bad kind: %q", pj.Kind)
case pj.Spec.PodSpec == nil && pj.Spec.Agent != prowapi.KubernetesAgent:
return fmt.Errorf("unsupported agent: %q. Only %q with a pod_spec is supported at present", pj.Spec.Agent, prowapi.KubernetesAgent)
case pj.Spec.PodSpec == nil:
return errors.New("empty pod_spec")
}
return nil
}
func readPJ(reader io.ReadCloser) (*prowapi.ProwJob, error) {
var pj prowapi.ProwJob
buf, err := ioutil.ReadAll(reader)
if err != nil {
return nil, fmt.Errorf("read: %v", err)
}
if err := yaml.Unmarshal(buf, &pj); err != nil {
return nil, fmt.Errorf("unmarshal: %v", err)
}
if err := validate(pj); err != nil {
return nil, fmt.Errorf("validate: %v", err)
}
return &pj, nil
}
func readFile(path string) (*prowapi.ProwJob, error) {
f, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("open: %v", err)
}
defer f.Close()
return readPJ(f)
}
func readHTTP(url string) (*prowapi.ProwJob, error) {
resp, err := http.Get(url)
if err != nil {
return nil, fmt.Errorf("get: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return nil, fmt.Errorf("bad status: %d", resp.StatusCode)
}
return readPJ(resp.Body)
}
func readPJs(jobs []string) (<-chan prowapi.ProwJob, <-chan error) {
ch := make(chan prowapi.ProwJob)
errch := make(chan error)
go func() {
defer close(ch)
defer close(errch)
if len(jobs) == 0 {
logrus.Info("Converting stdin prowjob...")
pj, err := readPJ(os.Stdin)
if err != nil {
errch <- err
return
}
ch <- *pj
errch <- nil
return
}
for _, j := range jobs {
var pj *prowapi.ProwJob
var err error
if strings.HasPrefix(j, "https:") || strings.HasPrefix(j, "http:") {
logrus.WithField("url", j).Info("Downloading...")
pj, err = readHTTP(j)
} else {
logrus.WithField("path", j).Info("Reading...")
pj, err = readFile(j)
}
if err != nil {
errch <- fmt.Errorf("%q: %v", j, err)
return
}
ch <- *pj
}
errch <- nil
}()
return ch, errch
}
func jobName(pj prowapi.ProwJob) string {
if pj.Spec.Job != "" {
return pj.Spec.Job
}
return pj.Name
}
func main() {
opt := gatherOptions()
pjs, errs := readPJs(opt.jobs)
defer interrupts.WaitForGracefulShutdown()
if err := processJobs(interrupts.Context(), opt, pjs, errs); err != nil {
logrus.WithError(err).Fatal("FAILED")
}
logrus.Info("SUCCESS")
}
func processJobs(ctx context.Context, opt options, pjs <-chan prowapi.ProwJob, errs <-chan error) error {
var cancel func()
if opt.totalTimeout > 0 {
ctx, cancel = context.WithTimeout(ctx, opt.totalTimeout)
} else {
ctx, cancel = context.WithCancel(ctx)
}
defer cancel()
for {
select {
case pj := <-pjs:
start := time.Now()
log := logrus.WithField("job", jobName(pj))
err := convertJob(ctx, log, pj, opt.priv, opt.printCmd, opt.timeout, opt.grace)
log = log.WithField("duration", time.Now().Sub(start))
if err != nil {
log.WithError(err).Error("FAIL")
if !opt.keepGoing {
log.Warn("Aborting other jobs...")
cancel()
}
continue
}
log.Info("PASS")
case err := <-errs:
return err
case <-ctx.Done():
return fmt.Errorf("cancel: %v", ctx.Err())
}
}
}