|
| 1 | +/* |
| 2 | +Copyright 2020 Kohl's Department Stores, Inc. |
| 3 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +you may not use this file except in compliance with the License. |
| 5 | +You may obtain a copy of the License at |
| 6 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +Unless required by applicable law or agreed to in writing, software |
| 8 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 9 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 10 | +See the License for the specific language governing permissions and |
| 11 | +limitations under the License. |
| 12 | +*/ |
| 13 | + |
| 14 | +package bigquerydb |
| 15 | + |
| 16 | +import ( |
| 17 | + "context" |
| 18 | + "encoding/json" |
| 19 | + "fmt" |
| 20 | + "io/ioutil" |
| 21 | + "math" |
| 22 | + "os" |
| 23 | + "strings" |
| 24 | + "time" |
| 25 | + |
| 26 | + "cloud.google.com/go/bigquery" |
| 27 | + "github.com/go-kit/kit/log" |
| 28 | + "github.com/go-kit/kit/log/level" |
| 29 | + "github.com/prometheus/client_golang/prometheus" |
| 30 | + "github.com/prometheus/common/model" |
| 31 | + "google.golang.org/api/option" |
| 32 | +) |
| 33 | + |
| 34 | +// BigqueryClient allows sending batches of Prometheus samples to Bigquery. |
| 35 | +type BigqueryClient struct { |
| 36 | + logger log.Logger |
| 37 | + client bigquery.Client |
| 38 | + datasetID string |
| 39 | + tableID string |
| 40 | + timeout time.Duration |
| 41 | + ignoredSamples prometheus.Counter |
| 42 | +} |
| 43 | + |
| 44 | +// NewClient creates a new Client. |
| 45 | +func NewClient(logger log.Logger, googleAPIjsonkeypath, googleAPIdatasetID, googleAPItableID string, remoteTimeout time.Duration) *BigqueryClient { |
| 46 | + ctx := context.Background() |
| 47 | + |
| 48 | + jsonFile, err := os.Open(googleAPIjsonkeypath) |
| 49 | + if err != nil { |
| 50 | + level.Error(logger).Log("err", err) |
| 51 | + os.Exit(1) |
| 52 | + } |
| 53 | + |
| 54 | + byteValue, _ := ioutil.ReadAll(jsonFile) |
| 55 | + |
| 56 | + var result map[string]interface{} |
| 57 | + json.Unmarshal([]byte(byteValue), &result) |
| 58 | + |
| 59 | + //fmt.Println(result["type"]) |
| 60 | + jsonFile.Close() |
| 61 | + |
| 62 | + projectID := fmt.Sprintf("%v", result["project_id"]) |
| 63 | + |
| 64 | + c, err := bigquery.NewClient(ctx, projectID, option.WithCredentialsFile(googleAPIjsonkeypath)) |
| 65 | + if err != nil { |
| 66 | + level.Error(logger).Log("err", err) |
| 67 | + os.Exit(1) |
| 68 | + } |
| 69 | + |
| 70 | + if logger == nil { |
| 71 | + logger = log.NewNopLogger() |
| 72 | + } |
| 73 | + |
| 74 | + return &BigqueryClient{ |
| 75 | + logger: logger, |
| 76 | + client: *c, |
| 77 | + datasetID: googleAPIdatasetID, |
| 78 | + tableID: googleAPItableID, |
| 79 | + timeout: remoteTimeout, |
| 80 | + ignoredSamples: prometheus.NewCounter( |
| 81 | + prometheus.CounterOpts{ |
| 82 | + Name: "prometheus_bigquery_ignored_samples_total", |
| 83 | + Help: "The total number of samples not sent to BigQuery due to unsupported float values (Inf, -Inf, NaN).", |
| 84 | + }, |
| 85 | + ), |
| 86 | + } |
| 87 | +} |
| 88 | + |
| 89 | +// Item represents a row item. |
| 90 | +type Item struct { |
| 91 | + value float64 |
| 92 | + metricname string |
| 93 | + timestamp time.Time |
| 94 | + tags string |
| 95 | +} |
| 96 | + |
| 97 | +// Save implements the ValueSaver interface. |
| 98 | +func (i *Item) Save() (map[string]bigquery.Value, string, error) { |
| 99 | + return map[string]bigquery.Value{ |
| 100 | + "value": i.value, |
| 101 | + "metricname": i.metricname, |
| 102 | + "timestamp": i.timestamp, |
| 103 | + "tags": i.tags, |
| 104 | + }, "", nil |
| 105 | +} |
| 106 | + |
| 107 | +// tagsFromMetric extracts tags from a Prometheus MetricNameLabel. |
| 108 | +func tagsFromMetric(m model.Metric) string { |
| 109 | + tags := make(map[string]interface{}, len(m)-1) |
| 110 | + for l, v := range m { |
| 111 | + if l != model.MetricNameLabel { |
| 112 | + tags[string(l)] = string(v) |
| 113 | + } |
| 114 | + } |
| 115 | + tagsmarshaled, _ := json.Marshal(tags) |
| 116 | + return string(tagsmarshaled) |
| 117 | +} |
| 118 | + |
| 119 | +// Write sends a batch of samples to BigQuery via the client. |
| 120 | +func (c *BigqueryClient) Write(samples model.Samples) error { |
| 121 | + inserter := c.client.Dataset(c.datasetID).Table(c.tableID).Inserter() |
| 122 | + inserter.SkipInvalidRows = true |
| 123 | + ctx, cancel := context.WithTimeout(context.Background(), c.timeout) |
| 124 | + |
| 125 | + batch := make([]*Item, 0, len(samples)) |
| 126 | + |
| 127 | + for _, s := range samples { |
| 128 | + v := float64(s.Value) |
| 129 | + if math.IsNaN(v) || math.IsInf(v, 0) { |
| 130 | + level.Debug(c.logger).Log("msg", "cannot send to BigQuery, skipping sample", "value", v, "sample", s) |
| 131 | + c.ignoredSamples.Inc() |
| 132 | + continue |
| 133 | + } |
| 134 | + |
| 135 | + batch = append(batch, &Item{ |
| 136 | + value: v, |
| 137 | + metricname: string(s.Metric[model.MetricNameLabel]), |
| 138 | + timestamp: s.Timestamp.Time(), |
| 139 | + tags: tagsFromMetric(s.Metric), |
| 140 | + }) |
| 141 | + |
| 142 | + } |
| 143 | + |
| 144 | + if err := inserter.Put(ctx, batch); err != nil { |
| 145 | + if multiError, ok := err.(bigquery.PutMultiError); ok { |
| 146 | + for _, err1 := range multiError { |
| 147 | + for _, err2 := range err1.Errors { |
| 148 | + fmt.Println(err2) |
| 149 | + } |
| 150 | + } |
| 151 | + } |
| 152 | + defer cancel() |
| 153 | + return err |
| 154 | + } |
| 155 | + defer cancel() |
| 156 | + return nil |
| 157 | +} |
| 158 | + |
| 159 | +func concatLabels(labels map[string]string) string { |
| 160 | + // 0xff cannot occur in valid UTF-8 sequences, so use it |
| 161 | + // as a separator here. |
| 162 | + separator := "\xff" |
| 163 | + pairs := make([]string, 0, len(labels)) |
| 164 | + for k, v := range labels { |
| 165 | + pairs = append(pairs, k+separator+v) |
| 166 | + } |
| 167 | + return strings.Join(pairs, separator) |
| 168 | +} |
| 169 | + |
| 170 | +// Name identifies the client as a BigQuery client. |
| 171 | +func (c BigqueryClient) Name() string { |
| 172 | + return "bigquerydb" |
| 173 | +} |
| 174 | + |
| 175 | +// Describe implements prometheus.Collector. |
| 176 | +func (c *BigqueryClient) Describe(ch chan<- *prometheus.Desc) { |
| 177 | + ch <- c.ignoredSamples.Desc() |
| 178 | +} |
| 179 | + |
| 180 | +// Collect implements prometheus.Collector. |
| 181 | +func (c *BigqueryClient) Collect(ch chan<- prometheus.Metric) { |
| 182 | + ch <- c.ignoredSamples |
| 183 | +} |
0 commit comments