parser.go 12 KB

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