time.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. // Copyright 2013 The Prometheus Authors
  2. // Licensed under the Apache License, Version 2.0 (the "License");
  3. // you may not use this file except in compliance with the License.
  4. // You may obtain a copy of the License at
  5. //
  6. // http://www.apache.org/licenses/LICENSE-2.0
  7. //
  8. // Unless required by applicable law or agreed to in writing, software
  9. // distributed under the License is distributed on an "AS IS" BASIS,
  10. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. package model
  14. import (
  15. "fmt"
  16. "math"
  17. "regexp"
  18. "strconv"
  19. "strings"
  20. "time"
  21. )
  22. const (
  23. // MinimumTick is the minimum supported time resolution. This has to be
  24. // at least time.Second in order for the code below to work.
  25. minimumTick = time.Millisecond
  26. // second is the Time duration equivalent to one second.
  27. second = int64(time.Second / minimumTick)
  28. // The number of nanoseconds per minimum tick.
  29. nanosPerTick = int64(minimumTick / time.Nanosecond)
  30. // Earliest is the earliest Time representable. Handy for
  31. // initializing a high watermark.
  32. Earliest = Time(math.MinInt64)
  33. // Latest is the latest Time representable. Handy for initializing
  34. // a low watermark.
  35. Latest = Time(math.MaxInt64)
  36. )
  37. // Time is the number of milliseconds since the epoch
  38. // (1970-01-01 00:00 UTC) excluding leap seconds.
  39. type Time int64
  40. // Interval describes an interval between two timestamps.
  41. type Interval struct {
  42. Start, End Time
  43. }
  44. // Now returns the current time as a Time.
  45. func Now() Time {
  46. return TimeFromUnixNano(time.Now().UnixNano())
  47. }
  48. // TimeFromUnix returns the Time equivalent to the Unix Time t
  49. // provided in seconds.
  50. func TimeFromUnix(t int64) Time {
  51. return Time(t * second)
  52. }
  53. // TimeFromUnixNano returns the Time equivalent to the Unix Time
  54. // t provided in nanoseconds.
  55. func TimeFromUnixNano(t int64) Time {
  56. return Time(t / nanosPerTick)
  57. }
  58. // Equal reports whether two Times represent the same instant.
  59. func (t Time) Equal(o Time) bool {
  60. return t == o
  61. }
  62. // Before reports whether the Time t is before o.
  63. func (t Time) Before(o Time) bool {
  64. return t < o
  65. }
  66. // After reports whether the Time t is after o.
  67. func (t Time) After(o Time) bool {
  68. return t > o
  69. }
  70. // Add returns the Time t + d.
  71. func (t Time) Add(d time.Duration) Time {
  72. return t + Time(d/minimumTick)
  73. }
  74. // Sub returns the Duration t - o.
  75. func (t Time) Sub(o Time) time.Duration {
  76. return time.Duration(t-o) * minimumTick
  77. }
  78. // Time returns the time.Time representation of t.
  79. func (t Time) Time() time.Time {
  80. return time.Unix(int64(t)/second, (int64(t)%second)*nanosPerTick)
  81. }
  82. // Unix returns t as a Unix time, the number of seconds elapsed
  83. // since January 1, 1970 UTC.
  84. func (t Time) Unix() int64 {
  85. return int64(t) / second
  86. }
  87. // UnixNano returns t as a Unix time, the number of nanoseconds elapsed
  88. // since January 1, 1970 UTC.
  89. func (t Time) UnixNano() int64 {
  90. return int64(t) * nanosPerTick
  91. }
  92. // The number of digits after the dot.
  93. var dotPrecision = int(math.Log10(float64(second)))
  94. // String returns a string representation of the Time.
  95. func (t Time) String() string {
  96. return strconv.FormatFloat(float64(t)/float64(second), 'f', -1, 64)
  97. }
  98. // MarshalJSON implements the json.Marshaler interface.
  99. func (t Time) MarshalJSON() ([]byte, error) {
  100. return []byte(t.String()), nil
  101. }
  102. // UnmarshalJSON implements the json.Unmarshaler interface.
  103. func (t *Time) UnmarshalJSON(b []byte) error {
  104. p := strings.Split(string(b), ".")
  105. switch len(p) {
  106. case 1:
  107. v, err := strconv.ParseInt(string(p[0]), 10, 64)
  108. if err != nil {
  109. return err
  110. }
  111. *t = Time(v * second)
  112. case 2:
  113. v, err := strconv.ParseInt(string(p[0]), 10, 64)
  114. if err != nil {
  115. return err
  116. }
  117. v *= second
  118. prec := dotPrecision - len(p[1])
  119. if prec < 0 {
  120. p[1] = p[1][:dotPrecision]
  121. } else if prec > 0 {
  122. p[1] = p[1] + strings.Repeat("0", prec)
  123. }
  124. va, err := strconv.ParseInt(p[1], 10, 32)
  125. if err != nil {
  126. return err
  127. }
  128. // If the value was something like -0.1 the negative is lost in the
  129. // parsing because of the leading zero, this ensures that we capture it.
  130. if len(p[0]) > 0 && p[0][0] == '-' && v+va > 0 {
  131. *t = Time(v+va) * -1
  132. } else {
  133. *t = Time(v + va)
  134. }
  135. default:
  136. return fmt.Errorf("invalid time %q", string(b))
  137. }
  138. return nil
  139. }
  140. // Duration wraps time.Duration. It is used to parse the custom duration format
  141. // from YAML.
  142. // This type should not propagate beyond the scope of input/output processing.
  143. type Duration time.Duration
  144. // Set implements pflag/flag.Value
  145. func (d *Duration) Set(s string) error {
  146. var err error
  147. *d, err = ParseDuration(s)
  148. return err
  149. }
  150. // Type implements pflag.Value
  151. func (d *Duration) Type() string {
  152. return "duration"
  153. }
  154. var durationRE = regexp.MustCompile("^([0-9]+)(y|w|d|h|m|s|ms)$")
  155. // ParseDuration parses a string into a time.Duration, assuming that a year
  156. // always has 365d, a week always has 7d, and a day always has 24h.
  157. func ParseDuration(durationStr string) (Duration, error) {
  158. matches := durationRE.FindStringSubmatch(durationStr)
  159. if len(matches) != 3 {
  160. return 0, fmt.Errorf("not a valid duration string: %q", durationStr)
  161. }
  162. var (
  163. n, _ = strconv.Atoi(matches[1])
  164. dur = time.Duration(n) * time.Millisecond
  165. )
  166. switch unit := matches[2]; unit {
  167. case "y":
  168. dur *= 1000 * 60 * 60 * 24 * 365
  169. case "w":
  170. dur *= 1000 * 60 * 60 * 24 * 7
  171. case "d":
  172. dur *= 1000 * 60 * 60 * 24
  173. case "h":
  174. dur *= 1000 * 60 * 60
  175. case "m":
  176. dur *= 1000 * 60
  177. case "s":
  178. dur *= 1000
  179. case "ms":
  180. // Value already correct
  181. default:
  182. return 0, fmt.Errorf("invalid time unit in duration string: %q", unit)
  183. }
  184. return Duration(dur), nil
  185. }
  186. func (d Duration) String() string {
  187. var (
  188. ms = int64(time.Duration(d) / time.Millisecond)
  189. unit = "ms"
  190. )
  191. if ms == 0 {
  192. return "0s"
  193. }
  194. factors := map[string]int64{
  195. "y": 1000 * 60 * 60 * 24 * 365,
  196. "w": 1000 * 60 * 60 * 24 * 7,
  197. "d": 1000 * 60 * 60 * 24,
  198. "h": 1000 * 60 * 60,
  199. "m": 1000 * 60,
  200. "s": 1000,
  201. "ms": 1,
  202. }
  203. switch int64(0) {
  204. case ms % factors["y"]:
  205. unit = "y"
  206. case ms % factors["w"]:
  207. unit = "w"
  208. case ms % factors["d"]:
  209. unit = "d"
  210. case ms % factors["h"]:
  211. unit = "h"
  212. case ms % factors["m"]:
  213. unit = "m"
  214. case ms % factors["s"]:
  215. unit = "s"
  216. }
  217. return fmt.Sprintf("%v%v", ms/factors[unit], unit)
  218. }
  219. // MarshalYAML implements the yaml.Marshaler interface.
  220. func (d Duration) MarshalYAML() (interface{}, error) {
  221. return d.String(), nil
  222. }
  223. // UnmarshalYAML implements the yaml.Unmarshaler interface.
  224. func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error {
  225. var s string
  226. if err := unmarshal(&s); err != nil {
  227. return err
  228. }
  229. dur, err := ParseDuration(s)
  230. if err != nil {
  231. return err
  232. }
  233. *d = dur
  234. return nil
  235. }