forked from canonical/iot-devicetwin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.go
164 lines (133 loc) · 4.54 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
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* This file is part of the IoT Device Twin Service
* Copyright 2019 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License version 3, as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
* SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package config
import (
"fmt"
"io/ioutil"
"path"
"strings"
"github.com/everactive/iot-devicetwin/config/keys"
"github.com/everactive/iot-identity/service/cert"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
)
var drivers = []string{"memory", "postgres"}
// MQTTConnect holds the credentials for MQTT connection
type MQTTConnect struct {
ClientID string
RootCA []byte
ClientCert []byte
ClientKey []byte
}
var defaultValues = map[string]interface{}{
keys.CertificatesPath: "/srv/certs",
keys.ConfigPath: "/srv/config",
keys.DatabaseDriver: "postgres",
keys.DatastoreSource: "dbname=management host=localhost user=manager password=abc1234 sslmode=disable",
keys.MQTTClientCertificateFilename: "server.crt",
keys.MQTTClientKeyFilename: "server.key",
keys.MQTTRootCAFilename: "ca.crt",
keys.MQTTClientIDPrefix: "devicetwin",
keys.MQTTHealthTopic: "devices/health/+",
keys.MQTTPort: "8883",
keys.MQTTPubTopic: "devices/pub/+",
keys.MQTTURL: "localhost",
keys.ServicePort: "8040",
}
const (
envPrefix = "IOTDEVICETWIN"
)
// LoadDeviceTwinConfig loads all configuration for the service, including base Viper LoadConfig
func LoadDeviceTwinConfig(configFilePath string) *MQTTConnect {
LoadConfig(configFilePath)
databaseDriver := viper.GetString(keys.DatabaseDriver)
found := false
for i := range drivers {
if drivers[i] == databaseDriver {
found = true
break
}
}
if !found {
log.Fatalf("The database driver must be one of: %s", strings.Join(drivers, ", "))
}
certsDir := viper.GetString(keys.CertificatesPath)
// Get the certificates for the MQTT broker
m, err := readCerts(certsDir)
if err != nil {
log.Fatalf("Error reading certificates: %v", err)
}
return &m
}
// LoadConfig handles loading configuration for Viper using configuration file, environment variables and default values
func LoadConfig(configFilePath string) {
viper.SetEnvPrefix(envPrefix)
viper.AutomaticEnv()
replacer := strings.NewReplacer(".", "_")
viper.SetEnvKeyReplacer(replacer)
if len(configFilePath) > 0 {
viper.SetConfigFile(configFilePath)
} else {
viper.SetConfigFile("config.yaml") // name of config file (without extension)
viper.AddConfigPath(".") // path to look for the config file in
}
// set defaults first
for key, val := range defaultValues {
viper.SetDefault(key, val)
}
err := viper.ReadInConfig() // Find and read the config file
if err != nil { // Handle errors reading the config file
log.Warn("Config file not found, using defaults")
}
for _, key := range viper.AllKeys() {
log.Tracef("%s = %+v", key, viper.Get(key))
}
}
// readCerts reads the certificates from the file system
func readCerts(certsDir string) (MQTTConnect, error) {
rootCAFilename := viper.GetString(keys.MQTTRootCAFilename)
clientCertFilename := viper.GetString(keys.MQTTClientCertificateFilename)
clientKeyFilename := viper.GetString(keys.MQTTClientKeyFilename)
c := MQTTConnect{}
// nolint: gosec
rootCA, err := ioutil.ReadFile(path.Join(certsDir, rootCAFilename))
if err != nil {
return c, err
}
// nolint: gosec
certFile, err := ioutil.ReadFile(path.Join(certsDir, clientCertFilename))
if err != nil {
return c, err
}
// nolint: gosec
key, err := ioutil.ReadFile(path.Join(certsDir, clientKeyFilename))
c.RootCA = rootCA
c.ClientKey = key
c.ClientCert = certFile
c.ClientID = generateClientID()
return c, err
}
func generateClientID() string {
prefix := viper.GetString(keys.MQTTClientIDPrefix)
// Generate a random string
s, err := cert.CreateSecret(6)
if err != nil {
log.Printf("Error creating client ID: %v", err)
}
return fmt.Sprintf("%s-%s", prefix, s)
}