value.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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. "encoding/json"
  16. "fmt"
  17. "math"
  18. "sort"
  19. "strconv"
  20. "strings"
  21. )
  22. var (
  23. // ZeroSamplePair is the pseudo zero-value of SamplePair used to signal a
  24. // non-existing sample pair. It is a SamplePair with timestamp Earliest and
  25. // value 0.0. Note that the natural zero value of SamplePair has a timestamp
  26. // of 0, which is possible to appear in a real SamplePair and thus not
  27. // suitable to signal a non-existing SamplePair.
  28. ZeroSamplePair = SamplePair{Timestamp: Earliest}
  29. // ZeroSample is the pseudo zero-value of Sample used to signal a
  30. // non-existing sample. It is a Sample with timestamp Earliest, value 0.0,
  31. // and metric nil. Note that the natural zero value of Sample has a timestamp
  32. // of 0, which is possible to appear in a real Sample and thus not suitable
  33. // to signal a non-existing Sample.
  34. ZeroSample = Sample{Timestamp: Earliest}
  35. )
  36. // A SampleValue is a representation of a value for a given sample at a given
  37. // time.
  38. type SampleValue float64
  39. // MarshalJSON implements json.Marshaler.
  40. func (v SampleValue) MarshalJSON() ([]byte, error) {
  41. return json.Marshal(v.String())
  42. }
  43. // UnmarshalJSON implements json.Unmarshaler.
  44. func (v *SampleValue) UnmarshalJSON(b []byte) error {
  45. if len(b) < 2 || b[0] != '"' || b[len(b)-1] != '"' {
  46. return fmt.Errorf("sample value must be a quoted string")
  47. }
  48. f, err := strconv.ParseFloat(string(b[1:len(b)-1]), 64)
  49. if err != nil {
  50. return err
  51. }
  52. *v = SampleValue(f)
  53. return nil
  54. }
  55. // Equal returns true if the value of v and o is equal or if both are NaN. Note
  56. // that v==o is false if both are NaN. If you want the conventional float
  57. // behavior, use == to compare two SampleValues.
  58. func (v SampleValue) Equal(o SampleValue) bool {
  59. if v == o {
  60. return true
  61. }
  62. return math.IsNaN(float64(v)) && math.IsNaN(float64(o))
  63. }
  64. func (v SampleValue) String() string {
  65. return strconv.FormatFloat(float64(v), 'f', -1, 64)
  66. }
  67. // SamplePair pairs a SampleValue with a Timestamp.
  68. type SamplePair struct {
  69. Timestamp Time
  70. Value SampleValue
  71. }
  72. // MarshalJSON implements json.Marshaler.
  73. func (s SamplePair) MarshalJSON() ([]byte, error) {
  74. t, err := json.Marshal(s.Timestamp)
  75. if err != nil {
  76. return nil, err
  77. }
  78. v, err := json.Marshal(s.Value)
  79. if err != nil {
  80. return nil, err
  81. }
  82. return []byte(fmt.Sprintf("[%s,%s]", t, v)), nil
  83. }
  84. // UnmarshalJSON implements json.Unmarshaler.
  85. func (s *SamplePair) UnmarshalJSON(b []byte) error {
  86. v := [...]json.Unmarshaler{&s.Timestamp, &s.Value}
  87. return json.Unmarshal(b, &v)
  88. }
  89. // Equal returns true if this SamplePair and o have equal Values and equal
  90. // Timestamps. The sematics of Value equality is defined by SampleValue.Equal.
  91. func (s *SamplePair) Equal(o *SamplePair) bool {
  92. return s == o || (s.Value.Equal(o.Value) && s.Timestamp.Equal(o.Timestamp))
  93. }
  94. func (s SamplePair) String() string {
  95. return fmt.Sprintf("%s @[%s]", s.Value, s.Timestamp)
  96. }
  97. // Sample is a sample pair associated with a metric.
  98. type Sample struct {
  99. Metric Metric `json:"metric"`
  100. Value SampleValue `json:"value"`
  101. Timestamp Time `json:"timestamp"`
  102. }
  103. // Equal compares first the metrics, then the timestamp, then the value. The
  104. // sematics of value equality is defined by SampleValue.Equal.
  105. func (s *Sample) Equal(o *Sample) bool {
  106. if s == o {
  107. return true
  108. }
  109. if !s.Metric.Equal(o.Metric) {
  110. return false
  111. }
  112. if !s.Timestamp.Equal(o.Timestamp) {
  113. return false
  114. }
  115. return s.Value.Equal(o.Value)
  116. }
  117. func (s Sample) String() string {
  118. return fmt.Sprintf("%s => %s", s.Metric, SamplePair{
  119. Timestamp: s.Timestamp,
  120. Value: s.Value,
  121. })
  122. }
  123. // MarshalJSON implements json.Marshaler.
  124. func (s Sample) MarshalJSON() ([]byte, error) {
  125. v := struct {
  126. Metric Metric `json:"metric"`
  127. Value SamplePair `json:"value"`
  128. }{
  129. Metric: s.Metric,
  130. Value: SamplePair{
  131. Timestamp: s.Timestamp,
  132. Value: s.Value,
  133. },
  134. }
  135. return json.Marshal(&v)
  136. }
  137. // UnmarshalJSON implements json.Unmarshaler.
  138. func (s *Sample) UnmarshalJSON(b []byte) error {
  139. v := struct {
  140. Metric Metric `json:"metric"`
  141. Value SamplePair `json:"value"`
  142. }{
  143. Metric: s.Metric,
  144. Value: SamplePair{
  145. Timestamp: s.Timestamp,
  146. Value: s.Value,
  147. },
  148. }
  149. if err := json.Unmarshal(b, &v); err != nil {
  150. return err
  151. }
  152. s.Metric = v.Metric
  153. s.Timestamp = v.Value.Timestamp
  154. s.Value = v.Value.Value
  155. return nil
  156. }
  157. // Samples is a sortable Sample slice. It implements sort.Interface.
  158. type Samples []*Sample
  159. func (s Samples) Len() int {
  160. return len(s)
  161. }
  162. // Less compares first the metrics, then the timestamp.
  163. func (s Samples) Less(i, j int) bool {
  164. switch {
  165. case s[i].Metric.Before(s[j].Metric):
  166. return true
  167. case s[j].Metric.Before(s[i].Metric):
  168. return false
  169. case s[i].Timestamp.Before(s[j].Timestamp):
  170. return true
  171. default:
  172. return false
  173. }
  174. }
  175. func (s Samples) Swap(i, j int) {
  176. s[i], s[j] = s[j], s[i]
  177. }
  178. // Equal compares two sets of samples and returns true if they are equal.
  179. func (s Samples) Equal(o Samples) bool {
  180. if len(s) != len(o) {
  181. return false
  182. }
  183. for i, sample := range s {
  184. if !sample.Equal(o[i]) {
  185. return false
  186. }
  187. }
  188. return true
  189. }
  190. // SampleStream is a stream of Values belonging to an attached COWMetric.
  191. type SampleStream struct {
  192. Metric Metric `json:"metric"`
  193. Values []SamplePair `json:"values"`
  194. }
  195. func (ss SampleStream) String() string {
  196. vals := make([]string, len(ss.Values))
  197. for i, v := range ss.Values {
  198. vals[i] = v.String()
  199. }
  200. return fmt.Sprintf("%s =>\n%s", ss.Metric, strings.Join(vals, "\n"))
  201. }
  202. // Value is a generic interface for values resulting from a query evaluation.
  203. type Value interface {
  204. Type() ValueType
  205. String() string
  206. }
  207. func (Matrix) Type() ValueType { return ValMatrix }
  208. func (Vector) Type() ValueType { return ValVector }
  209. func (*Scalar) Type() ValueType { return ValScalar }
  210. func (*String) Type() ValueType { return ValString }
  211. type ValueType int
  212. const (
  213. ValNone ValueType = iota
  214. ValScalar
  215. ValVector
  216. ValMatrix
  217. ValString
  218. )
  219. // MarshalJSON implements json.Marshaler.
  220. func (et ValueType) MarshalJSON() ([]byte, error) {
  221. return json.Marshal(et.String())
  222. }
  223. func (et *ValueType) UnmarshalJSON(b []byte) error {
  224. var s string
  225. if err := json.Unmarshal(b, &s); err != nil {
  226. return err
  227. }
  228. switch s {
  229. case "<ValNone>":
  230. *et = ValNone
  231. case "scalar":
  232. *et = ValScalar
  233. case "vector":
  234. *et = ValVector
  235. case "matrix":
  236. *et = ValMatrix
  237. case "string":
  238. *et = ValString
  239. default:
  240. return fmt.Errorf("unknown value type %q", s)
  241. }
  242. return nil
  243. }
  244. func (e ValueType) String() string {
  245. switch e {
  246. case ValNone:
  247. return "<ValNone>"
  248. case ValScalar:
  249. return "scalar"
  250. case ValVector:
  251. return "vector"
  252. case ValMatrix:
  253. return "matrix"
  254. case ValString:
  255. return "string"
  256. }
  257. panic("ValueType.String: unhandled value type")
  258. }
  259. // Scalar is a scalar value evaluated at the set timestamp.
  260. type Scalar struct {
  261. Value SampleValue `json:"value"`
  262. Timestamp Time `json:"timestamp"`
  263. }
  264. func (s Scalar) String() string {
  265. return fmt.Sprintf("scalar: %v @[%v]", s.Value, s.Timestamp)
  266. }
  267. // MarshalJSON implements json.Marshaler.
  268. func (s Scalar) MarshalJSON() ([]byte, error) {
  269. v := strconv.FormatFloat(float64(s.Value), 'f', -1, 64)
  270. return json.Marshal([...]interface{}{s.Timestamp, string(v)})
  271. }
  272. // UnmarshalJSON implements json.Unmarshaler.
  273. func (s *Scalar) UnmarshalJSON(b []byte) error {
  274. var f string
  275. v := [...]interface{}{&s.Timestamp, &f}
  276. if err := json.Unmarshal(b, &v); err != nil {
  277. return err
  278. }
  279. value, err := strconv.ParseFloat(f, 64)
  280. if err != nil {
  281. return fmt.Errorf("error parsing sample value: %s", err)
  282. }
  283. s.Value = SampleValue(value)
  284. return nil
  285. }
  286. // String is a string value evaluated at the set timestamp.
  287. type String struct {
  288. Value string `json:"value"`
  289. Timestamp Time `json:"timestamp"`
  290. }
  291. func (s *String) String() string {
  292. return s.Value
  293. }
  294. // MarshalJSON implements json.Marshaler.
  295. func (s String) MarshalJSON() ([]byte, error) {
  296. return json.Marshal([]interface{}{s.Timestamp, s.Value})
  297. }
  298. // UnmarshalJSON implements json.Unmarshaler.
  299. func (s *String) UnmarshalJSON(b []byte) error {
  300. v := [...]interface{}{&s.Timestamp, &s.Value}
  301. return json.Unmarshal(b, &v)
  302. }
  303. // Vector is basically only an alias for Samples, but the
  304. // contract is that in a Vector, all Samples have the same timestamp.
  305. type Vector []*Sample
  306. func (vec Vector) String() string {
  307. entries := make([]string, len(vec))
  308. for i, s := range vec {
  309. entries[i] = s.String()
  310. }
  311. return strings.Join(entries, "\n")
  312. }
  313. func (vec Vector) Len() int { return len(vec) }
  314. func (vec Vector) Swap(i, j int) { vec[i], vec[j] = vec[j], vec[i] }
  315. // Less compares first the metrics, then the timestamp.
  316. func (vec Vector) Less(i, j int) bool {
  317. switch {
  318. case vec[i].Metric.Before(vec[j].Metric):
  319. return true
  320. case vec[j].Metric.Before(vec[i].Metric):
  321. return false
  322. case vec[i].Timestamp.Before(vec[j].Timestamp):
  323. return true
  324. default:
  325. return false
  326. }
  327. }
  328. // Equal compares two sets of samples and returns true if they are equal.
  329. func (vec Vector) Equal(o Vector) bool {
  330. if len(vec) != len(o) {
  331. return false
  332. }
  333. for i, sample := range vec {
  334. if !sample.Equal(o[i]) {
  335. return false
  336. }
  337. }
  338. return true
  339. }
  340. // Matrix is a list of time series.
  341. type Matrix []*SampleStream
  342. func (m Matrix) Len() int { return len(m) }
  343. func (m Matrix) Less(i, j int) bool { return m[i].Metric.Before(m[j].Metric) }
  344. func (m Matrix) Swap(i, j int) { m[i], m[j] = m[j], m[i] }
  345. func (mat Matrix) String() string {
  346. matCp := make(Matrix, len(mat))
  347. copy(matCp, mat)
  348. sort.Sort(matCp)
  349. strs := make([]string, len(matCp))
  350. for i, ss := range matCp {
  351. strs[i] = ss.String()
  352. }
  353. return strings.Join(strs, "\n")
  354. }