-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
188 lines (159 loc) · 4.34 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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
package main
import (
"context"
"errors"
"fmt"
"os"
"strconv"
"strings"
"time"
"orion/config"
"orion/helpers"
"orion/logger"
"orion/mail"
"orion/models"
"github.com/go-redis/redis/v8"
_ "github.com/lib/pq"
"github.com/roylee0704/gron"
"github.com/xuri/excelize/v2"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
var dbConn *gorm.DB
var isConfigSuccess = false
var equals string = strings.Repeat("=", 50)
// Every 1 minutes
var repeatTime = 1 * time.Minute
// ignored error messages array
var ignoredErrorMessages = []string{
// ignored error messages here
}
// To Users
var toUsers = []string{
// team members here
}
// CC Users
var ccUsers = []string{
// team members here
}
func main() {
// Connect to the database
dbConn = dbConnection()
// Run the task every minute using the gron library
c := gron.New()
c.AddFunc(gron.Every(repeatTime), func() {
// Query the TARGET table and retrieve changes
changes, err := getTableChanges(dbConn)
if err != nil {
panic(err)
}
// Handle the changes
fmt.Println(equals)
if len(changes) > 0 {
for _, change := range changes {
logger.CLogger.Info("INFO: ", strconv.Itoa(change.ID)+" - "+change.ErrorMessage)
}
// Filter the changes
filteredChanges := helpers.FilterChanges(changes, ignoredErrorMessages)
if len(filteredChanges) > 0 {
for _, v := range filteredChanges {
logger.CLogger.Info("TRACE: ", strconv.Itoa(v.ID)+" - "+v.ErrorMessage)
}
f := helpers.SetChangesToExcel(filteredChanges)
sendMailWithAttachment(filteredChanges, f)
}
} else {
logger.CLogger.Info("INFO: No changes in the last minute.")
}
fmt.Println(equals)
})
c.Start()
// Infinite loop to keep the program running
select {}
}
// Initialize Application
func init() {
isConfigSuccess = configureApplication()
if !isConfigSuccess {
logger.CLogger.Error("INIT: Application configuration failed. Please check your config file.")
os.Exit(1)
}
}
// Configure Application
func configureApplication() bool {
// Clear the terminal screen
fmt.Println(equals)
dir, err := os.Getwd()
if err != nil {
logger.CLogger.Info("INIT: Cannot get current working directory os.Getwd()")
return false
} else {
config.ReadConfig(dir)
logger.CLogger.Info("INIT: Application configuration file read success.")
return true
}
}
// DB Connection
func dbConnection() *gorm.DB {
env := config.C.DB
// String to Int
port, err := strconv.Atoi(env.Port)
if err != nil {
logger.CLogger.Error("ERROR: ", err)
os.Exit(1)
}
// Connect to the "postgres" database
dbInfo := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=%s", env.Host, port, env.Username, env.Password, env.DBName, env.SSLMode)
db, err := gorm.Open(postgres.Open(dbInfo), &gorm.Config{})
if err != nil {
logger.CLogger.Error("ERROR: ", err)
os.Exit(1)
}
// Connection Success
logger.CLogger.Success("PostgreSQL Database Connection Success")
return db
}
// Redis Connection
func redisConnection(redisUrl string) (*redis.Client, context.Context) {
// redis://username:password@host:port/db
_, username, password, host, port, db := helpers.UrlToOptions(redisUrl)
// convert db to int
dbInt, err := strconv.Atoi(db)
if err != nil {
logger.CLogger.Success("INIT: redis connection database is not integer ", err)
}
rContext := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: host + ":" + port,
Username: username,
Password: password,
DB: dbInt,
})
// ping redis for check connection
_, err = rdb.Ping(rContext).Result()
if err != nil {
logger.CLogger.Error("INIT: redis ping request failed ", err)
}
return rdb, rContext
}
func getTableChanges(db *gorm.DB) ([]models.Log, error) {
// Get the changes in the last minute and not null error_message from TARGET table
var logs []models.Log
// Last Minute Changes
if err := db.Where("date_time >= ?", helpers.TimeFormatter(time.Now().Add(-repeatTime))).Where("error_message IS NOT NULL").Find(&logs).Error; !errors.Is(err, nil) {
logger.CLogger.Error("ERROR: ", err)
return nil, err
}
return logs, nil
}
// Send Mail with Excel File
func sendMailWithAttachment(logs []models.Log, f *excelize.File) {
mailContent := &models.Mail{
Sender: config.C.Mail.FromMail,
To: toUsers,
Cc: ccUsers,
Bcc: []string{},
Subject: config.C.App.TargetApp + " Error Logs",
}
mail.SendMail(mailContent, logs, f)
}