time.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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 and 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. *t = Time(v + va)
  129. default:
  130. return fmt.Errorf("invalid time %q", string(b))
  131. }
  132. return nil
  133. }
  134. // Duration wraps time.Duration. It is used to parse the custom duration format
  135. // from YAML.
  136. // This type should not propagate beyond the scope of input/output processing.
  137. type Duration time.Duration
  138. // Set implements pflag/flag.Value
  139. func (d *Duration) Set(s string) error {
  140. var err error
  141. *d, err = ParseDuration(s)
  142. return err
  143. }
  144. // Type implements pflag.Value
  145. func (d *Duration) Type() string {
  146. return "duration"
  147. }
  148. var durationRE = regexp.MustCompile("^([0-9]+)(y|w|d|h|m|s|ms)$")
  149. // ParseDuration parses a string into a time.Duration, assuming that a year
  150. // always has 365d, a week always has 7d, and a day always has 24h.
  151. func ParseDuration(durationStr string) (Duration, error) {
  152. matches := durationRE.FindStringSubmatch(durationStr)
  153. if len(matches) != 3 {
  154. return 0, fmt.Errorf("not a valid duration string: %q", durationStr)
  155. }
  156. var (
  157. n, _ = strconv.Atoi(matches[1])
  158. dur = time.Duration(n) * time.Millisecond
  159. )
  160. switch unit := matches[2]; unit {
  161. case "y":
  162. dur *= 1000 * 60 * 60 * 24 * 365
  163. case "w":
  164. dur *= 1000 * 60 * 60 * 24 * 7
  165. case "d":
  166. dur *= 1000 * 60 * 60 * 24
  167. case "h":
  168. dur *= 1000 * 60 * 60
  169. case "m":
  170. dur *= 1000 * 60
  171. case "s":
  172. dur *= 1000
  173. case "ms":
  174. // Value already correct
  175. default:
  176. return 0, fmt.Errorf("invalid time unit in duration string: %q", unit)
  177. }
  178. return Duration(dur), nil
  179. }
  180. func (d Duration) String() string {
  181. var (
  182. ms = int64(time.Duration(d) / time.Millisecond)
  183. unit = "ms"
  184. )
  185. if ms == 0 {
  186. return "0s"
  187. }
  188. factors := map[string]int64{
  189. "y": 1000 * 60 * 60 * 24 * 365,
  190. "w": 1000 * 60 * 60 * 24 * 7,
  191. "d": 1000 * 60 * 60 * 24,
  192. "h": 1000 * 60 * 60,
  193. "m": 1000 * 60,
  194. "s": 1000,
  195. "ms": 1,
  196. }
  197. switch int64(0) {
  198. case ms % factors["y"]:
  199. unit = "y"
  200. case ms % factors["w"]:
  201. unit = "w"
  202. case ms % factors["d"]:
  203. unit = "d"
  204. case ms % factors["h"]:
  205. unit = "h"
  206. case ms % factors["m"]:
  207. unit = "m"
  208. case ms % factors["s"]:
  209. unit = "s"
  210. }
  211. return fmt.Sprintf("%v%v", ms/factors[unit], unit)
  212. }
  213. // MarshalYAML implements the yaml.Marshaler interface.
  214. func (d Duration) MarshalYAML() (interface{}, error) {
  215. return d.String(), nil
  216. }
  217. // UnmarshalYAML implements the yaml.Unmarshaler interface.
  218. func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error {
  219. var s string
  220. if err := unmarshal(&s); err != nil {
  221. return err
  222. }
  223. dur, err := ParseDuration(s)
  224. if err != nil {
  225. return err
  226. }
  227. *d = dur
  228. return nil
  229. }