time.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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. // StringToDuration parses a string into a time.Duration, assuming that a year
  139. // a day always has 24h.
  140. func ParseDuration(durationStr string) (Duration, error) {
  141. matches := durationRE.FindStringSubmatch(durationStr)
  142. if len(matches) != 3 {
  143. return 0, fmt.Errorf("not a valid duration string: %q", durationStr)
  144. }
  145. durSeconds, _ := strconv.Atoi(matches[1])
  146. dur := time.Duration(durSeconds) * time.Second
  147. unit := matches[2]
  148. switch unit {
  149. case "d":
  150. dur *= 60 * 60 * 24
  151. case "h":
  152. dur *= 60 * 60
  153. case "m":
  154. dur *= 60
  155. case "s":
  156. dur *= 1
  157. default:
  158. return 0, fmt.Errorf("invalid time unit in duration string: %q", unit)
  159. }
  160. return Duration(dur), nil
  161. }
  162. var durationRE = regexp.MustCompile("^([0-9]+)([ywdhms]+)$")
  163. func (d Duration) String() string {
  164. seconds := int64(time.Duration(d) / time.Second)
  165. factors := map[string]int64{
  166. "d": 60 * 60 * 24,
  167. "h": 60 * 60,
  168. "m": 60,
  169. "s": 1,
  170. }
  171. unit := "s"
  172. switch int64(0) {
  173. case seconds % factors["d"]:
  174. unit = "d"
  175. case seconds % factors["h"]:
  176. unit = "h"
  177. case seconds % factors["m"]:
  178. unit = "m"
  179. }
  180. return fmt.Sprintf("%v%v", seconds/factors[unit], unit)
  181. }
  182. // MarshalYAML implements the yaml.Marshaler interface.
  183. func (d Duration) MarshalYAML() (interface{}, error) {
  184. return d.String(), nil
  185. }
  186. // UnmarshalYAML implements the yaml.Unmarshaler interface.
  187. func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error {
  188. var s string
  189. if err := unmarshal(&s); err != nil {
  190. return err
  191. }
  192. dur, err := ParseDuration(s)
  193. if err != nil {
  194. return err
  195. }
  196. *d = dur
  197. return nil
  198. }