-
Notifications
You must be signed in to change notification settings - Fork 219
/
resource_probe.go
228 lines (204 loc) · 6.44 KB
/
resource_probe.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
package syntheticmonitoring
import (
"context"
"encoding/base64"
"fmt"
"log"
"strconv"
"strings"
"github.com/hashicorp/go-cty/cty"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
sm "github.com/grafana/synthetic-monitoring-agent/pkg/pb/synthetic_monitoring"
"github.com/grafana/terraform-provider-grafana/internal/common"
)
func ResourceProbe() *schema.Resource {
return &schema.Resource{
Description: `
Besides the public probes run by Grafana Labs, you can also install your
own private probes. These are only accessible to you and only write data to
your Grafana Cloud account. Private probes are instances of the open source
Grafana Synthetic Monitoring Agent.
* [Official documentation](https://grafana.com/docs/grafana-cloud/synthetic-monitoring/private-probes/)
`,
CreateContext: ResourceProbeCreate,
ReadContext: ResourceProbeRead,
UpdateContext: ResourceProbeUpdate,
DeleteContext: ResourceProbeDelete,
Importer: &schema.ResourceImporter{
StateContext: ImportProbeStateWithToken,
},
Schema: map[string]*schema.Schema{
"id": {
Description: "The ID of the probe.",
Type: schema.TypeString,
Computed: true,
},
"tenant_id": {
Description: "The tenant ID of the probe.",
Type: schema.TypeInt,
Computed: true,
},
"auth_token": {
Description: "The probe authentication token. Your probe must use this to authenticate with Grafana Cloud.",
Type: schema.TypeString,
Computed: true,
Sensitive: true,
},
"name": {
Description: "Name of the probe.",
Type: schema.TypeString,
Required: true,
},
"latitude": {
Description: "Latitude coordinates.",
Type: schema.TypeFloat,
Required: true,
DiffSuppressFunc: common.SchemaDiffFloat32,
},
"longitude": {
Description: "Longitude coordinates.",
Type: schema.TypeFloat,
Required: true,
DiffSuppressFunc: common.SchemaDiffFloat32,
},
"region": {
Description: "Region of the probe.",
Type: schema.TypeString,
Required: true,
},
"labels": {
Description: "Custom labels to be included with collected metrics and logs.",
Type: schema.TypeMap,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
ValidateDiagFunc: func(i interface{}, p cty.Path) diag.Diagnostics {
for k, vInt := range i.(map[string]interface{}) {
v := vInt.(string)
lbl := sm.Label{Name: k, Value: v}
if err := lbl.Validate(); err != nil {
return diag.Errorf(`invalid label "%s=%s": %s`, k, v, err)
}
}
return nil
},
},
"public": {
Description: "Public probes are run by Grafana Labs and can be used by all users. Only Grafana Labs managed public probes will be set to `true`.",
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func ResourceProbeCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
c := meta.(*common.Client).SMAPI
p := makeProbe(d)
res, token, err := c.AddProbe(ctx, *p)
if err != nil {
return diag.FromErr(err)
}
d.SetId(strconv.FormatInt(res.Id, 10))
d.Set("tenant_id", res.TenantId)
d.Set("auth_token", base64.StdEncoding.EncodeToString(token))
return ResourceProbeRead(ctx, d, meta)
}
func ResourceProbeRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
c := meta.(*common.Client).SMAPI
id, err := strconv.ParseInt(d.Id(), 10, 64)
if err != nil {
return diag.FromErr(err)
}
prb, err := c.GetProbe(ctx, id)
if err != nil {
if strings.Contains(err.Error(), "404 Not Found") {
log.Printf("[WARN] removing probe %s from state because it no longer exists", d.Id())
d.SetId("")
return nil
}
return diag.FromErr(err)
}
d.Set("tenant_id", prb.TenantId)
d.Set("name", prb.Name)
d.Set("latitude", prb.Latitude)
d.Set("longitude", prb.Longitude)
d.Set("region", prb.Region)
d.Set("public", prb.Public)
if len(prb.Labels) > 0 {
// Convert []sm.Label into a map before set.
labels := make(map[string]string, len(prb.Labels))
for _, l := range prb.Labels {
labels[l.Name] = l.Value
}
d.Set("labels", labels)
}
return nil
}
func ResourceProbeUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
c := meta.(*common.Client).SMAPI
p := makeProbe(d)
_, err := c.UpdateProbe(ctx, *p)
if err != nil {
return diag.FromErr(err)
}
return ResourceProbeRead(ctx, d, meta)
}
func ResourceProbeDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
c := meta.(*common.Client).SMAPI
var diags diag.Diagnostics
id, _ := strconv.ParseInt(d.Id(), 10, 64)
err := c.DeleteProbe(ctx, id)
if err != nil {
return diag.FromErr(err)
}
d.SetId("")
return diags
}
// makeProbe populates an instance of sm.Probe. We need this for create and
// update calls with the SM API client.
func makeProbe(d *schema.ResourceData) *sm.Probe {
var id int64
if d.Id() != "" {
id, _ = strconv.ParseInt(d.Id(), 10, 64)
}
var labels []sm.Label
for name, value := range d.Get("labels").(map[string]interface{}) {
labels = append(labels, sm.Label{
Name: name,
Value: value.(string),
})
}
return &sm.Probe{
Id: id,
TenantId: int64(d.Get("tenant_id").(int)),
Name: d.Get("name").(string),
Latitude: float32(d.Get("latitude").(float64)),
Longitude: float32(d.Get("longitude").(float64)),
Region: d.Get("region").(string),
Labels: labels,
Public: d.Get("public").(bool),
}
}
// ImportProbeStateWithToken is an implementation of StateContextFunc
// that can be used to pass the ID of the probe and the existing
// auth_token.
func ImportProbeStateWithToken(ctx context.Context, d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) {
parts := strings.SplitN(d.Id(), ":", 2)
// the auth_token is optional
if len(parts) == 2 {
if parts[0] == "" || parts[1] == "" {
return nil, fmt.Errorf("invalid id %q, expected format 'probe_id:auth_token'", d.Id())
}
if _, err := base64.StdEncoding.DecodeString(parts[1]); err != nil {
return nil, fmt.Errorf("invalid auth_token %q, expecting a base64-encoded string", parts[1])
}
if err := d.Set("auth_token", parts[1]); err != nil {
return nil, fmt.Errorf("failed to set auth_token: %s", err)
}
}
d.SetId(parts[0])
return []*schema.ResourceData{d}, nil
}