-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
171 lines (152 loc) · 4.57 KB
/
main.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
// main.go - Main Program
//
// ॐ भूर्भुवः स्वः
// तत्स॑वि॒तुर्वरे॑ण्यं॒
// भर्गो॑ दे॒वस्य॑ धीमहि।
// धियो॒ यो नः॑ प्रचो॒दया॑त्॥
//
//
// बोसजी के द्वारा रचित गो-मिल तन्त्राक्ष्
// ============================
//
// यह गो-क्रमादेश आधारित एम.क्यू.टी.टी अधिलेख में प्रचालेखन का तन्त्राक्ष् है।
//
// एक रचनात्मक भारतीय उत्पाद।
//
// go-mli - Boseji's Golang MQTT Logging command line
//
// Easy to use Golang based MQTT Command line logger.
//
// Sources
// -------
// https://github.com/boseji/go-mli
//
// License
// -------
//
// SPDX: GPL-3.0-or-later
//
// go-mli - Boseji's Golang MQTT Logging command line
// Copyright (C) 2024 by Abhijit Bose (aka. Boseji)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program. If not, see <https://www.gnu.org/licenses/>.
//
// Main Program
package main
import (
"context"
"flag"
"log"
"os"
"os/signal"
"path/filepath"
"sync"
"time"
)
func main() {
var wg sync.WaitGroup
var cfg cfg
// Context
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Define Flags
cfgFile := flag.String("config", "config.json",
"JSON File containing the Configuration.")
flag.Parse()
log.Println("[main] Flag ", flag.Parsed())
// Get the Config File
configFile, err := filepath.Abs(*cfgFile)
if err != nil {
log.Fatalf("[main][ERROR] Failed to get the Path for %q\n", *cfgFile)
}
// Check if the Config File exists
if _, err := os.Stat(configFile); os.IsNotExist(err) {
log.Fatalf("[main][ERROR] Configuration file does not exists.")
}
// Load Configuration
err = cfg.Load(configFile)
if err != nil {
log.Fatalf("[main][ERROR] Failed to load the Config file %q -\n%v",
configFile, err)
}
// Load Message
log.Println("[main] `go-mli` Boseji's Golang MQTT Logging command line")
log.Println("[main] Configuration Loaded -", configFile)
log.Println("[main] Present Configuration: \n", cfg)
// Create the Handlers
loggingFile := time.Now().Format("log-2006-01-02T15-04-05.csv")
logChan := make(chan string, len(cfg.Topics)*2)
recFn := getRecorder(logChan, ctx, &wg, STORE_WAIT*2)
// Handle Ctrl+C
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, os.Interrupt)
exitChan := make(chan struct{})
isError := false
// Start the Storage Process
wg.Add(1)
go storeGoroutine(logChan, ctx, &wg, loggingFile)
// Ctrl+C Go Routine
wg.Add(1) // For the Ctrl+C Go Routine
go func() {
defer wg.Done()
select {
case <-signalChan: // first signal, cancel context
cancel()
log.Println()
log.Println("[INTR] Intercepted a Ctrl+C..")
break
case <-ctx.Done():
log.Println("[INTR][ERROR] Intercepted Error..")
signal.Stop(signalChan)
isError = true
break
}
signal.Stop(signalChan)
close(exitChan) // For Exit
}()
// Create MQTT Connection
mqttOptions := setupMQTT(cfg, cancel, recFn)
client, err := connectMQTT(mqttOptions)
if err != nil {
log.Printf("[main][ERROR] Failed to connect to the MQTT Broker - \n %v", err)
cancel()
}
// Subscribe to the desired topics
for _, topic := range cfg.Topics {
err = subscribeMQTT(client, topic)
if err != nil {
log.Printf("[main][ERROR] Failed to subscribe to %q\n %v\n",
topic, err)
cancel()
}
}
// Wait for Exit with SIGINT or SIGKILL
<-exitChan
log.Println("[main] Closing connection..")
err = disconnectMQTT(client, 20)
if err != nil {
log.Printf("[main][ERROR] Failed to close MQTT Connection : %v\n", err)
cancel()
}
// Error in exit
if isError {
log.Println("[main][ERROR] Exiting due an Error or failure.")
os.Exit(1)
}
// Wait for Every GoRoutine to Terminate
wg.Wait()
// Just to Satisfy Make
log.Println("[main] Program Terminated Normally.")
os.Exit(0)
}