/
endpoint-monitor.go
203 lines (165 loc) · 5.32 KB
/
endpoint-monitor.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
package main
import (
"encoding/json"
"fmt"
"io"
"math/rand"
"net/http"
"os"
"strconv"
"time"
// "github.com/gorilla/mux"
"github.com/patdaman/endpoint-monitor/database"
"github.com/patdaman/endpoint-monitor/notify"
"github.com/patdaman/endpoint-monitor/requests"
// "github.com/urfave/cli"
// "database"
// "notify"
// "requests"
"github.com/gorilla/mux"
httpSwagger "github.com/swaggo/http-swagger"
"github.com/urfave/cli"
)
type configParser struct {
NotifyWhen NotifyWhen `json:"notifyWhen"`
Requests []requests.RequestConfig `json:"requests"`
Notifications notify.NotificationTypes `json:"notifications"`
Database database.DatabaseTypes `json:"database"`
Concurrency int `json:"concurrency"`
Port int `json:"port"`
}
type NotifyWhen struct {
MeanResponseCount int `json:"meanResponseCount"`
ErrorCount int `json:"errorCount"`
}
func main() {
// Cli tool setup to get config file path from parameters
app := cli.NewApp()
app.Name = "Endpoint-Monitor"
app.Usage = "Monitor http(s) endpoints \r\nSave telemetry data to Influx DB \r\nSend notifications in multiple formats"
app.Flags = []cli.Flag{
&cli.StringFlag{
Name: "config",
Value: "config.json",
Usage: "location of config file",
},
&cli.StringFlag{
Name: "log",
Value: "",
Usage: "file to save logs",
},
&cli.BoolFlag{
Name: "notify",
Usage: "send notifications on alerts",
},
&cli.BoolFlag{
Name: "test",
Usage: "send test notifications on start",
},
}
app.Action = func(c *cli.Context) error {
if fileExists(c.String("config")) {
if len(c.String("log")) != 0 {
// Log parameter given. Confirm file can be created at given path
if !logFilePathValid(c.String("log")) {
println("Invalid File Path given for parameter --log")
os.Exit(3)
}
}
println("Reading File :", c.String("config"))
// Start monitoring when a valid file path is given
startMonitoring(c.String("config"), c.String("log"), c.Bool("notifyActive"), c.Bool("test"))
} else {
println("Config file not present at the given location: ", c.String("config"), "\nPlease give correct file location using --config parameter")
}
return nil
}
// Run as cli app
app.Run(os.Args)
}
func startMonitoring(configFileName string, logFileName string, notifyActive bool, test bool) {
configFile, err := os.Open(configFileName)
if err != nil {
fmt.Println("Error opening config file:\n", err.Error())
}
// Parse the config file data to configParser struct
jsonParser := json.NewDecoder(configFile)
var config configParser
if err = jsonParser.Decode(&config); err != nil {
fmt.Println("Error parsing config file .Please check format of the file \nParse Error:", err.Error())
os.Exit(3)
}
if notifyActive {
// Setup notification clients
notify.AddNew(config.Notifications)
if test == true {
// Send test notifications to all notification clients
notify.SendTestNotification()
}
}
// Create unique ids for each request date given in config file
reqs, ids := validateAndCreateIdsForRequests(config.Requests)
// Set up and initialize databases
database.AddNew(config.Database)
database.Initialize(ids, config.NotifyWhen.MeanResponseCount, config.NotifyWhen.ErrorCount)
// Initialize and start monitoring all the apis
requests.RequestsInit(reqs, config.Concurrency)
requests.StartMonitoring()
database.EnableLogging(logFileName)
// Just to check Endpoint Monitor is running or not
http.HandleFunc("/", statusHandler)
r := mux.NewRouter()
r.PathPrefix("/swagger/").Handler(httpSwagger.WrapHandler)
if config.Port == 0 {
// Default port
http.ListenAndServe(":7321", r)
} else {
// Port is mentioned in config file
http.ListenAndServe(":"+strconv.Itoa(config.Port), r)
}
}
// Prints program running
func statusHandler(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "Endpoint Monitor is running \n Planning to display useful information in further releases")
}
// Returns whether a file exits or not
func fileExists(name string) bool {
if _, err := os.Stat(name); err != nil {
if os.IsNotExist(err) {
return false
}
}
return true
}
func logFilePathValid(name string) bool {
f, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
defer f.Close()
if err != nil {
return false
}
return true
}
// Checks whether each request in config file has valid data
// Creates unique ids for each request using math/rand
func validateAndCreateIdsForRequests(reqs []requests.RequestConfig) ([]requests.RequestConfig, map[int]int64) {
source := rand.NewSource(time.Now().UnixNano())
random := rand.New(source)
// Array of ids used by database pacakge to calculate mean response time and send notifications
ids := make(map[int]int64, 0)
// Array of new requests data after updating the ids
newreqs := make([]requests.RequestConfig, 0)
for i, requestConfig := range reqs {
validateErr := requestConfig.Validate()
if validateErr != nil {
println("\nInvalid Request data in config file for Request #", i, " ", requestConfig.Url)
println("Error:", validateErr.Error())
os.Exit(3)
}
// Set a random value as id
randInt := random.Intn(1000000)
ids[randInt] = requestConfig.ResponseTime
requestConfig.SetId(randInt)
newreqs = append(newreqs, requestConfig)
}
return newreqs, ids
}