-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
339 lines (271 loc) · 9.85 KB
/
index.js
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
let AWS = require("aws-sdk");
const ShortUniqueId = require('short-unique-id');
const Notifications = require("./Notifications");
const Template = require('./Template');
AWS.config.update({
region: "us-east-2",
});
let config = {
tableName : "SERVICE-LOGS",
mailList : [],
stage : "Dev",
mailSubject : "New AWS Log",
sourceEmail : false,
notifyOnSeverityLevel : 10,
serviceName : null,
enableNotifications : false,
region : "us-east-2",
/**
* @param {any} config
*/
update(config) {
if(config.tableName)
this.tableName = config.tableName;
if(config.mailList && Array.isArray(config.mailList)){
for (let i = 0 ; i < config.mailList.length ; i ++ )
{
if(Notifications.validateEmail(config.mailList[i]))
this.mailList[i] = config.mailList[i];
else
console.log(`${config.mailList[i]} is not a valid Email`);
}
}
if(config.mailSubject)
this.mailSubject = config.mailSubject;
if(config.notifyOnSeverityLevel)
this.notifyOnSeverityLevel = config.notifyOnSeverityLevel;
if(config.serviceName)
this.serviceName = config.serviceName;
if(config.stage)
this.stage = config.stage;
if(config.enableNotifications)
this.enableNotifications = config.enableNotifications;
if(config.region){
AWS.config.update({region:config.region});
this.region = config.region;
}
if(config.sourceEmail){
if(Notifications.validateEmail(config.sourceEmail))
Notifications.isVerified(config.sourceEmail).then(res => {
console.log(res);
if(Boolean(res) === true) this.sourceEmail = config.sourceEmail;
else console.log(`"${config.sourceEmail}" Must be a verified Email or Domain in your AWS account. Configure this in SES settings in your AWS account`);
});
else
console.log(`${config.sourceEmail} is not a valid Email`);
}
if(config.accessKeyId && config.secretAccessKey)
{
AWS.config.update(
{
accessKeyId : config.accessKeyId,
secretAccessKey : config.secretAccessKey
}
);
}
}
};
const tableExists = () =>
new Promise((resolve, reject)=> {
try {
AWS.config.update({
region: config.region,
});
let dynamodb = new AWS.DynamoDB();
console.log("Check table: " + config.tableName);
var params = {
TableName: config.tableName /* required */
};
dynamodb.describeTable(params, function(err, data) {
if (err) {
console.error(`** WARNING ** -- Table "${config.tableName}" Resource not found.`,err.message); // an error occurred
resolve(false);
}
else {
console.log(`** LOG ** -- Table "${config.tableName}" Resource was found`); // successful response
resolve(true);
}
});
} catch (error) {
console.error(`** ERROR ** -- Table "${config.tableName}" resource not found`,error.message); // an error occurred
resolve(false);
}
});
const createTable = () =>
{
try {
console.log(`** LOG ** -- Creating "${config.tableName}" Resource...`);
AWS.config.update({
region: config.region,
});
var dynamodb = new AWS.DynamoDB();
var params = {
TableName : config.tableName,
KeySchema: [
{ AttributeName: "ID", KeyType: "HASH"},
{ AttributeName: "TIMESTAMP", KeyType: "RANGE"}
],
AttributeDefinitions: [
{ AttributeName: "ID", AttributeType: "S"},
{ AttributeName: "TIMESTAMP", AttributeType: "N"},
{ AttributeName: "TYPE", AttributeType: "S" },
{ AttributeName: "SERVICE", AttributeType: "S" },
{ AttributeName: "MESSAGE", AttributeType: "S" },
],
GlobalSecondaryIndexes: [
{
IndexName: "TypeIndex",
KeySchema: [
{
AttributeName: "TYPE",
KeyType: "HASH"
}
],
Projection: {
ProjectionType: "ALL"
},
},
{
IndexName: "TypeService",
KeySchema: [
{
AttributeName: "SERVICE",
KeyType: "HASH"
}
],
Projection: {
ProjectionType: "ALL"
},
},
{
IndexName: "TypeMessage",
KeySchema: [
{
AttributeName: "MESSAGE",
KeyType: "HASH"
}
],
Projection: {
ProjectionType: "ALL"
},
}
],
BillingMode: "PAY_PER_REQUEST"
};
dynamodb.createTable(params, function(tableErr, tableData) {
if (tableErr) {
console.error(`** ERROR ** -- Table "${config.tableName}" Resource was NOT created.`,tableErr); // an error occurred
return false;
} else {
console.log(`** LOG ** -- Table "${config.tableName}" Resource was Created!`);
return true;
}
});
} catch (error) {
console.error(`** ERROR ** -- Table "${config.tableName}" resource not found`,error); // an error occurred
return false;
}
};
const safetyCheck = () =>
new Promise(async (resolve, reject)=> {
try {
const made = await tableExists();
if(!made)
createTable();
resolve(made);
} catch (error) {
console.log(error);
resolve(false);
}
});
const Save = (message, type = "INFO", severity=0, details = false) =>
new Promise(async (resolve, reject)=> {
try {
if (!config.tableName || typeof config.tableName !== "string")
throw new Error("Table Name was not configured");
if (!config.region || typeof config.region !== "string")
throw new Error("Region was not configured");
if (!config.serviceName || typeof config.serviceName !== "string")
throw new Error("Service Name was not configured");
if (!type || typeof type !== "string" || (type !== "INFO" && type !== "WARN" && type !== "ERROR"))
throw new Error("Not a Valid Log type");
if (!message || typeof message !== "string")
throw new Error("Log message required");
await safetyCheck();
let dynamoDB = new AWS.DynamoDB.DocumentClient({
apiVersion: "2012-08-10",
});
//Notification Trigger
if(Boolean(config.enableNotifications) === true && severity && severity >= config.notifyOnSeverityLevel){
if(Array.isArray(config.mailList) && config.mailList.length > 0){
console.log(config.sourceEmail)
if(config.sourceEmail){
if(details)
await Notifications.sendMail(message,config.mailList,config.mailSubject,Template.generateReportTemplateWithDetails(message,Date.now().toLocaleString(),config.serviceName,severity,details,type),config.sourceEmail);
else
await Notifications.sendMail(message,config.mailList,config.mailSubject,Template.generateReportTemplate(message,Date.now().toLocaleString(),config.serviceName,severity,type),config.sourceEmail);
}
else
console.error("Source Email was not configured");
}
else
console.error("Reciever List was not configured");
}
const uid = new ShortUniqueId({ length: 13 });
let Log = {
ID : uid(),
TIMESTAMP : Date.now(),
SERVICE : config.serviceName,
TYPE : type,
MESSAGE : message,
SEVERITY : severity,
STAGE : config.stage
};
if(details)
Log.Details = JSON.stringify(details);
const parameters = {
TableName: config.tableName,
Item: Log,
};
await dynamoDB.put(parameters).promise();
console.log("Log saved -- ID : ", Log.ID);
resolve(true);
} catch (err) {
console.error("Log save Error: ", err);
resolve(false);
}
});
const logit = (message, severity, details, type) =>
new Promise(async (resolve, reject)=> {
try {
if(details)
console.log(message, details);
else
console.log(message);
await Save(message,type,severity,details);
resolve(true);
} catch (error) {
console.log(error);
resolve(false);
}
});
const l = (message, details = false, severity = 1) =>
logit(message, severity, details, "INFO");
const w = (message, details = false, severity = 2) =>
logit(message, severity, details, "WARN");
const e = (message, details = false, severity = 3) =>
logit(message, severity, details, "ERROR");
const log = (message, severity=1,details = false) =>
logit(message, severity, details, "INFO");
const warn = (message, severity=2,details = false) =>
logit(message, severity, details, "WARN");
const error = (message, severity=3,details = false) =>
logit(message, severity, details, "ERROR");
exports.safetyCheck = safetyCheck;
exports.e = e;
exports.l = l;
exports.w = w;
exports.log = log;
exports.warn = warn;
exports.error = error;
exports.config = config;