forked from snapcore/snapd
/
warning.go
292 lines (255 loc) · 7.32 KB
/
warning.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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2018 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package state
import (
"encoding/json"
"errors"
"fmt"
"sort"
"strings"
"time"
"github.com/snapcore/snapd/logger"
)
var (
DefaultRepeatAfter = time.Hour * 24
DefaultExpireAfter = time.Hour * 24 * 28
errNoWarningMessage = errors.New("warning has no message")
errBadWarningMessage = errors.New("malformed warning message")
errNoWarningFirstAdded = errors.New("warning has no first-added timestamp")
errNoWarningExpireAfter = errors.New("warning has no expire-after duration")
errNoWarningRepeatAfter = errors.New("warning has no repeat-after duration")
)
type jsonWarning struct {
Message string `json:"message"`
FirstAdded time.Time `json:"first-added"`
LastAdded time.Time `json:"last-added"`
LastShown *time.Time `json:"last-shown,omitempty"`
ExpireAfter string `json:"expire-after,omitempty"`
RepeatAfter string `json:"repeat-after,omitempty"`
}
type Warning struct {
// the warning text itself. Only one of these in the system at a time.
message string
// the first time one of these messages was created
firstAdded time.Time
// the last time one of these was created
lastAdded time.Time
// the last time one of these was shown to the user
lastShown time.Time
// how much time since one of these was last added should we drop the message
expireAfter time.Duration
// how much time since one of these was last shown should we repeat it
repeatAfter time.Duration
}
func (w *Warning) String() string {
return w.message
}
func (w *Warning) MarshalJSON() ([]byte, error) {
jw := jsonWarning{
Message: w.message,
FirstAdded: w.firstAdded,
LastAdded: w.lastAdded,
ExpireAfter: w.expireAfter.String(),
RepeatAfter: w.repeatAfter.String(),
}
if !w.lastShown.IsZero() {
jw.LastShown = &w.lastShown
}
return json.Marshal(jw)
}
func (w *Warning) UnmarshalJSON(data []byte) error {
var jw jsonWarning
err := json.Unmarshal(data, &jw)
if err != nil {
return err
}
w.message = jw.Message
w.firstAdded = jw.FirstAdded
w.lastAdded = jw.LastAdded
if jw.LastShown != nil {
w.lastShown = *jw.LastShown
}
if jw.ExpireAfter != "" {
w.expireAfter, err = time.ParseDuration(jw.ExpireAfter)
if err != nil {
return err
}
}
if jw.RepeatAfter != "" {
w.repeatAfter, err = time.ParseDuration(jw.RepeatAfter)
if err != nil {
return err
}
}
return w.validate()
}
func (w *Warning) validate() (e error) {
if w.message == "" {
return errNoWarningMessage
}
if strings.TrimSpace(w.message) != w.message {
return errBadWarningMessage
}
if w.firstAdded.IsZero() {
return errNoWarningFirstAdded
}
if w.expireAfter == 0 {
return errNoWarningExpireAfter
}
if w.repeatAfter == 0 {
return errNoWarningRepeatAfter
}
return nil
}
func (w *Warning) ExpiredBefore(now time.Time) bool {
return w.lastAdded.Add(w.expireAfter).Before(now)
}
func (w *Warning) ShowAfter(t time.Time) bool {
if w.lastShown.IsZero() {
// warning was never shown before; was it added after the cutoff?
return !w.firstAdded.After(t)
}
return w.lastShown.Add(w.repeatAfter).Before(t)
}
// flattenWarning loops over the warnings map, and returns all
// non-expired warnings therein as a flat list, for serialising.
// Call with the lock held.
func (s *State) flattenWarnings() []*Warning {
now := time.Now()
flat := make([]*Warning, 0, len(s.warnings))
for _, w := range s.warnings {
if w.ExpiredBefore(now) {
continue
}
flat = append(flat, w)
}
return flat
}
// unflattenWarnings takes a flat list of warnings and replaces the
// warning map with them, ignoring expired warnings in the process.
// Call with the lock held.
func (s *State) unflattenWarnings(flat []*Warning) {
now := time.Now()
s.warnings = make(map[string]*Warning, len(flat))
for _, w := range flat {
if w.ExpiredBefore(now) {
continue
}
s.warnings[w.message] = w
}
}
// Warnf records a warning: if it's the first Warning with this
// message it'll be added (with its firstAdded and lastAdded set to the
// current time), otherwise the existing one will have its lastAdded
// updated.
func (s *State) Warnf(template string, args ...interface{}) {
var message string
if len(args) > 0 {
message = fmt.Sprintf(template, args...)
} else {
message = template
}
s.addWarning(Warning{
message: message,
expireAfter: DefaultExpireAfter,
repeatAfter: DefaultRepeatAfter,
}, time.Now().UTC())
}
func (s *State) addWarning(w Warning, t time.Time) {
s.writing()
if s.warnings[w.message] == nil {
w.firstAdded = t
if err := w.validate(); err != nil {
// programming error!
logger.Panicf("internal error, please report: attempted to add invalid warning: %v", err)
return
}
s.warnings[w.message] = &w
}
s.warnings[w.message].lastAdded = t
}
type byLastAdded []*Warning
func (a byLastAdded) Len() int { return len(a) }
func (a byLastAdded) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a byLastAdded) Less(i, j int) bool { return a[i].lastAdded.Before(a[j].lastAdded) }
// AllWarnings returns all the warnings in the system, whether they're
// due to be shown or not. They'll be sorted by lastAdded.
func (s *State) AllWarnings() []*Warning {
s.reading()
all := s.flattenWarnings()
sort.Sort(byLastAdded(all))
return all
}
// OkayWarnings marks warnings that were showable at the given time as shown.
func (s *State) OkayWarnings(t time.Time) int {
t = t.UTC()
s.writing()
n := 0
for _, w := range s.warnings {
if w.ShowAfter(t) {
w.lastShown = t
n++
}
}
return n
}
// PendingWarnings returns the list of warnings to show the user, sorted by
// lastAdded, and a timestamp than can be used to refer to these warnings.
//
// Warnings to show to the user are those that have not been shown before,
// or that have been shown earlier than repeatAfter ago.
func (s *State) PendingWarnings() ([]*Warning, time.Time) {
s.reading()
now := time.Now().UTC()
var toShow []*Warning
for _, w := range s.warnings {
if !w.ShowAfter(now) {
continue
}
toShow = append(toShow, w)
}
sort.Sort(byLastAdded(toShow))
return toShow, now
}
// WarningsSummary returns the number of warnings that are ready to be
// shown to the user, and the timestamp of the most recently added
// warning (useful for silencing the warning alerts, and OKing the
// returned warnings).
func (s *State) WarningsSummary() (int, time.Time) {
s.reading()
now := time.Now().UTC()
var last time.Time
var n int
for _, w := range s.warnings {
if w.ShowAfter(now) {
n++
if w.lastAdded.After(last) {
last = w.lastAdded
}
}
}
return n, last
}
// UnshowAllWarnings clears the lastShown timestamp from all the
// warnings. For use in debugging.
func (s *State) UnshowAllWarnings() {
s.writing()
for _, w := range s.warnings {
w.lastShown = time.Time{}
}
}