Debian Codegraph @

api/prometheus/v1/example_test.go

raw
1 // Copyright 2019 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
14 // Package v1_test provides examples making requests to Prometheus using the
15 // Golang client.
16 package v1_test
17
18 import (
19 "context"
20 "fmt"
21 "net/http"
22 "os"
23 "time"
24
25 "github.com/prometheus/common/config"
26
27 "github.com/prometheus/client_golang/api"
28 v1 "github.com/prometheus/client_golang/api/prometheus/v1"
29 )
30
31 const DemoPrometheusURL = "https://demo.prometheus.io:443"
32
33 func ExampleAPI_query() {
34 client, err := api.NewClient(api.Config{
35 Address: DemoPrometheusURL,
36 })
37 if err != nil {
38 fmt.Printf("Error creating client: %v\n", err)
39 os.Exit(1)
40 }
41
42 v1api := v1.NewAPI(client)
43 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
44 defer cancel()
45 result, warnings, err := v1api.Query(ctx, "up", time.Now(), v1.WithTimeout(5*time.Second))
46 if err != nil {
47 fmt.Printf("Error querying Prometheus: %v\n", err)
48 os.Exit(1)
49 }
50 if len(warnings) > 0 {
51 fmt.Printf("Warnings: %v\n", warnings)
52 }
53 fmt.Printf("Result:\n%v\n", result)
54 }
55
56 func ExampleAPI_queryRange() {
57 client, err := api.NewClient(api.Config{
58 Address: DemoPrometheusURL,
59 })
60 if err != nil {
61 fmt.Printf("Error creating client: %v\n", err)
62 os.Exit(1)
63 }
64
65 v1api := v1.NewAPI(client)
66 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
67 defer cancel()
68 r := v1.Range{
69 Start: time.Now().Add(-time.Hour),
70 End: time.Now(),
71 Step: time.Minute,
72 }
73 result, warnings, err := v1api.QueryRange(ctx, "rate(prometheus_tsdb_head_samples_appended_total[5m])", r, v1.WithTimeout(5*time.Second))
74 if err != nil {
75 fmt.Printf("Error querying Prometheus: %v\n", err)
76 os.Exit(1)
77 }
78 if len(warnings) > 0 {
79 fmt.Printf("Warnings: %v\n", warnings)
80 }
81 fmt.Printf("Result:\n%v\n", result)
82 }
83
84 type userAgentRoundTripper struct {
85 name string
86 rt http.RoundTripper
87 }
88
89 // RoundTrip implements the http.RoundTripper interface.
90 func (u userAgentRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) {
91 if r.UserAgent() == "" {
92 // The specification of http.RoundTripper says that it shouldn't mutate
93 // the request so make a copy of req.Header since this is all that is
94 // modified.
95 r2 := new(http.Request)
96 *r2 = *r
97 r2.Header = make(http.Header)
98 for k, s := range r.Header {
99 r2.Header[k] = s
100 }
101 r2.Header.Set("User-Agent", u.name)
102 r = r2
103 }
104 return u.rt.RoundTrip(r)
105 }
106
107 func ExampleAPI_queryRangeWithUserAgent() {
108 client, err := api.NewClient(api.Config{
109 Address: DemoPrometheusURL,
110 RoundTripper: userAgentRoundTripper{name: "Client-Golang", rt: api.DefaultRoundTripper},
111 })
112 if err != nil {
113 fmt.Printf("Error creating client: %v\n", err)
114 os.Exit(1)
115 }
116
117 v1api := v1.NewAPI(client)
118 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
119 defer cancel()
120 r := v1.Range{
121 Start: time.Now().Add(-time.Hour),
122 End: time.Now(),
123 Step: time.Minute,
124 }
125 result, warnings, err := v1api.QueryRange(ctx, "rate(prometheus_tsdb_head_samples_appended_total[5m])", r)
126 if err != nil {
127 fmt.Printf("Error querying Prometheus: %v\n", err)
128 os.Exit(1)
129 }
130 if len(warnings) > 0 {
131 fmt.Printf("Warnings: %v\n", warnings)
132 }
133 fmt.Printf("Result:\n%v\n", result)
134 }
135
136 func ExampleAPI_queryRangeWithBasicAuth() {
137 client, err := api.NewClient(api.Config{
138 Address: DemoPrometheusURL,
139 // We can use amazing github.com/prometheus/common/config helper!
140 RoundTripper: config.NewBasicAuthRoundTripper(
141 config.NewInlineSecret("me"),
142 config.NewInlineSecret("definitely_me"),
143 api.DefaultRoundTripper,
144 ),
145 })
146 if err != nil {
147 fmt.Printf("Error creating client: %v\n", err)
148 os.Exit(1)
149 }
150
151 v1api := v1.NewAPI(client)
152 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
153 defer cancel()
154 r := v1.Range{
155 Start: time.Now().Add(-time.Hour),
156 End: time.Now(),
157 Step: time.Minute,
158 }
159 result, warnings, err := v1api.QueryRange(ctx, "rate(prometheus_tsdb_head_samples_appended_total[5m])", r)
160 if err != nil {
161 fmt.Printf("Error querying Prometheus: %v\n", err)
162 os.Exit(1)
163 }
164 if len(warnings) > 0 {
165 fmt.Printf("Warnings: %v\n", warnings)
166 }
167 fmt.Printf("Result:\n%v\n", result)
168 }
169
170 func ExampleAPI_queryRangeWithAuthBearerToken() {
171 client, err := api.NewClient(api.Config{
172 Address: DemoPrometheusURL,
173 // We can use amazing github.com/prometheus/common/config helper!
174 RoundTripper: config.NewAuthorizationCredentialsRoundTripper(
175 "Bearer",
176 config.NewInlineSecret("secret_token"),
177 api.DefaultRoundTripper,
178 ),
179 })
180 if err != nil {
181 fmt.Printf("Error creating client: %v\n", err)
182 os.Exit(1)
183 }
184
185 v1api := v1.NewAPI(client)
186 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
187 defer cancel()
188 r := v1.Range{
189 Start: time.Now().Add(-time.Hour),
190 End: time.Now(),
191 Step: time.Minute,
192 }
193 result, warnings, err := v1api.QueryRange(ctx, "rate(prometheus_tsdb_head_samples_appended_total[5m])", r)
194 if err != nil {
195 fmt.Printf("Error querying Prometheus: %v\n", err)
196 os.Exit(1)
197 }
198 if len(warnings) > 0 {
199 fmt.Printf("Warnings: %v\n", warnings)
200 }
201 fmt.Printf("Result:\n%v\n", result)
202 }
203
204 func ExampleAPI_queryRangeWithAuthBearerTokenHeadersRoundTripper() {
205 client, err := api.NewClient(api.Config{
206 Address: DemoPrometheusURL,
207 // We can use amazing github.com/prometheus/common/config helper!
208 RoundTripper: config.NewHeadersRoundTripper(
209 &config.Headers{
210 Headers: map[string]config.Header{
211 "Authorization": {
212 Values: []string{"Bearer secret"},
213 },
214 },
215 },
216 api.DefaultRoundTripper,
217 ),
218 })
219 if err != nil {
220 fmt.Printf("Error creating client: %v\n", err)
221 os.Exit(1)
222 }
223
224 v1api := v1.NewAPI(client)
225 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
226 defer cancel()
227 r := v1.Range{
228 Start: time.Now().Add(-time.Hour),
229 End: time.Now(),
230 Step: time.Minute,
231 }
232 result, warnings, err := v1api.QueryRange(ctx, "rate(prometheus_tsdb_head_samples_appended_total[5m])", r)
233 if err != nil {
234 fmt.Printf("Error querying Prometheus: %v\n", err)
235 os.Exit(1)
236 }
237 if len(warnings) > 0 {
238 fmt.Printf("Warnings: %v\n", warnings)
239 }
240 fmt.Printf("Result:\n%v\n", result)
241 }
242
243 func ExampleAPI_series() {
244 client, err := api.NewClient(api.Config{
245 Address: DemoPrometheusURL,
246 })
247 if err != nil {
248 fmt.Printf("Error creating client: %v\n", err)
249 os.Exit(1)
250 }
251
252 v1api := v1.NewAPI(client)
253 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
254 defer cancel()
255 lbls, warnings, err := v1api.Series(ctx, []string{
256 "{__name__=~\"scrape_.+\",job=\"node\"}",
257 "{__name__=~\"scrape_.+\",job=\"prometheus\"}",
258 }, time.Now().Add(-time.Hour), time.Now())
259 if err != nil {
260 fmt.Printf("Error querying Prometheus: %v\n", err)
261 os.Exit(1)
262 }
263 if len(warnings) > 0 {
264 fmt.Printf("Warnings: %v\n", warnings)
265 }
266 fmt.Println("Result:")
267 for _, lbl := range lbls {
268 fmt.Println(lbl)
269 }
270 }