parser.go 11 KB

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