parser.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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. Minute // Minutes field, default 0
  17. Hour // Hours field, default 0
  18. Dom // Day of month field, default *
  19. Month // Month field, default *
  20. Dow // Day of week field, default *
  21. DowOptional // Optional day of week field, default *
  22. Descriptor // Allow descriptors such as @monthly, @weekly, etc.
  23. )
  24. var places = []ParseOption{
  25. Second,
  26. Minute,
  27. Hour,
  28. Dom,
  29. Month,
  30. Dow,
  31. }
  32. var defaults = []string{
  33. "0",
  34. "0",
  35. "0",
  36. "*",
  37. "*",
  38. "*",
  39. }
  40. // A custom Parser that can be configured.
  41. type Parser struct {
  42. options ParseOption
  43. optionals int
  44. }
  45. // Creates a custom Parser with custom options.
  46. //
  47. // // Standard parser without descriptors
  48. // specParser := NewParser(Minute | Hour | Dom | Month | Dow)
  49. // sched, err := specParser.Parse("0 0 15 */3 *")
  50. //
  51. // // Same as above, just excludes time fields
  52. // subsParser := NewParser(Dom | Month | Dow)
  53. // sched, err := specParser.Parse("15 */3 *")
  54. //
  55. // // Same as above, just makes Dow optional
  56. // subsParser := NewParser(Dom | Month | DowOptional)
  57. // sched, err := specParser.Parse("15 */3")
  58. //
  59. func NewParser(options ParseOption) Parser {
  60. optionals := 0
  61. if options&DowOptional > 0 {
  62. options |= Dow
  63. optionals++
  64. }
  65. return Parser{options, optionals}
  66. }
  67. // Parse returns a new crontab schedule representing the given spec.
  68. // It returns a descriptive error if the spec is not valid.
  69. // It accepts crontab specs and features configured by NewParser.
  70. func (p Parser) Parse(spec string) (Schedule, error) {
  71. if len(spec) == 0 {
  72. return nil, fmt.Errorf("Empty spec string")
  73. }
  74. // Extract timezone if present
  75. var loc = time.Local
  76. if strings.HasPrefix(spec, "TZ=") {
  77. var err error
  78. i := strings.Index(spec, " ")
  79. if loc, err = time.LoadLocation(spec[3:i]); err != nil {
  80. return nil, fmt.Errorf("Provided bad location %s: %v", spec[3:i], err)
  81. }
  82. spec = strings.TrimSpace(spec[i:])
  83. }
  84. // Handle named schedules (descriptors)
  85. if strings.HasPrefix(spec, "@") {
  86. return parseDescriptor(spec, loc)
  87. }
  88. // Figure out how many fields we need
  89. max := 0
  90. for _, place := range places {
  91. if p.options&place > 0 {
  92. max++
  93. }
  94. }
  95. min := max - p.optionals
  96. // Split on whitespace.
  97. fields := strings.Fields(spec)
  98. // Validate number of fields
  99. if count := len(fields); count < min || count > max {
  100. if min == max {
  101. return nil, fmt.Errorf("Expected exactly %d fields, found %d: %s", min, count, spec)
  102. }
  103. return nil, fmt.Errorf("Expected %d to %d fields, found %d: %s", min, max, count, spec)
  104. }
  105. // Fill in missing fields
  106. fields = expandFields(fields, p.options)
  107. var err error
  108. field := func(field string, r bounds) uint64 {
  109. if err != nil {
  110. return 0
  111. }
  112. var bits uint64
  113. bits, err = getField(field, r)
  114. return bits
  115. }
  116. var (
  117. second = field(fields[0], seconds)
  118. minute = field(fields[1], minutes)
  119. hour = field(fields[2], hours)
  120. dayofmonth = field(fields[3], dom)
  121. month = field(fields[4], months)
  122. dayofweek = field(fields[5], dow)
  123. )
  124. if err != nil {
  125. return nil, err
  126. }
  127. return &SpecSchedule{
  128. Second: second,
  129. Minute: minute,
  130. Hour: hour,
  131. Dom: dayofmonth,
  132. Month: month,
  133. Dow: dayofweek,
  134. Location: loc,
  135. }, nil
  136. }
  137. func expandFields(fields []string, options ParseOption) []string {
  138. n := 0
  139. count := len(fields)
  140. expFields := make([]string, len(places))
  141. copy(expFields, defaults)
  142. for i, place := range places {
  143. if options&place > 0 {
  144. expFields[i] = fields[n]
  145. n++
  146. }
  147. if n == count {
  148. break
  149. }
  150. }
  151. return expFields
  152. }
  153. var standardParser = NewParser(
  154. Minute | Hour | Dom | Month | Dow | Descriptor,
  155. )
  156. // ParseStandard returns a new crontab schedule representing the given standardSpec
  157. // (https://en.wikipedia.org/wiki/Cron). It differs from Parse requiring to always
  158. // pass 5 entries representing: minute, hour, day of month, month and day of week,
  159. // in that order. It returns a descriptive error if the spec is not valid.
  160. //
  161. // It accepts
  162. // - Standard crontab specs, e.g. "* * * * ?"
  163. // - Descriptors, e.g. "@midnight", "@every 1h30m"
  164. func ParseStandard(standardSpec string) (Schedule, error) {
  165. return standardParser.Parse(standardSpec)
  166. }
  167. var defaultParser = NewParser(
  168. Second | Minute | Hour | Dom | Month | DowOptional | Descriptor,
  169. )
  170. // Parse returns a new crontab schedule representing the given spec.
  171. // It returns a descriptive error if the spec is not valid.
  172. //
  173. // It accepts
  174. // - Full crontab specs, e.g. "* * * * * ?"
  175. // - Descriptors, e.g. "@midnight", "@every 1h30m"
  176. func Parse(spec string) (Schedule, error) {
  177. return defaultParser.Parse(spec)
  178. }
  179. // getField returns an Int with the bits set representing all of the times that
  180. // the field represents or error parsing field value. A "field" is a comma-separated
  181. // list of "ranges".
  182. func getField(field string, r bounds) (uint64, error) {
  183. var bits uint64
  184. ranges := strings.FieldsFunc(field, func(r rune) bool { return r == ',' })
  185. for _, expr := range ranges {
  186. bit, err := getRange(expr, r)
  187. if err != nil {
  188. return bits, err
  189. }
  190. bits |= bit
  191. }
  192. return bits, nil
  193. }
  194. // getRange returns the bits indicated by the given expression:
  195. // number | number "-" number [ "/" number ]
  196. // or error parsing range.
  197. func getRange(expr string, r bounds) (uint64, error) {
  198. var (
  199. start, end, step uint
  200. rangeAndStep = strings.Split(expr, "/")
  201. lowAndHigh = strings.Split(rangeAndStep[0], "-")
  202. singleDigit = len(lowAndHigh) == 1
  203. err error
  204. )
  205. var extra uint64
  206. if lowAndHigh[0] == "*" || lowAndHigh[0] == "?" {
  207. start = r.min
  208. end = r.max
  209. extra = starBit
  210. } else {
  211. start, err = parseIntOrName(lowAndHigh[0], r.names)
  212. if err != nil {
  213. return 0, err
  214. }
  215. switch len(lowAndHigh) {
  216. case 1:
  217. end = start
  218. case 2:
  219. end, err = parseIntOrName(lowAndHigh[1], r.names)
  220. if err != nil {
  221. return 0, err
  222. }
  223. default:
  224. return 0, fmt.Errorf("Too many hyphens: %s", expr)
  225. }
  226. }
  227. switch len(rangeAndStep) {
  228. case 1:
  229. step = 1
  230. case 2:
  231. step, err = mustParseInt(rangeAndStep[1])
  232. if err != nil {
  233. return 0, err
  234. }
  235. // Special handling: "N/step" means "N-max/step".
  236. if singleDigit {
  237. end = r.max
  238. }
  239. default:
  240. return 0, fmt.Errorf("Too many slashes: %s", expr)
  241. }
  242. if start < r.min {
  243. return 0, fmt.Errorf("Beginning of range (%d) below minimum (%d): %s", start, r.min, expr)
  244. }
  245. if end > r.max {
  246. return 0, fmt.Errorf("End of range (%d) above maximum (%d): %s", end, r.max, expr)
  247. }
  248. if start > end {
  249. return 0, fmt.Errorf("Beginning of range (%d) beyond end of range (%d): %s", start, end, expr)
  250. }
  251. if step == 0 {
  252. return 0, fmt.Errorf("Step of range should be a positive number: %s", expr)
  253. }
  254. return getBits(start, end, step) | extra, nil
  255. }
  256. // parseIntOrName returns the (possibly-named) integer contained in expr.
  257. func parseIntOrName(expr string, names map[string]uint) (uint, error) {
  258. if names != nil {
  259. if namedInt, ok := names[strings.ToLower(expr)]; ok {
  260. return namedInt, nil
  261. }
  262. }
  263. return mustParseInt(expr)
  264. }
  265. // mustParseInt parses the given expression as an int or returns an error.
  266. func mustParseInt(expr string) (uint, error) {
  267. num, err := strconv.Atoi(expr)
  268. if err != nil {
  269. return 0, fmt.Errorf("Failed to parse int from %s: %s", expr, err)
  270. }
  271. if num < 0 {
  272. return 0, fmt.Errorf("Negative number (%d) not allowed: %s", num, expr)
  273. }
  274. return uint(num), nil
  275. }
  276. // getBits sets all bits in the range [min, max], modulo the given step size.
  277. func getBits(min, max, step uint) uint64 {
  278. var bits uint64
  279. // If step is 1, use shifts.
  280. if step == 1 {
  281. return ^(math.MaxUint64 << (max + 1)) & (math.MaxUint64 << min)
  282. }
  283. // Else, use a simple loop.
  284. for i := min; i <= max; i += step {
  285. bits |= 1 << i
  286. }
  287. return bits
  288. }
  289. // all returns all bits within the given bounds. (plus the star bit)
  290. func all(r bounds) uint64 {
  291. return getBits(r.min, r.max, 1) | starBit
  292. }
  293. // parseDescriptor returns a predefined schedule for the expression, or error if none matches.
  294. func parseDescriptor(descriptor string, loc *time.Location) (Schedule, error) {
  295. switch descriptor {
  296. case "@yearly", "@annually":
  297. return &SpecSchedule{
  298. Second: 1 << seconds.min,
  299. Minute: 1 << minutes.min,
  300. Hour: 1 << hours.min,
  301. Dom: 1 << dom.min,
  302. Month: 1 << months.min,
  303. Dow: all(dow),
  304. Location: loc,
  305. }, nil
  306. case "@monthly":
  307. return &SpecSchedule{
  308. Second: 1 << seconds.min,
  309. Minute: 1 << minutes.min,
  310. Hour: 1 << hours.min,
  311. Dom: 1 << dom.min,
  312. Month: all(months),
  313. Dow: all(dow),
  314. Location: loc,
  315. }, nil
  316. case "@weekly":
  317. return &SpecSchedule{
  318. Second: 1 << seconds.min,
  319. Minute: 1 << minutes.min,
  320. Hour: 1 << hours.min,
  321. Dom: all(dom),
  322. Month: all(months),
  323. Dow: 1 << dow.min,
  324. Location: loc,
  325. }, nil
  326. case "@daily", "@midnight":
  327. return &SpecSchedule{
  328. Second: 1 << seconds.min,
  329. Minute: 1 << minutes.min,
  330. Hour: 1 << hours.min,
  331. Dom: all(dom),
  332. Month: all(months),
  333. Dow: all(dow),
  334. Location: loc,
  335. }, nil
  336. case "@hourly":
  337. return &SpecSchedule{
  338. Second: 1 << seconds.min,
  339. Minute: 1 << minutes.min,
  340. Hour: all(hours),
  341. Dom: all(dom),
  342. Month: all(months),
  343. Dow: all(dow),
  344. Location: loc,
  345. }, nil
  346. }
  347. const every = "@every "
  348. if strings.HasPrefix(descriptor, every) {
  349. duration, err := time.ParseDuration(descriptor[len(every):])
  350. if err != nil {
  351. return nil, fmt.Errorf("Failed to parse duration %s: %s", descriptor, err)
  352. }
  353. return Every(duration), nil
  354. }
  355. return nil, fmt.Errorf("Unrecognized descriptor: %s", descriptor)
  356. }