vitess.io/vitess@v0.16.2/go/vt/vtorc/discovery/metric_json.go (about) 1 /* 2 Copyright 2017 Simon J Mudd 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package discovery 18 19 // Collect discovery metrics and manage their storage and retrieval for monitoring purposes. 20 21 import ( 22 "errors" 23 "fmt" 24 "time" 25 26 "vitess.io/vitess/go/vt/vtorc/collection" 27 ) 28 29 // formattedFloat is to force the JSON output to show 3 decimal places 30 type formattedFloat float64 31 32 func (m formattedFloat) String() string { 33 return fmt.Sprintf("%.3f", m) 34 } 35 36 // MetricJSON holds a structure which represents some discovery latency information 37 type MetricJSON struct { 38 Timestamp time.Time 39 Hostname string 40 Port int 41 BackendLatencySeconds formattedFloat 42 InstanceLatencySeconds formattedFloat 43 TotalLatencySeconds formattedFloat 44 Err error 45 } 46 47 // JSONSince returns an API response of discovery metric collection information 48 // in a printable JSON format. 49 func JSONSince(c *collection.Collection, t time.Time) ([](MetricJSON), error) { 50 if c == nil { 51 return nil, errors.New("MetricCollection.JSONSince: c == nil") 52 } 53 raw, err := c.Since(t) 54 if err != nil { 55 return nil, err 56 } 57 58 // build up JSON response for each Metric we received 59 var s []MetricJSON 60 for i := range raw { 61 m := raw[i].(*Metric) // convert back to a real Metric rather than collection.Metric interface 62 mj := MetricJSON{ 63 Timestamp: m.Timestamp, 64 Hostname: m.InstanceKey.Hostname, 65 Port: m.InstanceKey.Port, 66 BackendLatencySeconds: formattedFloat(m.BackendLatency.Seconds()), 67 InstanceLatencySeconds: formattedFloat(m.InstanceLatency.Seconds()), 68 TotalLatencySeconds: formattedFloat(m.TotalLatency.Seconds()), 69 Err: m.Err, 70 } 71 s = append(s, mj) 72 } 73 return s, nil 74 }