-
Notifications
You must be signed in to change notification settings - Fork 0
/
jobs.go
116 lines (98 loc) · 2.14 KB
/
jobs.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
package fetch
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path"
"strings"
"time"
"cloud.google.com/go/storage"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
)
const (
jobsFile = "jobs.json"
)
type Jobs struct {
Refresh time.Time
Jobs []string
}
func RefreshJobList(ctx context.Context, workdir string) error {
jobs, err := getJobs(ctx)
if err != nil {
return err
}
if err := jobs.storeJobs(workdir); err != nil {
return err
}
return nil
}
func StartPeriodicRefreshJobList(ctx context.Context, workdir string, interval time.Duration) error {
ticker := time.NewTicker(interval)
go func() {
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
if err := RefreshJobList(ctx, workdir); err != nil {
fmt.Printf("Periodic job refresh failed: %+v\n", err)
}
}
}
}()
return nil
}
func getJobs(ctx context.Context) (*Jobs, error) {
client, err := storage.NewClient(ctx, option.WithoutAuthentication())
if err != nil {
return nil, err
}
bucket := client.Bucket(bucketName)
query := &storage.Query{Delimiter: "/", Prefix: bucketRootPath + "/periodic-ci-openshift-release-master"}
query.SetAttrSelection([]string{"Prefix"})
allJobs := Jobs{Refresh: time.Now().UTC()}
it := bucket.Objects(ctx, query)
for {
attrs, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
return nil, err
}
if attrs.Prefix == "" {
continue
}
splPrefix := strings.Split(attrs.Prefix, "/")
allJobs.Jobs = append(allJobs.Jobs, splPrefix[len(splPrefix)-2])
}
return &allJobs, nil
}
func (jobs *Jobs) storeJobs(workdir string) error {
if err := os.MkdirAll(workdir, os.ModePerm); err != nil {
return err
}
b, err := json.MarshalIndent(jobs, "", " ")
if err != nil {
return err
}
err = ioutil.WriteFile(path.Join(workdir, jobsFile), b, 0644)
if err != nil {
return err
}
return nil
}
func LoadJobsFromDisk(workdir string) (*Jobs, error) {
b, err := ioutil.ReadFile(path.Join(workdir, jobsFile))
if err != nil {
return nil, err
}
jobs := &Jobs{}
if err := json.Unmarshal(b, jobs); err != nil {
return nil, err
}
return jobs, nil
}