/
config.go
321 lines (296 loc) · 8.97 KB
/
config.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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
/*
###########################################################################
#
# Filename: config.go
#
# Author: Siva Teja Areti
# Created: June 6, 2017
#
# Description: libnetwork plugin config
#
###########################################################################
#
# Copyright (c) 2017 Nuage Networks
#
###########################################################################
*/
package config
import (
"crypto/md5"
"fmt"
log "github.com/Sirupsen/logrus"
"gopkg.in/natefinch/lumberjack.v2"
"gopkg.in/yaml.v2"
"io/ioutil"
"os"
"path"
"strings"
)
//Config data used across packages
const (
LOGDIR = "/var/log/nuage-libnetwork"
LOGFILE = "/var/log/nuage-libnetwork/nuage-libnetwork.log"
PluginDir = "/run/docker/plugins"
PluginName = "nuage"
ContainerIfacePrefix = "eth"
BasePrefix = "nln"
EntityPortKey = "entityport"
BridgePortKey = "brPort"
UUIDKey = "vmuuid"
MACKey = "mac"
NameKey = "name"
PolicyGroupKey = "policy-group"
StaticIPKey = "static-ip"
MaxIntfNum = 4000000
InvalidPortName = -1
BridgeName = "alubr0"
VSDContainerIDKey = "cont-uuid"
UserKey = "NUAGE-USER"
EnterpriseKey = "NUAGE-ENTERPRISE"
DomainKey = "NUAGE-DOMAIN"
ZoneKey = "NUAGE-ZONE"
NetworkKey = "NUAGE-NETWORK"
NetworkTypeKey = "NUAGE-NETWORK-TYPE"
)
var DockerNetworkType = map[string]string{"v1": "nuage", "v2": "nuage:latest"}
var logMessageCounter int
type logTextFormatter log.TextFormatter
//NuageNetworkParams nuage network metadata
type NuageNetworkParams struct {
Organization string
Domain string
Zone string
User string
SubnetName string
SubnetCIDR string
Gateway string
}
//NuageEventMetadata struct contains the metadata required to communicate across channels
type NuageEventMetadata struct {
IPAddress string
UUID string
Name string
PolicyGroup string
OrchestrationID string
NetworkParams *NuageNetworkParams
}
//NuageLibNetworkConfig configuration data for nuage libnetwork remote and ipam drivers
type NuageLibNetworkConfig struct {
NumOfRetries int
TimeInterval int
LogFileSize int
URL string
Port string
Username string
Password string
Organization string
Scope string
LogLevel string
VRSBridge string
VRSSocketFile string
DockerSocketFile string
PluginVersion string
}
//ReadConfigFile reads, validates and sets defaults to config file
func ReadConfigFile(configFile string) (*NuageLibNetworkConfig, error) {
nuageConfigParams, err := loadConfig(configFile)
if err != nil {
log.Errorf("Load config failed with error: %v", err)
return nil, err
}
err = validateConfig(nuageConfigParams)
if err != nil {
log.Errorf("Validating nuage config failed with error: %v", err)
return nil, err
}
return nuageConfigParams, nil
}
func loadConfig(configFile string) (*NuageLibNetworkConfig, error) {
conf := &NuageLibNetworkConfig{}
if configFile != "" {
configData, err := ioutil.ReadFile(configFile)
if err != nil {
log.Errorf("Reading config file failed with error: %v", err)
return nil, err
}
err = parse(configData, conf)
if err != nil {
log.Errorf("Parsing config file failed with error: %v", err)
return nil, err
}
} else {
return nil, fmt.Errorf("No configuration file specified")
}
setDefaultsInConfig(conf)
return conf, nil
}
func validateConfig(conf *NuageLibNetworkConfig) error {
if conf.URL == "" {
return fmt.Errorf("Empty URL found in config file")
}
if conf.Username == "" {
return fmt.Errorf("Empty username found in config file")
}
if conf.Password == "" {
return fmt.Errorf("Empty password found in config file")
}
if conf.Organization == "" {
return fmt.Errorf("Empty organization found in config file")
}
return nil
}
func setDefaultsInConfig(conf *NuageLibNetworkConfig) {
if conf.DockerSocketFile == "" {
log.Warnf("empty docker endpoint. using default value")
conf.DockerSocketFile = "unix:///var/run/docker.sock"
}
if conf.VRSSocketFile == "" {
log.Warnf("empty vrs endpoint. using default value")
conf.VRSSocketFile = "/var/run/openvswitch/db.sock"
}
if conf.VRSBridge == "" {
log.Warnf("empty vrs bridge. using default value \"alubr0\"")
conf.VRSBridge = "alubr0"
}
if conf.LogLevel == "" || (conf.LogLevel != "Debug" && conf.LogLevel != "Info" && conf.LogLevel != "Warn" && conf.LogLevel != "Error") {
log.Warnf("invalid log debug level \"%s\". using default value \"Info\"", conf.LogLevel)
conf.LogLevel = "Warn"
}
if conf.Scope == "" || (conf.Scope != "local" && conf.Scope != "global") {
log.Warnf("invalid scope value %s found. using default value \"global\"", conf.Scope)
conf.Scope = "global"
}
if conf.NumOfRetries == 0 {
log.Warnf("Invalid retry count %d specified. Using default value 5", conf.NumOfRetries)
conf.NumOfRetries = 5
}
if conf.TimeInterval == 0 {
log.Warnf("Invalid time interval %d specified. Using default value 100ms", conf.TimeInterval)
conf.TimeInterval = 100
}
if conf.LogFileSize == 0 {
log.Warnf("Invalid log file size %d specified. Using default value 10MB", conf.LogFileSize)
conf.LogFileSize = 10
}
if conf.PluginVersion == "" {
log.Warnf("Plugin version to be run not found in config file")
conf.PluginVersion = "v1"
}
}
func parse(data []byte, conf *NuageLibNetworkConfig) error {
err := yaml.Unmarshal(data, conf)
if err != nil {
log.Errorf("YAML unmarshal failed with error: %v", err)
return err
}
log.Warnf("Parsed configuration %+v successfully", conf)
return nil
}
//SetupLogging sets up logging infrastructure
func SetupLogging() {
customFormatter := new(logTextFormatter)
log.SetFormatter(customFormatter)
log.SetOutput(&lumberjack.Logger{
Filename: LOGFILE,
MaxSize: 1,
MaxAge: 30,
})
log.SetLevel(log.DebugLevel)
}
//SetLogLevel sets the default log level
func SetLogLevel(conf *NuageLibNetworkConfig) {
var supportedLogLevels = map[string]log.Level{
"debug": log.DebugLevel,
"info": log.InfoLevel,
"warn": log.WarnLevel,
"error": log.ErrorLevel,
}
log.SetOutput(&lumberjack.Logger{
Filename: LOGFILE,
MaxSize: conf.LogFileSize,
MaxAge: 30,
})
log.SetLevel(supportedLogLevels[strings.ToLower(conf.LogLevel)])
}
func createFile(dir, file string) (*os.File, error) {
err := os.MkdirAll(dir, 0700)
if err != nil {
return nil, err
}
handle, err := os.Create(file)
if err != nil {
return nil, err
}
return handle, nil
}
//Format custom format method used by logrus. Prints in standard nuage log format
func (f *logTextFormatter) Format(entry *log.Entry) ([]byte, error) {
logMessageCounter++
outputString := fmt.Sprintf("|%v|%s|%04d|%s|%s\n", entry.Time, strings.ToUpper(log.Level.String(entry.Level)), logMessageCounter, path.Base(os.Args[0]), entry.Message)
for k, v := range entry.Data {
outputString += fmt.Sprintf("|%s=%s|", k, v)
}
return []byte(outputString), nil
}
//ParseNuageParams Parses all the nuage options passed
func ParseNuageParams(networkOptions map[string]string) *NuageNetworkParams {
nuageParams := &NuageNetworkParams{}
for key, val := range networkOptions {
switch key {
case "organization":
nuageParams.Organization = val
case "domain":
nuageParams.Domain = val
case "zone":
nuageParams.Zone = val
case "subnet":
nuageParams.SubnetName = val
case "user":
nuageParams.User = val
default:
log.Warnf("Unknown key[%s] value[%s] found in network options. Ignoring them", key, val)
}
}
log.Debugf("%+v", nuageParams)
return nuageParams
}
//ValidateNuageParams validates the nuage parameters
func ValidateNuageParams(nuageParams *NuageNetworkParams) error {
if nuageParams.Organization == "" || nuageParams.User == "" {
return fmt.Errorf("Organization or User required to create a NuageNet")
}
if nuageParams.Domain == "" {
return fmt.Errorf("Domain Required to create a NuageNet")
}
if nuageParams.Zone == "" || nuageParams.SubnetName == "" {
return fmt.Errorf("If L3Domain, both Zone and Subnets are required")
}
log.Debugf("Validating nuage params is successful")
return nil
}
//IsSameNetworkOpts checks if nuage network options matches
func IsSameNetworkOpts(opts1, opts2 *NuageNetworkParams) bool {
if opts1.Organization != opts2.Organization {
return false
}
if opts1.Domain != opts2.Domain {
return false
}
if opts1.Zone != opts2.Zone {
return false
}
if opts1.SubnetName != opts2.SubnetName {
return false
}
return true
}
//MD5Hash generates md5 hash string for given network options
func MD5Hash(networkOpts *NuageNetworkParams) string {
str := networkOpts.Organization + networkOpts.Domain +
networkOpts.SubnetName
return fmt.Sprintf("%x", md5.Sum([]byte(str)))
}
//String stringifies NuageNetworkParams
func (v NuageNetworkParams) String() string {
return fmt.Sprintf("%s-%s-%s", v.Organization, v.Domain, v.SubnetName)
}