parser.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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. // expandOptionalFields returns fields with any optional fields added in at
  197. // their default value, if not provided.
  198. //
  199. // It panics if the input does not fulfill the following precondition:
  200. // 1. (# options fields) - (1 optional field) <= len(fields) <= (# options fields)
  201. // 2. Any optional fields have had their field added.
  202. // For example, options&SecondOptional implies options&Second)
  203. func expandOptionalFields(fields []string, options ParseOption) []string {
  204. expectedFields := 0
  205. for _, place := range places {
  206. if options&place > 0 {
  207. expectedFields++
  208. }
  209. }
  210. switch {
  211. case len(fields) == expectedFields:
  212. return fields
  213. case len(fields) == expectedFields-1:
  214. switch {
  215. case options&DowOptional > 0:
  216. return append(fields, defaults[5]) // TODO: improve access to default
  217. case options&SecondOptional > 0:
  218. return append([]string{defaults[0]}, fields...)
  219. }
  220. }
  221. panic(fmt.Errorf("expected %d fields, got %d", expectedFields, len(fields)))
  222. }
  223. var standardParser = NewParser(
  224. Minute | Hour | Dom | Month | Dow | Descriptor,
  225. )
  226. // ParseStandard returns a new crontab schedule representing the given standardSpec
  227. // (https://en.wikipedia.org/wiki/Cron). It differs from Parse requiring to always
  228. // pass 5 entries representing: minute, hour, day of month, month and day of week,
  229. // in that order. It returns a descriptive error if the spec is not valid.
  230. //
  231. // It accepts
  232. // - Standard crontab specs, e.g. "* * * * ?"
  233. // - Descriptors, e.g. "@midnight", "@every 1h30m"
  234. func ParseStandard(standardSpec string) (Schedule, error) {
  235. return standardParser.Parse(standardSpec)
  236. }
  237. // getField returns an Int with the bits set representing all of the times that
  238. // the field represents or error parsing field value. A "field" is a comma-separated
  239. // list of "ranges".
  240. func getField(field string, r bounds) (uint64, error) {
  241. var bits uint64
  242. ranges := strings.FieldsFunc(field, func(r rune) bool { return r == ',' })
  243. for _, expr := range ranges {
  244. bit, err := getRange(expr, r)
  245. if err != nil {
  246. return bits, err
  247. }
  248. bits |= bit
  249. }
  250. return bits, nil
  251. }
  252. // getRange returns the bits indicated by the given expression:
  253. // number | number "-" number [ "/" number ]
  254. // or error parsing range.
  255. func getRange(expr string, r bounds) (uint64, error) {
  256. var (
  257. start, end, step uint
  258. rangeAndStep = strings.Split(expr, "/")
  259. lowAndHigh = strings.Split(rangeAndStep[0], "-")
  260. singleDigit = len(lowAndHigh) == 1
  261. err error
  262. )
  263. var extra uint64
  264. if lowAndHigh[0] == "*" || lowAndHigh[0] == "?" {
  265. start = r.min
  266. end = r.max
  267. extra = starBit
  268. } else {
  269. start, err = parseIntOrName(lowAndHigh[0], r.names)
  270. if err != nil {
  271. return 0, err
  272. }
  273. switch len(lowAndHigh) {
  274. case 1:
  275. end = start
  276. case 2:
  277. end, err = parseIntOrName(lowAndHigh[1], r.names)
  278. if err != nil {
  279. return 0, err
  280. }
  281. default:
  282. return 0, fmt.Errorf("too many hyphens: %s", expr)
  283. }
  284. }
  285. switch len(rangeAndStep) {
  286. case 1:
  287. step = 1
  288. case 2:
  289. step, err = mustParseInt(rangeAndStep[1])
  290. if err != nil {
  291. return 0, err
  292. }
  293. // Special handling: "N/step" means "N-max/step".
  294. if singleDigit {
  295. end = r.max
  296. }
  297. if step > 1 {
  298. extra = 0
  299. }
  300. default:
  301. return 0, fmt.Errorf("too many slashes: %s", expr)
  302. }
  303. if start < r.min {
  304. return 0, fmt.Errorf("beginning of range (%d) below minimum (%d): %s", start, r.min, expr)
  305. }
  306. if end > r.max {
  307. return 0, fmt.Errorf("end of range (%d) above maximum (%d): %s", end, r.max, expr)
  308. }
  309. if start > end {
  310. return 0, fmt.Errorf("beginning of range (%d) beyond end of range (%d): %s", start, end, expr)
  311. }
  312. if step == 0 {
  313. return 0, fmt.Errorf("step of range should be a positive number: %s", expr)
  314. }
  315. return getBits(start, end, step) | extra, nil
  316. }
  317. // parseIntOrName returns the (possibly-named) integer contained in expr.
  318. func parseIntOrName(expr string, names map[string]uint) (uint, error) {
  319. if names != nil {
  320. if namedInt, ok := names[strings.ToLower(expr)]; ok {
  321. return namedInt, nil
  322. }
  323. }
  324. return mustParseInt(expr)
  325. }
  326. // mustParseInt parses the given expression as an int or returns an error.
  327. func mustParseInt(expr string) (uint, error) {
  328. num, err := strconv.Atoi(expr)
  329. if err != nil {
  330. return 0, fmt.Errorf("failed to parse int from %s: %s", expr, err)
  331. }
  332. if num < 0 {
  333. return 0, fmt.Errorf("negative number (%d) not allowed: %s", num, expr)
  334. }
  335. return uint(num), nil
  336. }
  337. // getBits sets all bits in the range [min, max], modulo the given step size.
  338. func getBits(min, max, step uint) uint64 {
  339. var bits uint64
  340. // If step is 1, use shifts.
  341. if step == 1 {
  342. return ^(math.MaxUint64 << (max + 1)) & (math.MaxUint64 << min)
  343. }
  344. // Else, use a simple loop.
  345. for i := min; i <= max; i += step {
  346. bits |= 1 << i
  347. }
  348. return bits
  349. }
  350. // all returns all bits within the given bounds. (plus the star bit)
  351. func all(r bounds) uint64 {
  352. return getBits(r.min, r.max, 1) | starBit
  353. }
  354. // parseDescriptor returns a predefined schedule for the expression, or error if none matches.
  355. func parseDescriptor(descriptor string, loc *time.Location) (Schedule, error) {
  356. switch descriptor {
  357. case "@yearly", "@annually":
  358. return &SpecSchedule{
  359. Second: 1 << seconds.min,
  360. Minute: 1 << minutes.min,
  361. Hour: 1 << hours.min,
  362. Dom: 1 << dom.min,
  363. Month: 1 << months.min,
  364. Dow: all(dow),
  365. Location: loc,
  366. }, nil
  367. case "@monthly":
  368. return &SpecSchedule{
  369. Second: 1 << seconds.min,
  370. Minute: 1 << minutes.min,
  371. Hour: 1 << hours.min,
  372. Dom: 1 << dom.min,
  373. Month: all(months),
  374. Dow: all(dow),
  375. Location: loc,
  376. }, nil
  377. case "@weekly":
  378. return &SpecSchedule{
  379. Second: 1 << seconds.min,
  380. Minute: 1 << minutes.min,
  381. Hour: 1 << hours.min,
  382. Dom: all(dom),
  383. Month: all(months),
  384. Dow: 1 << dow.min,
  385. Location: loc,
  386. }, nil
  387. case "@daily", "@midnight":
  388. return &SpecSchedule{
  389. Second: 1 << seconds.min,
  390. Minute: 1 << minutes.min,
  391. Hour: 1 << hours.min,
  392. Dom: all(dom),
  393. Month: all(months),
  394. Dow: all(dow),
  395. Location: loc,
  396. }, nil
  397. case "@hourly":
  398. return &SpecSchedule{
  399. Second: 1 << seconds.min,
  400. Minute: 1 << minutes.min,
  401. Hour: all(hours),
  402. Dom: all(dom),
  403. Month: all(months),
  404. Dow: all(dow),
  405. Location: loc,
  406. }, nil
  407. }
  408. const every = "@every "
  409. if strings.HasPrefix(descriptor, every) {
  410. duration, err := time.ParseDuration(descriptor[len(every):])
  411. if err != nil {
  412. return nil, fmt.Errorf("failed to parse duration %s: %s", descriptor, err)
  413. }
  414. return Every(duration), nil
  415. }
  416. return nil, fmt.Errorf("unrecognized descriptor: %s", descriptor)
  417. }