value.go 9.2 KB

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