parser.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. package cron
  2. import (
  3. "math"
  4. "strconv"
  5. "strings"
  6. "time"
  7. "github.com/pkg/errors"
  8. )
  9. // Configuration options for creating a parser. Most options specify which
  10. // fields should be included, while others enable features. If a field is not
  11. // included the parser will assume a default value. These options do not change
  12. // the order fields are parse in.
  13. type ParseOption int
  14. const (
  15. Second ParseOption = 1 << iota // Seconds field, default 0
  16. SecondOptional // Optional seconds field, default 0
  17. Minute // Minutes field, default 0
  18. Hour // Hours field, default 0
  19. Dom // Day of month field, default *
  20. Month // Month field, default *
  21. Dow // Day of week field, default *
  22. DowOptional // Optional day of week field, default *
  23. Descriptor // Allow descriptors such as @monthly, @weekly, etc.
  24. )
  25. var places = []ParseOption{
  26. Second,
  27. Minute,
  28. Hour,
  29. Dom,
  30. Month,
  31. Dow,
  32. }
  33. var defaults = []string{
  34. "0",
  35. "0",
  36. "0",
  37. "*",
  38. "*",
  39. "*",
  40. }
  41. // A custom Parser that can be configured.
  42. type Parser struct {
  43. options ParseOption
  44. }
  45. // NewParser creates a Parser with custom options.
  46. //
  47. // It panics if more than one Optional is given, since it would be impossible to
  48. // correctly infer which optional is provided or missing in general.
  49. //
  50. // Examples
  51. //
  52. // // Standard parser without descriptors
  53. // specParser := NewParser(Minute | Hour | Dom | Month | Dow)
  54. // sched, err := specParser.Parse("0 0 15 */3 *")
  55. //
  56. // // Same as above, just excludes time fields
  57. // specParser := NewParser(Dom | Month | Dow)
  58. // sched, err := specParser.Parse("15 */3 *")
  59. //
  60. // // Same as above, just makes Dow optional
  61. // specParser := NewParser(Dom | Month | DowOptional)
  62. // sched, err := specParser.Parse("15 */3")
  63. func NewParser(options ParseOption) Parser {
  64. optionals := 0
  65. if options&DowOptional > 0 {
  66. optionals++
  67. }
  68. if options&SecondOptional > 0 {
  69. optionals++
  70. }
  71. if optionals > 1 {
  72. panic("multiple optionals may not be configured")
  73. }
  74. return Parser{options}
  75. }
  76. // Parse returns a new crontab schedule representing the given spec.
  77. // It returns a descriptive error if the spec is not valid.
  78. // It accepts crontab specs and features configured by NewParser.
  79. func (p Parser) Parse(spec string) (Schedule, error) {
  80. if len(spec) == 0 {
  81. return nil, errors.New("empty spec string")
  82. }
  83. // Extract timezone if present
  84. var loc = time.Local
  85. if strings.HasPrefix(spec, "TZ=") || strings.HasPrefix(spec, "CRON_TZ=") {
  86. var err error
  87. i := strings.Index(spec, " ")
  88. eq := strings.Index(spec, "=")
  89. if loc, err = time.LoadLocation(spec[eq+1 : i]); err != nil {
  90. return nil, errors.Wrap(err, "provided bad location")
  91. }
  92. spec = strings.TrimSpace(spec[i:])
  93. }
  94. // Handle named schedules (descriptors), if configured
  95. if strings.HasPrefix(spec, "@") {
  96. if p.options&Descriptor == 0 {
  97. return nil, errors.New("descriptors not enabled")
  98. }
  99. return parseDescriptor(spec, loc)
  100. }
  101. // Split on whitespace.
  102. fields := strings.Fields(spec)
  103. // Validate & fill in any omitted or optional fields
  104. var err error
  105. fields, err = normalizeFields(fields, p.options)
  106. if err != nil {
  107. return nil, err
  108. }
  109. field := func(field string, r bounds) uint64 {
  110. if err != nil {
  111. return 0
  112. }
  113. var bits uint64
  114. bits, err = getField(field, r)
  115. return bits
  116. }
  117. var (
  118. second = field(fields[0], seconds)
  119. minute = field(fields[1], minutes)
  120. hour = field(fields[2], hours)
  121. dayofmonth = field(fields[3], dom)
  122. month = field(fields[4], months)
  123. dayofweek = field(fields[5], dow)
  124. )
  125. if err != nil {
  126. return nil, err
  127. }
  128. return &SpecSchedule{
  129. Second: second,
  130. Minute: minute,
  131. Hour: hour,
  132. Dom: dayofmonth,
  133. Month: month,
  134. Dow: dayofweek,
  135. Location: loc,
  136. }, nil
  137. }
  138. // normalizeFields takes a subset set of the time fields and returns the full set
  139. // with defaults (zeroes) populated for unset fields.
  140. //
  141. // As part of performing this function, it also validates that the provided
  142. // fields are compatible with the configured options.
  143. func normalizeFields(fields []string, options ParseOption) ([]string, error) {
  144. // Validate optionals & add their field to options
  145. optionals := 0
  146. if options&SecondOptional > 0 {
  147. options |= Second
  148. optionals++
  149. }
  150. if options&DowOptional > 0 {
  151. options |= Dow
  152. optionals++
  153. }
  154. if optionals > 1 {
  155. return nil, errors.New("multiple optionals may not be configured")
  156. }
  157. // Figure out how many fields we need
  158. max := 0
  159. for _, place := range places {
  160. if options&place > 0 {
  161. max++
  162. }
  163. }
  164. min := max - optionals
  165. // Validate number of fields
  166. if count := len(fields); count < min || count > max {
  167. if min == max {
  168. return nil, errors.New("incorrect number of fields")
  169. }
  170. return nil, errors.New("incorrect number of fields, expected " + strconv.Itoa(min) + "-" + strconv.Itoa(max))
  171. }
  172. // Populate the optional field if not provided
  173. if min < max && len(fields) == min {
  174. switch {
  175. case options&DowOptional > 0:
  176. fields = append(fields, defaults[5]) // TODO: improve access to default
  177. case options&SecondOptional > 0:
  178. fields = append([]string{defaults[0]}, fields...)
  179. default:
  180. return nil, errors.New("unexpected optional field")
  181. }
  182. }
  183. // Populate all fields not part of options with their defaults
  184. n := 0
  185. expandedFields := make([]string, len(places))
  186. copy(expandedFields, defaults)
  187. for i, place := range places {
  188. if options&place > 0 {
  189. expandedFields[i] = fields[n]
  190. n++
  191. }
  192. }
  193. return expandedFields, nil
  194. }
  195. var standardParser = NewParser(
  196. Minute | Hour | Dom | Month | Dow | Descriptor,
  197. )
  198. // ParseStandard returns a new crontab schedule representing the given
  199. // standardSpec (https://en.wikipedia.org/wiki/Cron). It requires 5 entries
  200. // representing: minute, hour, day of month, month and day of week, in that
  201. // order. It returns a descriptive error if the spec is not valid.
  202. //
  203. // It accepts
  204. // - Standard crontab specs, e.g. "* * * * ?"
  205. // - Descriptors, e.g. "@midnight", "@every 1h30m"
  206. func ParseStandard(standardSpec string) (Schedule, error) {
  207. return standardParser.Parse(standardSpec)
  208. }
  209. // getField returns an Int with the bits set representing all of the times that
  210. // the field represents or error parsing field value. A "field" is a comma-separated
  211. // list of "ranges".
  212. func getField(field string, r bounds) (uint64, error) {
  213. var bits uint64
  214. ranges := strings.FieldsFunc(field, func(r rune) bool { return r == ',' })
  215. for _, expr := range ranges {
  216. bit, err := getRange(expr, r)
  217. if err != nil {
  218. return bits, err
  219. }
  220. bits |= bit
  221. }
  222. return bits, nil
  223. }
  224. // getRange returns the bits indicated by the given expression:
  225. //
  226. // number | number "-" number [ "/" number ]
  227. //
  228. // or error parsing range.
  229. func getRange(expr string, r bounds) (uint64, error) {
  230. var (
  231. start, end, step uint
  232. rangeAndStep = strings.Split(expr, "/")
  233. lowAndHigh = strings.Split(rangeAndStep[0], "-")
  234. singleDigit = len(lowAndHigh) == 1
  235. err error
  236. )
  237. var extra uint64
  238. if lowAndHigh[0] == "*" || lowAndHigh[0] == "?" {
  239. start = r.min
  240. end = r.max
  241. extra = starBit
  242. } else {
  243. start, err = parseIntOrName(lowAndHigh[0], r.names)
  244. if err != nil {
  245. return 0, err
  246. }
  247. switch len(lowAndHigh) {
  248. case 1:
  249. end = start
  250. case 2:
  251. end, err = parseIntOrName(lowAndHigh[1], r.names)
  252. if err != nil {
  253. return 0, err
  254. }
  255. default:
  256. return 0, errors.New("too many hyphens: " + expr)
  257. }
  258. }
  259. switch len(rangeAndStep) {
  260. case 1:
  261. step = 1
  262. case 2:
  263. step, err = mustParseInt(rangeAndStep[1])
  264. if err != nil {
  265. return 0, err
  266. }
  267. // Special handling: "N/step" means "N-max/step".
  268. if singleDigit {
  269. end = r.max
  270. }
  271. if step > 1 {
  272. extra = 0
  273. }
  274. default:
  275. return 0, errors.New("too many slashes: " + expr)
  276. }
  277. if start < r.min {
  278. return 0, errors.New("beginning of range below minimum: " + expr)
  279. }
  280. if end > r.max {
  281. return 0, errors.New("end of range above maximum: " + expr)
  282. }
  283. if start > end {
  284. return 0, errors.New("beginning of range after end: " + expr)
  285. }
  286. if step == 0 {
  287. return 0, errors.New("step cannot be zero: " + expr)
  288. }
  289. return getBits(start, end, step) | extra, nil
  290. }
  291. // parseIntOrName returns the (possibly-named) integer contained in expr.
  292. func parseIntOrName(expr string, names map[string]uint) (uint, error) {
  293. if names != nil {
  294. if namedInt, ok := names[strings.ToLower(expr)]; ok {
  295. return namedInt, nil
  296. }
  297. }
  298. return mustParseInt(expr)
  299. }
  300. // mustParseInt parses the given expression as an int or returns an error.
  301. func mustParseInt(expr string) (uint, error) {
  302. num, err := strconv.Atoi(expr)
  303. if err != nil {
  304. return 0, errors.Wrap(err, "failed to parse number")
  305. }
  306. if num < 0 {
  307. return 0, errors.New("number must be positive")
  308. }
  309. return uint(num), nil
  310. }
  311. // getBits sets all bits in the range [min, max], modulo the given step size.
  312. func getBits(min, max, step uint) uint64 {
  313. var bits uint64
  314. // If step is 1, use shifts.
  315. if step == 1 {
  316. return ^(math.MaxUint64 << (max + 1)) & (math.MaxUint64 << min)
  317. }
  318. // Else, use a simple loop.
  319. for i := min; i <= max; i += step {
  320. bits |= 1 << i
  321. }
  322. return bits
  323. }
  324. // all returns all bits within the given bounds.
  325. func all(r bounds) uint64 {
  326. return getBits(r.min, r.max, 1) | starBit
  327. }
  328. // parseDescriptor returns a predefined schedule for the expression, or error if none matches.
  329. func parseDescriptor(descriptor string, loc *time.Location) (Schedule, error) {
  330. switch descriptor {
  331. case "@yearly", "@annually":
  332. return &SpecSchedule{
  333. Second: 1 << seconds.min,
  334. Minute: 1 << minutes.min,
  335. Hour: 1 << hours.min,
  336. Dom: 1 << dom.min,
  337. Month: 1 << months.min,
  338. Dow: all(dow),
  339. Location: loc,
  340. }, nil
  341. case "@monthly":
  342. return &SpecSchedule{
  343. Second: 1 << seconds.min,
  344. Minute: 1 << minutes.min,
  345. Hour: 1 << hours.min,
  346. Dom: 1 << dom.min,
  347. Month: all(months),
  348. Dow: all(dow),
  349. Location: loc,
  350. }, nil
  351. case "@weekly":
  352. return &SpecSchedule{
  353. Second: 1 << seconds.min,
  354. Minute: 1 << minutes.min,
  355. Hour: 1 << hours.min,
  356. Dom: all(dom),
  357. Month: all(months),
  358. Dow: 1 << dow.min,
  359. Location: loc,
  360. }, nil
  361. case "@daily", "@midnight":
  362. return &SpecSchedule{
  363. Second: 1 << seconds.min,
  364. Minute: 1 << minutes.min,
  365. Hour: 1 << hours.min,
  366. Dom: all(dom),
  367. Month: all(months),
  368. Dow: all(dow),
  369. Location: loc,
  370. }, nil
  371. case "@hourly":
  372. return &SpecSchedule{
  373. Second: 1 << seconds.min,
  374. Minute: 1 << minutes.min,
  375. Hour: all(hours),
  376. Dom: all(dom),
  377. Month: all(months),
  378. Dow: all(dow),
  379. Location: loc,
  380. }, nil
  381. }
  382. const every = "@every "
  383. if strings.HasPrefix(descriptor, every) {
  384. duration, err := time.ParseDuration(descriptor[len(every):])
  385. if err != nil {
  386. return nil, errors.Wrap(err, "failed to parse duration")
  387. }
  388. return Every(duration), nil
  389. }
  390. return nil, errors.New("unrecognized descriptor: " + descriptor)
  391. }