-
Notifications
You must be signed in to change notification settings - Fork 32
/
netbox.go
165 lines (145 loc) · 4.87 KB
/
netbox.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
// Copyright 2020 Netflix Inc
// Author: Colin McIntosh ([email protected])
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package netbox provides a TargetLoader for loading devices from NetBox.
package netbox
import (
"context"
"fmt"
"net"
"strconv"
"time"
"github.com/google/gnxi/utils/xpath"
"github.com/netbox-community/go-netbox/netbox"
"github.com/netbox-community/go-netbox/netbox/client"
"github.com/netbox-community/go-netbox/netbox/client/dcim"
"github.com/openconfig/gnmi/proto/gnmi"
targetpb "github.com/openconfig/gnmi/proto/target"
"github.com/openconfig/gnmi/target"
"github.com/openconfig/gnmi-gateway/gateway/configuration"
"github.com/openconfig/gnmi-gateway/gateway/connections"
"github.com/openconfig/gnmi-gateway/gateway/loaders"
)
const Name = "netbox"
var _ loaders.TargetLoader = new(NetBoxTargetLoader)
type NetBoxTargetLoader struct {
config *configuration.GatewayConfig
last *targetpb.Configuration
apiKey string
client *client.NetBoxAPI
host string
interval time.Duration
}
func init() {
loaders.Register(Name, NewNetBoxTargetLoader)
}
func NewNetBoxTargetLoader(config *configuration.GatewayConfig) loaders.TargetLoader {
return &NetBoxTargetLoader{
config: config,
apiKey: config.TargetLoaders.NetBoxAPIKey,
host: config.TargetLoaders.NetBoxHost,
interval: config.TargetLoaders.NetBoxReloadInterval,
}
}
func (m *NetBoxTargetLoader) GetConfiguration() (*targetpb.Configuration, error) {
resp, err := m.client.Dcim.DcimDevicesList(&dcim.DcimDevicesListParams{
Context: context.Background(),
Tag: &m.config.TargetLoaders.NetBoxIncludeTag,
}, nil)
if err != nil {
if resp != nil {
m.config.Log.Error().Msgf("NetBox devices list response: %s", resp.Error())
}
err = fmt.Errorf("unable to list devices in NetBox with tag '%s': %v", m.config.TargetLoaders.NetBoxIncludeTag, err)
m.config.Log.Error().Msg(err.Error())
return nil, err
}
configs := &targetpb.Configuration{
Target: make(map[string]*targetpb.Target),
Request: make(map[string]*gnmi.SubscribeRequest),
}
var subs []*gnmi.Subscription
for _, x := range m.config.TargetLoaders.NetBoxSubscribePaths {
path, err := xpath.ToGNMIPath(x)
if err != nil {
return nil, fmt.Errorf("unable to parse simple config XPath: %s: %v", x, err)
}
subs = append(subs, &gnmi.Subscription{Path: path})
}
configs.Request["default"] = &gnmi.SubscribeRequest{
Request: &gnmi.SubscribeRequest_Subscribe{
Subscribe: &gnmi.SubscriptionList{
Prefix: &gnmi.Path{},
Subscription: subs,
},
},
}
payload := resp.GetPayload()
if payload != nil {
for _, device := range payload.Results {
if device.PrimaryIP.Address == nil || *device.PrimaryIP.Address == "" {
continue
}
ip, _, err := net.ParseCIDR(*device.PrimaryIP.Address)
if err != nil {
m.config.Log.Error().Msgf("unable to parse IP for NetBox device %s: %v", device.Name, err)
continue
}
ipBytes, _ := ip.MarshalText()
address := string(ipBytes) + ":" + strconv.Itoa(m.config.TargetLoaders.NetBoxDeviceGNMIPort)
configs.Target[*device.Name] = &targetpb.Target{
Addresses: []string{address},
Request: "default",
Credentials: &targetpb.Credentials{
Username: m.config.TargetLoaders.NetBoxDeviceUsername,
Password: m.config.TargetLoaders.NetBoxDevicePassword,
},
}
}
}
if err := target.Validate(configs); err != nil {
return nil, fmt.Errorf("configuration from NetBox loader is invalid: %w", err)
}
return configs, nil
}
func (m *NetBoxTargetLoader) Start() error {
m.client = netbox.NewNetboxWithAPIKey(
m.config.TargetLoaders.NetBoxHost,
m.config.TargetLoaders.NetBoxAPIKey,
)
_, err := m.GetConfiguration() // make sure there are no errors at startup
return err
}
func (m *NetBoxTargetLoader) WatchConfiguration(targetChan chan<- *connections.TargetConnectionControl) error {
for {
targetConfig, err := m.GetConfiguration()
if err != nil {
m.config.Log.Error().Err(err).Msgf("Unable to get target configuration.")
} else {
controlMsg := new(connections.TargetConnectionControl)
if m.last != nil {
for targetName := range m.last.Target {
_, exists := targetConfig.Target[targetName]
if !exists {
controlMsg.Remove = append(controlMsg.Remove, targetName)
}
}
}
controlMsg.Insert = targetConfig
m.last = targetConfig
targetChan <- controlMsg
}
time.Sleep(m.interval)
}
}