generated from kubernetes/kubernetes-template-project
-
Notifications
You must be signed in to change notification settings - Fork 73
/
janitor.go
184 lines (153 loc) · 5.59 KB
/
janitor.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
/*
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 (
"fmt"
"os/exec"
"strings"
"time"
"github.com/sirupsen/logrus"
flag "github.com/spf13/pflag"
"sigs.k8s.io/prow/pkg/logrusutil"
"sigs.k8s.io/boskos/client"
"sigs.k8s.io/boskos/common"
)
var (
bufferSize = 1 // Maximum holding resources
rTypes common.CommaSeparatedStrings
rTypesConfig string
poolSize int
updateFrequency time.Duration
janitorPath = flag.String("janitor-path", "/bin/gcp_janitor.py", "Path to janitor binary path")
boskosURL = flag.String("boskos-url", "http://boskos", "Boskos URL")
username = flag.String("username", "", "Username used to access the Boskos server")
passwordFile = flag.String("password-file", "", "The path to password file used to access the Boskos server")
logLevel = flag.String("log-level", "info", fmt.Sprintf("Log level is one of %v.", logrus.AllLevels))
)
func init() {
flag.Var(&rTypes, "resource-type", "comma-separated list of resources need to be cleaned up")
flag.StringVar(&rTypesConfig, "resource-type-from-config", "", "extract a list of resources need to be cleaned up from boskos' config file; "+
"if both resource-type and resource-type-from-config are specified, resource-type will take priority")
flag.IntVar(&poolSize, "pool-size", 20, "number of concurrent janitor goroutine")
flag.DurationVar(&updateFrequency, "update-frequency", 5*time.Minute, "How often to heartbeat owning resources.")
}
func main() {
logrusutil.ComponentInit()
flag.Parse()
extraJanitorFlags := flag.CommandLine.Args()
level, err := logrus.ParseLevel(*logLevel)
if err != nil {
logrus.WithError(err).Fatal("invalid log level specified")
}
logrus.SetLevel(level)
boskos, err := client.NewClient("Janitor", *boskosURL, *username, *passwordFile)
if err != nil {
logrus.WithError(err).Fatal("unable to create a Boskos client")
}
logrus.Info("Initialized boskos client!")
if len(rTypes) == 0 && rTypesConfig == "" {
logrus.Fatal("--resource-type or --resource-type-from-config must be set")
}
var rt common.ResourceTypes
if rt, err = common.NewResourceTypes(rTypes, rTypesConfig); err != nil {
logrus.WithError(err).Fatal("new resource types")
}
logrus.Infof("initialized resource types: %+v", rt.Types())
go func(boskos boskosClient) {
for range time.Tick(updateFrequency) {
if err := boskos.SyncAll(); err != nil {
logrus.WithError(err).Warn("SyncAll failed")
}
}
}(boskos)
buffer := setup(boskos, poolSize, bufferSize, janitorClean, extraJanitorFlags)
for {
run(boskos, buffer, rt.Types())
time.Sleep(time.Minute)
}
}
type clean func(resource *common.Resource, extraFlags []string) error
// TODO(amwat): remove this logic when we get rid of --project.
func format(rtype string) string {
splits := strings.Split(rtype, "-")
return splits[len(splits)-1]
}
// Clean by janitor script
func janitorClean(resource *common.Resource, flags []string) error {
args := append([]string{fmt.Sprintf("--%s=%s", format(resource.Type), resource.Name)}, flags...)
logrus.Infof("executing janitor: %s %s", *janitorPath, strings.Join(args, " "))
cmd := exec.Command(*janitorPath, args...)
b, err := cmd.CombinedOutput()
if err != nil {
logrus.WithError(err).Infof("failed to clean up project %s, error info: %s", resource.Name, string(b))
} else {
logrus.Tracef("output from janitor: %s", string(b))
logrus.Infof("successfully cleaned up resource %s", resource.Name)
}
return err
}
type boskosClient interface {
Acquire(rtype string, state string, dest string) (*common.Resource, error)
ReleaseOne(name string, dest string) error
SyncAll() error
}
func setup(c boskosClient, janitorCount int, bufferSize int, cleanFunc clean, flags []string) chan *common.Resource {
buffer := make(chan *common.Resource, bufferSize)
for i := 0; i < janitorCount; i++ {
go janitor(c, buffer, cleanFunc, flags)
}
return buffer
}
func run(c boskosClient, buffer chan<- *common.Resource, rtypes []string) int {
totalAcquire := 0
res := make(map[string]int)
for _, s := range rtypes {
res[s] = 0
}
for {
for r := range res {
if resource, err := c.Acquire(r, common.Dirty, common.Cleaning); err != nil {
logrus.WithError(err).Infof("no available resource %s", r)
totalAcquire += res[r]
delete(res, r)
} else if resource == nil {
// To Sen: I don t understand why this would happen
logrus.Warning("received nil resource")
totalAcquire += res[r]
delete(res, r)
} else {
logrus.Infof("Acquired resources %s of type %s", resource.Name, resource.Type)
buffer <- resource // will block until buffer has a free slot
res[r]++
}
}
if len(res) == 0 {
break
}
}
return totalAcquire
}
// async janitor goroutine
func janitor(c boskosClient, buffer <-chan *common.Resource, fn clean, flags []string) {
for {
resource := <-buffer
dest := common.Free
if err := fn(resource, flags); err != nil {
logrus.WithError(err).Debugf("%s failed!", *janitorPath)
dest = common.Dirty
}
if err := c.ReleaseOne(resource.Name, dest); err != nil {
logrus.WithError(err).Error("boskos release failed!")
}
}
}