/
persist.go
160 lines (141 loc) · 3.98 KB
/
persist.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
/*
Copyright 2022 The TestGrid 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 queue
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"cloud.google.com/go/storage"
"github.com/GoogleCloudPlatform/testgrid/util/gcs"
"github.com/sirupsen/logrus"
)
// PersistClient contains interfaces for reading from and writing to a Path.
type PersistClient interface {
gcs.Uploader
gcs.Opener
}
// Fixer will adjust the queue until the context expires.
type Fixer func(context.Context, *Queue) error
// FixPersistent persists the queue to the remote path every tick.
//
// The first time it will load the state. Thereafter it will save the state.
// This includes restarts due to expiring contexts -- it will just load once.
func FixPersistent(logr logrus.FieldLogger, client PersistClient, path gcs.Path, tick <-chan time.Time) Fixer {
var shouldSave bool
log := logr.WithField("path", path)
return func(parentCtx context.Context, q *Queue) error {
log.Debug("Using persistent state")
ctx, cancel := context.WithCancel(parentCtx)
defer cancel()
go func() { // allow a grace period for reads/writes
select {
case <-ctx.Done():
return
case <-parentCtx.Done():
timer := time.NewTimer(5 * time.Second)
select {
case <-ctx.Done():
if !timer.Stop() {
<-timer.C
}
return
case <-timer.C:
cancel()
return
}
}
}()
tryLoad := func() error {
reader, attrs, err := client.Open(ctx, path)
if errors.Is(err, storage.ErrObjectNotExist) {
log.Info("Previous persistent queue state does not exist.")
return nil
}
if err != nil {
return fmt.Errorf("open: %w", err)
}
defer reader.Close()
dec := json.NewDecoder(reader)
var whens map[string]time.Time
if err := dec.Decode(&whens); err != nil {
return fmt.Errorf("decode: %v", err)
}
current := q.Current()
for name := range whens {
if _, ok := current[name]; ok {
continue
}
delete(whens, name)
}
log.WithField("from", attrs.LastModified).Info("Loaded previous state, syncing queue.")
if err := q.FixAll(whens, false); err != nil {
return fmt.Errorf("fix all: %v", err)
}
return nil
}
logSave := true
trySave := func() error {
currently := q.Current()
buf, err := json.MarshalIndent(currently, "", " ")
if err != nil {
return fmt.Errorf("marshal: %v", err)
}
attrs, err := client.Upload(ctx, path, buf, gcs.DefaultACL, gcs.NoCache)
if err == nil && logSave {
logSave = false
log.WithField("updated", attrs.Updated).Info("Wrote persistent state")
}
return err
}
for {
select {
case <-parentCtx.Done():
log.Debug("Stopped syncing persistent state")
return parentCtx.Err()
case <-tick:
}
if shouldSave {
log.Trace("Saving persistent state...")
if err := trySave(); err != nil {
log := log.WithError(err)
var chirp func(...interface{})
if errors.Is(err, context.Canceled) {
chirp = log.Debug
} else {
chirp = log.Warning
}
chirp("Failed to save persistent state.")
continue
}
log.Debug("Saved persistent state.")
} else {
log.Trace("Loading persistent state...")
if err := tryLoad(); err != nil {
log := log.WithError(err)
var chirp func(...interface{})
if errors.Is(err, context.Canceled) {
chirp = log.Debug
} else {
chirp = log.Warning
}
chirp("Failed to load persistent state.")
continue
}
shouldSave = true
log.Debug("Loaded persistent state.")
}
}
}
}