-
Notifications
You must be signed in to change notification settings - Fork 0
/
packetmd.go
112 lines (100 loc) · 2.51 KB
/
packetmd.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
package packetmd
import (
"regexp"
"strings"
"github.com/packethost/packngo"
)
// KV represents a key-value pair stored in a device tag
type KV struct {
Key string
Value string
}
// GetKVPairs will parse a device's tags looking for tags of the form `key=value` where the delimiter (=) can be set to an arbitrary string
func GetKVPairs(tags []string, delimiter string) ([]*KV, error) {
pairs := make([]*KV, 0)
if delimiter == "" {
delimiter = "="
}
for _, tag := range tags { // loop through the device tags
// match any tag that is of the form key=value
matched, err := regexp.MatchString(".+"+delimiter+".+", tag)
if err != nil {
return nil, err
}
// if the tag doesn't match this, skip it
if !matched {
continue
}
// split the tag on the delimiter, but only into two parts
split := strings.SplitN(tag, delimiter, 2)
if len(split) < 2 {
continue
}
pairs = append(pairs, &KV{
Key: split[0],
Value: split[1],
})
}
return pairs, nil
}
// GetKVsByKey searches all the KV pairs on a device and filters based on a key
func GetKVsByKey(tags []string, key, delimiter string) ([]*KV, error) {
kvs, err := GetKVPairs(tags, delimiter)
if err != nil {
return nil, err
}
foundKvs := make([]*KV, 0)
for _, kv := range kvs {
if kv.Key == key {
foundKvs = append(foundKvs, kv)
}
}
return foundKvs, nil
}
// AddTag adds a tag to a packet device
func AddTag(client *packngo.Client, deviceID, tag string) error {
device, _, err := client.Devices.Get(deviceID)
if err != nil {
return err
}
tags := append(device.Tags, tag)
client.Devices.Update(deviceID, &packngo.DeviceUpdateRequest{
Tags: &tags,
})
return nil
}
// RemoveTag removes a tag from a packet device
func RemoveTag(client *packngo.Client, deviceID, tag string) error {
device, _, err := client.Devices.Get(deviceID)
if err != nil {
return err
}
tags := make([]string, 0)
for _, t := range device.Tags {
if t != tag {
tags = append(tags, t)
}
}
client.Devices.Update(deviceID, &packngo.DeviceUpdateRequest{
Tags: &tags,
})
return nil
}
// UpdateTag updates an existing tag on a packet device. If it can't find the tag, nothing happens
func UpdateTag(client *packngo.Client, deviceID, tag, newTag string) error {
device, _, err := client.Devices.Get(deviceID)
if err != nil {
return err
}
tags := make([]string, 0)
for _, t := range device.Tags {
if t == tag {
t = newTag
}
tags = append(tags, t)
}
client.Devices.Update(deviceID, &packngo.DeviceUpdateRequest{
Tags: &tags,
})
return nil
}