Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

parser.go 9.4KB

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