-
Notifications
You must be signed in to change notification settings - Fork 11
/
alerts.go
194 lines (160 loc) · 7.24 KB
/
alerts.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
// Copyright (c) 2020 Sorint.lab S.p.A.
//
// 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 <http://www.gnu.org/licenses/>.
package controller
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"time"
"github.com/360EntSecGroup-Skylar/excelize"
"github.com/ercole-io/ercole/model"
"github.com/ercole-io/ercole/utils"
"github.com/golang/gddo/httputil"
"go.mongodb.org/mongo-driver/bson/primitive"
)
// SearchAlerts search alerts using the filters in the request
func (ctrl *APIController) SearchAlerts(w http.ResponseWriter, r *http.Request) {
var mode string
var search string
var sortBy string
var sortDesc bool
var pageNumber int
var pageSize int
var location string
var environment string
var severity string
var status string
var from time.Time
var to time.Time
var err utils.AdvancedErrorInterface
mode = r.URL.Query().Get("mode")
if mode == "" {
mode = "all"
} else if mode != "all" && mode != "aggregated-code-severity" && mode != "aggregated-category-severity" {
utils.WriteAndLogError(ctrl.Log, w, http.StatusUnprocessableEntity, utils.NewAdvancedErrorPtr(errors.New("Invalid mode value"), http.StatusText(http.StatusUnprocessableEntity)))
return
}
search = r.URL.Query().Get("search")
sortBy = r.URL.Query().Get("sort-by")
if sortDesc, err = utils.Str2bool(r.URL.Query().Get("sort-desc"), false); err != nil {
utils.WriteAndLogError(ctrl.Log, w, http.StatusUnprocessableEntity, err)
return
}
if pageNumber, err = utils.Str2int(r.URL.Query().Get("page"), -1); err != nil {
utils.WriteAndLogError(ctrl.Log, w, http.StatusUnprocessableEntity, err)
return
}
if pageSize, err = utils.Str2int(r.URL.Query().Get("size"), -1); err != nil {
utils.WriteAndLogError(ctrl.Log, w, http.StatusUnprocessableEntity, err)
return
}
location = r.URL.Query().Get("location")
environment = r.URL.Query().Get("environment")
severity = r.URL.Query().Get("severity")
if severity != "" && severity != model.AlertSeverityWarning && severity != model.AlertSeverityCritical && severity != model.AlertSeverityInfo {
utils.WriteAndLogError(ctrl.Log, w, http.StatusUnprocessableEntity, utils.NewAdvancedErrorPtr(errors.New("invalid severity"), "Invalid severity"))
return
}
status = r.URL.Query().Get("status")
if status != "" && status != model.AlertStatusNew && status != model.AlertStatusAck {
utils.WriteAndLogError(ctrl.Log, w, http.StatusUnprocessableEntity, utils.NewAdvancedErrorPtr(errors.New("invalid status"), "Invalid status"))
return
}
if from, err = utils.Str2time(r.URL.Query().Get("from"), utils.MIN_TIME); err != nil {
utils.WriteAndLogError(ctrl.Log, w, http.StatusUnprocessableEntity, err)
return
}
if to, err = utils.Str2time(r.URL.Query().Get("to"), utils.MAX_TIME); err != nil {
utils.WriteAndLogError(ctrl.Log, w, http.StatusUnprocessableEntity, err)
return
}
contentType := httputil.NegotiateContentType(r, []string{"application/json", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}, "application/json")
switch contentType {
case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
if mode != "all" {
utils.WriteAndLogError(ctrl.Log, w, http.StatusBadRequest,
utils.NewAdvancedErrorPtr(fmt.Errorf("only mode 'all' is acceptable for xlsx"), http.StatusText(http.StatusBadRequest)))
return
}
ctrl.searchAlertsXLSX(w, r, search, sortBy, sortDesc, pageNumber, pageSize, location, environment, severity, status, from, to)
default:
ctrl.searchAlertsJSON(w, r, mode, search, sortBy, sortDesc, pageNumber, pageSize, location, environment, severity, status, from, to)
}
}
// searchAlertsJSON search alerts using the filters in the request returning it in JSON format
func (ctrl *APIController) searchAlertsJSON(w http.ResponseWriter, r *http.Request,
mode string, search string, sortBy string, sortDesc bool, pageNumber int, pageSize int,
location, environment, severity string, status string, from time.Time, to time.Time) {
response, err := ctrl.Service.SearchAlerts(mode, search, sortBy, sortDesc, pageNumber, pageSize, location, environment, severity, status, from, to)
if err != nil {
utils.WriteAndLogError(ctrl.Log, w, http.StatusInternalServerError, err)
return
}
if pageNumber == -1 || pageSize == -1 {
utils.WriteJSONResponse(w, http.StatusOK, response)
} else {
alerts := response[0]
utils.WriteJSONResponse(w, http.StatusOK, alerts)
}
}
// searchAlertsXLSX search alerts using the filters in the request returning it in XLSX format
func (ctrl *APIController) searchAlertsXLSX(w http.ResponseWriter, r *http.Request,
search string, sortBy string, sortDesc bool, pageNumber int, pageSize int,
location, environment, severity string, status string, from time.Time, to time.Time) {
response, aerr := ctrl.Service.SearchAlerts("all", search, sortBy, sortDesc, pageNumber, pageSize, location, environment, severity, status, from, to)
if aerr != nil {
utils.WriteAndLogError(ctrl.Log, w, http.StatusInternalServerError, aerr)
return
}
//TODO Move in service
sheets, err := excelize.OpenFile(ctrl.Config.ResourceFilePath + "/templates/template_alerts.xlsx")
if err != nil {
utils.WriteAndLogError(ctrl.Log, w, http.StatusInternalServerError, utils.NewAdvancedErrorPtr(err, "READ_TEMPLATE"))
return
}
for i, val := range response {
sheets.SetCellValue("Alerts", fmt.Sprintf("A%d", i+2), val["alertCategory"])
sheets.SetCellValue("Alerts", fmt.Sprintf("B%d", i+2), val["date"].(primitive.DateTime).Time().UTC().String())
sheets.SetCellValue("Alerts", fmt.Sprintf("C%d", i+2), val["alertSeverity"])
sheets.SetCellValue("Alerts", fmt.Sprintf("D%d", i+2), val["hostname"])
sheets.SetCellValue("Alerts", fmt.Sprintf("E%d", i+2), val["alertCode"])
sheets.SetCellValue("Alerts", fmt.Sprintf("F%d", i+2), val["description"])
}
utils.WriteXLSXResponse(w, sheets)
}
// AckAlerts ack the specified alert in the request
func (ctrl *APIController) AckAlerts(w http.ResponseWriter, r *http.Request) {
if ctrl.Config.APIService.ReadOnly {
utils.WriteAndLogError(ctrl.Log, w, http.StatusForbidden, utils.NewAdvancedErrorPtr(errors.New("The API is disabled because the service is put in read-only mode"), "FORBIDDEN_REQUEST"))
return
}
var ids []primitive.ObjectID
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(&ids); err != nil {
utils.WriteAndLogError(ctrl.Log, w, http.StatusBadRequest,
utils.NewAdvancedErrorPtr(err, http.StatusText(http.StatusBadRequest)))
return
}
aerr := ctrl.Service.AckAlerts(ids)
if aerr == utils.AerrAlertNotFound {
utils.WriteAndLogError(ctrl.Log, w, http.StatusNotFound, aerr)
} else if aerr != nil {
utils.WriteAndLogError(ctrl.Log, w, http.StatusInternalServerError, aerr)
return
}
utils.WriteJSONResponse(w, http.StatusOK, nil)
}