parser.go 12 KB

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