You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

231 lines
5.4 KiB

  1. package cron
  2. import (
  3. "fmt"
  4. "log"
  5. "math"
  6. "strconv"
  7. "strings"
  8. "time"
  9. )
  10. // Parse returns a new crontab schedule representing the given spec.
  11. // It returns a descriptive error if the spec is not valid.
  12. //
  13. // It accepts
  14. // - Full crontab specs, e.g. "* * * * * ?"
  15. // - Descriptors, e.g. "@midnight", "@every 1h30m"
  16. func Parse(spec string) (_ Schedule, err error) {
  17. // Convert panics into errors
  18. defer func() {
  19. if recovered := recover(); recovered != nil {
  20. err = fmt.Errorf("%v", recovered)
  21. }
  22. }()
  23. if spec[0] == '@' {
  24. return parseDescriptor(spec), nil
  25. }
  26. // Split on whitespace. We require 5 or 6 fields.
  27. // (second) (minute) (hour) (day of month) (month) (day of week, optional)
  28. fields := strings.Fields(spec)
  29. if len(fields) != 5 && len(fields) != 6 {
  30. log.Panicf("Expected 5 or 6 fields, found %d: %s", len(fields), spec)
  31. }
  32. // If a sixth field is not provided (DayOfWeek), then it is equivalent to star.
  33. if len(fields) == 5 {
  34. fields = append(fields, "*")
  35. }
  36. schedule := &SpecSchedule{
  37. Second: getField(fields[0], seconds),
  38. Minute: getField(fields[1], minutes),
  39. Hour: getField(fields[2], hours),
  40. Dom: getField(fields[3], dom),
  41. Month: getField(fields[4], months),
  42. Dow: getField(fields[5], dow),
  43. }
  44. return schedule, nil
  45. }
  46. // getField returns an Int with the bits set representing all of the times that
  47. // the field represents. A "field" is a comma-separated list of "ranges".
  48. func getField(field string, r bounds) uint64 {
  49. // list = range {"," range}
  50. var bits uint64
  51. ranges := strings.FieldsFunc(field, func(r rune) bool { return r == ',' })
  52. for _, expr := range ranges {
  53. bits |= getRange(expr, r)
  54. }
  55. return bits
  56. }
  57. // getRange returns the bits indicated by the given expression:
  58. // number | number "-" number [ "/" number ]
  59. func getRange(expr string, r bounds) uint64 {
  60. var (
  61. start, end, step uint
  62. rangeAndStep = strings.Split(expr, "/")
  63. lowAndHigh = strings.Split(rangeAndStep[0], "-")
  64. singleDigit = len(lowAndHigh) == 1
  65. )
  66. var extra_star uint64
  67. if lowAndHigh[0] == "*" || lowAndHigh[0] == "?" {
  68. start = r.min
  69. end = r.max
  70. extra_star = starBit
  71. } else {
  72. start = parseIntOrName(lowAndHigh[0], r.names)
  73. switch len(lowAndHigh) {
  74. case 1:
  75. end = start
  76. case 2:
  77. end = parseIntOrName(lowAndHigh[1], r.names)
  78. default:
  79. log.Panicf("Too many hyphens: %s", expr)
  80. }
  81. }
  82. switch len(rangeAndStep) {
  83. case 1:
  84. step = 1
  85. case 2:
  86. step = mustParseInt(rangeAndStep[1])
  87. // Special handling: "N/step" means "N-max/step".
  88. if singleDigit {
  89. end = r.max
  90. }
  91. default:
  92. log.Panicf("Too many slashes: %s", expr)
  93. }
  94. if start < r.min {
  95. log.Panicf("Beginning of range (%d) below minimum (%d): %s", start, r.min, expr)
  96. }
  97. if end > r.max {
  98. log.Panicf("End of range (%d) above maximum (%d): %s", end, r.max, expr)
  99. }
  100. if start > end {
  101. log.Panicf("Beginning of range (%d) beyond end of range (%d): %s", start, end, expr)
  102. }
  103. return getBits(start, end, step) | extra_star
  104. }
  105. // parseIntOrName returns the (possibly-named) integer contained in expr.
  106. func parseIntOrName(expr string, names map[string]uint) uint {
  107. if names != nil {
  108. if namedInt, ok := names[strings.ToLower(expr)]; ok {
  109. return namedInt
  110. }
  111. }
  112. return mustParseInt(expr)
  113. }
  114. // mustParseInt parses the given expression as an int or panics.
  115. func mustParseInt(expr string) uint {
  116. num, err := strconv.Atoi(expr)
  117. if err != nil {
  118. log.Panicf("Failed to parse int from %s: %s", expr, err)
  119. }
  120. if num < 0 {
  121. log.Panicf("Negative number (%d) not allowed: %s", num, expr)
  122. }
  123. return uint(num)
  124. }
  125. // getBits sets all bits in the range [min, max], modulo the given step size.
  126. func getBits(min, max, step uint) uint64 {
  127. var bits uint64
  128. // If step is 1, use shifts.
  129. if step == 1 {
  130. return ^(math.MaxUint64 << (max + 1)) & (math.MaxUint64 << min)
  131. }
  132. // Else, use a simple loop.
  133. for i := min; i <= max; i += step {
  134. bits |= 1 << i
  135. }
  136. return bits
  137. }
  138. // all returns all bits within the given bounds. (plus the star bit)
  139. func all(r bounds) uint64 {
  140. return getBits(r.min, r.max, 1) | starBit
  141. }
  142. // parseDescriptor returns a pre-defined schedule for the expression, or panics
  143. // if none matches.
  144. func parseDescriptor(spec string) Schedule {
  145. switch spec {
  146. case "@yearly", "@annually":
  147. return &SpecSchedule{
  148. Second: 1 << seconds.min,
  149. Minute: 1 << minutes.min,
  150. Hour: 1 << hours.min,
  151. Dom: 1 << dom.min,
  152. Month: 1 << months.min,
  153. Dow: all(dow),
  154. }
  155. case "@monthly":
  156. return &SpecSchedule{
  157. Second: 1 << seconds.min,
  158. Minute: 1 << minutes.min,
  159. Hour: 1 << hours.min,
  160. Dom: 1 << dom.min,
  161. Month: all(months),
  162. Dow: all(dow),
  163. }
  164. case "@weekly":
  165. return &SpecSchedule{
  166. Second: 1 << seconds.min,
  167. Minute: 1 << minutes.min,
  168. Hour: 1 << hours.min,
  169. Dom: all(dom),
  170. Month: all(months),
  171. Dow: 1 << dow.min,
  172. }
  173. case "@daily", "@midnight":
  174. return &SpecSchedule{
  175. Second: 1 << seconds.min,
  176. Minute: 1 << minutes.min,
  177. Hour: 1 << hours.min,
  178. Dom: all(dom),
  179. Month: all(months),
  180. Dow: all(dow),
  181. }
  182. case "@hourly":
  183. return &SpecSchedule{
  184. Second: 1 << seconds.min,
  185. Minute: 1 << minutes.min,
  186. Hour: all(hours),
  187. Dom: all(dom),
  188. Month: all(months),
  189. Dow: all(dow),
  190. }
  191. }
  192. const every = "@every "
  193. if strings.HasPrefix(spec, every) {
  194. duration, err := time.ParseDuration(spec[len(every):])
  195. if err != nil {
  196. log.Panicf("Failed to parse duration %s: %s", spec, err)
  197. }
  198. return Every(duration)
  199. }
  200. log.Panicf("Unrecognized descriptor: %s", spec)
  201. return nil
  202. }