This repository has been archived by the owner on May 19, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconfig.go
352 lines (307 loc) · 8.64 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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
package config
import (
"crypto/rand"
"fmt"
"io"
"math/big"
"os"
"strings"
"time"
"github.com/urfave/cli/v2"
)
var (
NullClient = Client{}
NullOptions = Options{}
)
// Options takes the build information and provides the CLI with correct information
type Options struct {
Version string
Revision string
Created string
// DisableExitOnHelp configures if --help should exit or not, used with helpPrinter()
DisableExitOnHelp bool
}
// Client struct
type Client struct {
BrokerAddresses []string
Topic string
QoS int
KeepAlive time.Duration
ConnectTimeout time.Duration
CleanSession bool
Username string
Password string
ClientID string
MetricsAddress string
MetricsPort int
disableExitOnHelp bool
cliReader io.Reader
cliWriter io.Writer
cliErrWriter io.Writer
version string
revision string
created string
}
// NewClient returns the Client or error
func NewClient(opts Options) (Client, error) {
client := newClient(opts)
generatedCfg, err := client.generateConfig(os.Args)
if err != nil {
return NullClient, err
}
return generatedCfg, nil
}
// GenerateMarkdown creates a markdown file with documentation for the application
func GenerateMarkdown(filePath string) error {
client := newClient(NullOptions)
err := client.generateMarkdown(filePath)
return err
}
func newClient(opts Options) *Client {
return &Client{
disableExitOnHelp: opts.DisableExitOnHelp,
cliReader: os.Stdin,
cliWriter: os.Stdout,
cliErrWriter: os.Stderr,
version: opts.Version,
revision: opts.Revision,
created: opts.Created,
}
}
func (client *Client) generateConfig(args []string) (Client, error) {
app := client.newCLIApp()
err := app.Run(args)
if err != nil {
return NullClient, err
}
return *client, nil
}
func (client *Client) generateMarkdown(filePath string) error {
app := client.newCLIApp()
md, err := app.ToMarkdown()
if err != nil {
return err
}
err = os.WriteFile(filePath, []byte(md), 0666) // #nosec
return err
}
func (client *Client) setConfig(cfg Client) {
client.BrokerAddresses = cfg.BrokerAddresses
client.Topic = cfg.Topic
client.QoS = cfg.QoS
client.KeepAlive = cfg.KeepAlive
client.ConnectTimeout = cfg.ConnectTimeout
client.CleanSession = cfg.CleanSession
client.Username = cfg.Username
client.Password = cfg.Password
client.ClientID = cfg.ClientID
client.MetricsAddress = cfg.MetricsAddress
client.MetricsPort = cfg.MetricsPort
}
func (client *Client) setIO(reader io.Reader, writer io.Writer, errWriter io.Writer) {
client.cliReader = reader
client.cliWriter = writer
client.cliErrWriter = errWriter
}
func (client *Client) newCLIApp() *cli.App {
cli.VersionPrinter = client.versionHandler
cli.HelpPrinter = client.helpPrinter
app := &cli.App{
Name: "mqtt-log-stdout",
Usage: "MQTT client that listens to a topic and prints it to stdout",
Version: client.version,
Flags: client.newCLIFlags(),
Action: client.newCLIAction,
}
app.Writer = client.cliWriter
app.ErrWriter = client.cliErrWriter
app.Reader = client.cliReader
return app
}
func (client *Client) newCLIAction(c *cli.Context) error {
err := client.setConfigFromCLI(c)
return err
}
func (client *Client) newCLIFlags() []cli.Flag {
return []cli.Flag{
&cli.StringSliceFlag{
Name: "mqtt-broker-addresses",
Usage: "The MQTT broker addresses",
Required: true,
EnvVars: []string{"MQTT_BROKER_ADDRESSES", "MQTT_HOST_1", "MQTT_HOST_2", "MQTT_HOST_3"},
},
&cli.StringFlag{
Name: "mqtt-topic",
Usage: "The MQTT topic to output logs for",
Required: true,
EnvVars: []string{"MQTT_TOPIC", "LOG_TOPIC"},
},
&cli.IntFlag{
Name: "mqtt-port",
Usage: "The MQTT port",
Required: false,
EnvVars: []string{"MQTT_PORT"},
Value: 1883,
},
&cli.IntFlag{
Name: "mqtt-qos",
Usage: "The MQTT QoS",
Required: false,
EnvVars: []string{"MQTT_QOS"},
Value: 0,
},
&cli.IntFlag{
Name: "mqtt-keep-alive",
Usage: "The MQTT keep alive interval in seconds (0 = disabled)",
Required: false,
EnvVars: []string{"MQTT_KEEP_ALIVE"},
Value: 0,
},
&cli.IntFlag{
Name: "mqtt-connect-timeout",
Usage: "How long should the MQTT client try to connect to the server? (in seconds)",
Required: false,
EnvVars: []string{"MQTT_CONNECT_TIMEOUT"},
Value: 1,
},
&cli.BoolFlag{
Name: "mqtt-clean-session",
Usage: "Should the MQTT client initiate a clean session when subscribing to the topic?",
Required: false,
EnvVars: []string{"MQTT_CLEAN_SESSION"},
Value: false,
},
&cli.StringFlag{
Name: "mqtt-username",
Usage: "The MQTT username",
Required: false,
EnvVars: []string{"MQTT_USERNAME"},
},
&cli.StringFlag{
Name: "mqtt-password",
Usage: "The MQTT password",
Required: false,
EnvVars: []string{"MQTT_PASSWORD"},
},
&cli.StringFlag{
Name: "mqtt-client-id",
Usage: "The MQTT Client ID (defaults to host name)",
Required: false,
EnvVars: []string{"MQTT_CLIENT_ID"},
},
&cli.BoolFlag{
Name: "mqtt-client-id-random-suffix",
Usage: "Should a suffix be appended to the Client ID",
Required: false,
EnvVars: []string{"MQTT_CLIENT_ID_RANDOM_SUFFIX"},
Value: false,
},
&cli.StringFlag{
Name: "metrics-address",
Usage: "The http address metrics should be exposed on",
Required: false,
EnvVars: []string{"METRICS_ADDRESS"},
Value: "0.0.0.0",
},
&cli.IntFlag{
Name: "metrics-port",
Usage: "The http port metrics should be exposed on",
Required: false,
EnvVars: []string{"METRICS_PORT"},
Value: 8080,
},
}
}
func (client *Client) setConfigFromCLI(cli *cli.Context) error {
flagMqttClientID := cli.String("mqtt-client-id")
flagMqttClientIDRandomSuffix := cli.Bool("mqtt-client-id-random-suffix")
mqttClientID, err := getClientID(flagMqttClientID, flagMqttClientIDRandomSuffix)
if err != nil {
return err
}
flagMqttBrokerAddresses := cli.StringSlice("mqtt-broker-addresses")
flagMqttPort := cli.Int("mqtt-port")
brokerAddresses := getBrokerAddresses(flagMqttBrokerAddresses, flagMqttPort)
flagQoS := cli.Int("mqtt-qos")
qos, err := getQoS(flagQoS)
if err != nil {
return err
}
keepAlive := time.Duration(cli.Int("mqtt-keep-alive")) * time.Second
connectTimeout := time.Duration(cli.Int("mqtt-connect-timeout")) * time.Second
newCfg := Client{
BrokerAddresses: brokerAddresses,
Topic: cli.String("mqtt-topic"),
QoS: qos,
KeepAlive: keepAlive,
ConnectTimeout: connectTimeout,
CleanSession: cli.Bool("mqtt-clean-session"),
Username: cli.String("mqtt-username"),
Password: cli.String("mqtt-password"),
ClientID: mqttClientID,
MetricsAddress: cli.String("metrics-address"),
MetricsPort: cli.Int("metrics-port"),
}
client.setConfig(newCfg)
return nil
}
func (client *Client) versionHandler(c *cli.Context) {
fmt.Printf("version=%s revision=%s created=%s\n", client.version, client.revision, client.created)
os.Exit(0)
}
// helpPrinter uses the default HelpPrinterCustom() but adds an os.Exit(0)
func (client *Client) helpPrinter(out io.Writer, templ string, data interface{}) {
cli.HelpPrinterCustom(out, templ, data, nil)
if !client.disableExitOnHelp {
os.Exit(0)
}
}
func getClientID(clientID string, randomSuffix bool) (string, error) {
hostname, err := os.Hostname()
if err != nil {
return "", err
}
if clientID == "" {
clientID = hostname
}
if randomSuffix {
return getRandomClientID(clientID)
}
return clientID, nil
}
func getRandomClientID(clientID string) (string, error) {
randomString, err := generateRandomString(5)
if err != nil {
return "", err
}
return fmt.Sprintf("%s-%s", clientID, randomString), nil
}
func getBrokerAddresses(brokerAddresses []string, port int) []string {
var newBrokers []string
for _, broker := range brokerAddresses {
b := fmt.Sprintf("tcp://%s:%d", broker, port)
if strings.Contains(broker, ":") {
b = fmt.Sprintf("tcp://%s", broker)
}
newBrokers = append(newBrokers, b)
}
return newBrokers
}
func getQoS(qos int) (int, error) {
if qos < 0 || qos > 1 {
return 0, fmt.Errorf("QoS allowed to be 0 or 1, received: %d", qos)
}
return qos, nil
}
func generateRandomString(n int) (string, error) {
const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
ret := make([]byte, n)
for i := 0; i < n; i++ {
num, err := rand.Int(rand.Reader, big.NewInt(int64(len(letters))))
if err != nil {
return "", err
}
ret[i] = letters[num.Int64()]
}
return string(ret), nil
}