/
timer.go
323 lines (295 loc) · 8.21 KB
/
timer.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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
// Copyright 2019 Yunion
//
// 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 models
import (
"context"
"fmt"
"sort"
"strconv"
"strings"
"time"
"yunion.io/x/log"
api "yunion.io/x/onecloud/pkg/apis/compute"
"yunion.io/x/onecloud/pkg/i18n"
"yunion.io/x/onecloud/pkg/util/bitmap"
)
type STimer struct {
// Cycle type
Type string `width:"8" charset:"ascii"`
// 0-59
Minute int `nullable:"false"`
// 0-23
Hour int `nullable:"false"`
// 0-7 1 is Monday 0 is unlimited
WeekDays uint8 `nullable:"false"`
// 0-31 0 is unlimited
MonthDays uint32 `nullable:"false"`
// StartTime represent the start time of this timer
StartTime time.Time
// EndTime represent deadline of this timer
EndTime time.Time
// NextTime represent the time timer should bell
NextTime time.Time `index:"true"`
IsExpired bool
}
// Update will update the SScalingTimer
func (st *STimer) Update(now time.Time) {
if now.IsZero() {
now = time.Now()
}
if !now.Before(st.EndTime) {
st.IsExpired = true
return
}
if now.Before(st.StartTime) {
now = st.StartTime
}
if !st.NextTime.Before(now) {
return
}
newNextTime := time.Date(now.Year(), now.Month(), now.Day(), st.Hour, st.Minute, 0, 0, time.UTC).In(now.Location())
if now.After(newNextTime) {
newNextTime = newNextTime.AddDate(0, 0, 1)
}
switch {
case st.WeekDays != 0:
// week
nowDay, weekdays := int(newNextTime.Weekday()), st.GetWeekDays()
if nowDay == 0 {
nowDay = 7
}
// weekdays[0]+7 is for the case that all time nodes has been missed in this week
weekdays = append(weekdays, weekdays[0]+7)
index := sort.SearchInts(weekdays, nowDay)
newNextTime = newNextTime.AddDate(0, 0, weekdays[index]-nowDay)
case st.MonthDays != 0:
// month
monthdays := st.GetMonthDays()
suitTime := newNextTime
for {
day := suitTime.Day()
index := sort.SearchInts(monthdays, day)
if index == len(monthdays) || monthdays[index] > st.MonthDaySum(suitTime) {
// set suitTime as the first day of next month
suitTime = suitTime.AddDate(0, 1, -suitTime.Day()+1)
continue
}
newNextTime = time.Date(suitTime.Year(), suitTime.Month(), monthdays[index], suitTime.Hour(),
suitTime.Minute(), 0, 0, suitTime.Location())
break
}
default:
// day
}
log.Debugf("The final NextTime: %s", newNextTime)
st.NextTime = newNextTime
if st.NextTime.After(st.EndTime) {
st.IsExpired = true
}
}
// MonthDaySum calculate the number of month's days
func (st *STimer) MonthDaySum(t time.Time) int {
year, month := t.Year(), t.Month()
monthDays := []int{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
if month != 2 {
return monthDays[2]
}
if year%4 != 0 || (year%100 == 0 && year%400 != 0) {
return 28
}
return 29
}
func (st *STimer) GetWeekDays() []int {
return bitmap.Uint2IntArray(uint32(st.WeekDays))
}
func (st *STimer) GetMonthDays() []int {
return bitmap.Uint2IntArray(st.MonthDays)
}
func (st *STimer) SetWeekDays(days []int) {
st.WeekDays = uint8(bitmap.IntArray2Uint(days))
}
func (st *STimer) SetMonthDays(days []int) {
st.MonthDays = bitmap.IntArray2Uint(days)
}
func (st *STimer) TimerDetails() api.TimerDetails {
return api.TimerDetails{ExecTime: st.EndTime}
}
func (st *STimer) CycleTimerDetails() api.CycleTimerDetails {
out := api.CycleTimerDetails{
Minute: st.Minute,
Hour: st.Hour,
WeekDays: st.GetWeekDays(),
MonthDays: st.GetMonthDays(),
StartTime: st.StartTime,
EndTime: st.EndTime,
CycleType: st.Type,
}
return out
}
func checkTimerCreateInput(in api.TimerCreateInput) (api.TimerCreateInput, error) {
now := time.Now()
if now.After(in.ExecTime) {
return in, fmt.Errorf("exec_time is earlier than now")
}
return in, nil
}
var (
timerDescTable = i18n.Table{}
TIMERLANG = "timerLang"
)
func init() {
timerDescTable.Set("timerLang", i18n.NewTableEntry().EN("en").CN("cn"))
}
func (st *STimer) Description(ctx context.Context) string {
lang := timerDescTable.Lookup(ctx, TIMERLANG)
switch lang {
case "en":
return st.descEnglish()
case "cn":
return st.descChinese()
}
return ""
}
var (
wdsCN = []string{"", "一", "二", "三", "四", "五", "六", "日"}
wdsEN = []string{"", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
zone = time.Now().Local().Location()
//zone = time.FixedZone("GMT", 8*3600)
)
func (st *STimer) descChinese() string {
format := "2006-01-02 15:04:05"
var prefix string
switch st.Type {
case api.TIMER_TYPE_ONCE:
return fmt.Sprintf("单次 %s触发", st.StartTime.In(zone).Format(format))
case api.TIMER_TYPE_DAY:
prefix = "每天"
case api.TIMER_TYPE_WEEK:
wds := st.GetWeekDays()
weekDays := make([]string, len(wds))
for i := range wds {
weekDays[i] = fmt.Sprintf("星期%s", wdsCN[wds[i]])
}
prefix = fmt.Sprintf("每周 【%s】", strings.Join(weekDays, "|"))
case api.TIMER_TYPE_MONTH:
mns := st.GetMonthDays()
monthDays := make([]string, len(mns))
for i := range mns {
monthDays[i] = fmt.Sprintf("%d号", mns[i])
}
prefix = fmt.Sprintf("每月 【%s】", strings.Join(monthDays, "|"))
}
return fmt.Sprintf("%s %02d:%02d触发 有效时间为%s至%s", prefix, st.Hour, st.Minute, st.StartTime.In(zone).Format(format), st.EndTime.In(zone).Format(format))
}
func (st *STimer) descEnglish() string {
var detail string
format := "2006-01-02 15:04:05"
switch st.Type {
case api.TIMER_TYPE_ONCE:
return st.EndTime.In(zone).Format(format)
case api.TIMER_TYPE_DAY:
detail = fmt.Sprintf("%d:%d every day", st.Hour, st.Minute)
case api.TIMER_TYPE_WEEK:
detail = st.weekDaysDesc()
case api.TIMER_TYPE_MONTH:
detail = st.monthDaysDesc()
}
if st.EndTime.IsZero() {
return detail
}
return fmt.Sprintf("%s, from %s to %s", detail, st.StartTime.In(zone).Format(format), st.EndTime.In(zone).Format(format))
}
func (st *STimer) weekDaysDesc() string {
if st.WeekDays == 0 {
return ""
}
var desc strings.Builder
wds := st.GetWeekDays()
i := 0
desc.WriteString(fmt.Sprintf("%d:%d every %s", st.Hour, st.Minute, wdsEN[wds[i]]))
for i++; i < len(wds)-1; i++ {
desc.WriteString(", ")
desc.WriteString(wdsEN[wds[i]])
}
if i == len(wds)-1 {
desc.WriteString(" and ")
desc.WriteString(wdsEN[wds[i]])
}
return desc.String()
}
func (st *STimer) monthDaysDesc() string {
if st.MonthDays == 0 {
return ""
}
var desc strings.Builder
mds := st.GetMonthDays()
i := 0
desc.WriteString(fmt.Sprintf("%d:%d on the %d%s", st.Hour, st.Minute, mds[i], st.dateSuffix(mds[i])))
for i++; i < len(mds)-1; i++ {
desc.WriteString(", ")
desc.WriteString(strconv.Itoa(mds[i]))
desc.WriteString(st.dateSuffix(mds[i]))
}
if i == len(mds)-1 {
desc.WriteString(" and ")
desc.WriteString(strconv.Itoa(mds[i]))
desc.WriteString(st.dateSuffix(mds[i]))
}
desc.WriteString(" of each month")
return desc.String()
}
func (st *STimer) dateSuffix(date int) string {
var ret string
switch date {
case 1:
ret = "st"
case 2:
ret = "nd"
case 3:
ret = "rd"
default:
ret = "th"
}
return ret
}
func checkCycleTimerCreateInput(in api.CycleTimerCreateInput) (api.CycleTimerCreateInput, error) {
now := time.Now()
if in.Minute < 0 || in.Minute > 59 {
return in, fmt.Errorf("minute should between 0 and 59")
}
if in.Hour < 0 || in.Hour > 23 {
return in, fmt.Errorf("hour should between 0 and 23")
}
switch in.CycleType {
case api.TIMER_TYPE_DAY:
in.WeekDays = []int{}
in.MonthDays = []int{}
case api.TIMER_TYPE_WEEK:
if len(in.WeekDays) == 0 {
return in, fmt.Errorf("week_days should not be empty")
}
in.MonthDays = []int{}
case api.TIMER_TYPE_MONTH:
if len(in.MonthDays) == 0 {
return in, fmt.Errorf("month_days should not be empty")
}
in.WeekDays = []int{}
default:
return in, fmt.Errorf("unkown cycle type %s", in.CycleType)
}
if now.After(in.EndTime) {
return in, fmt.Errorf("end_time is earlier than now")
}
return in, nil
}