-
Notifications
You must be signed in to change notification settings - Fork 0
/
backup.go
192 lines (158 loc) · 4.82 KB
/
backup.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
package main
import (
"bytes"
"context"
"fmt"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"time"
"github.com/ansel1/merry/v2"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/getsentry/sentry-go"
config "github.com/granitebps/puasa-sunnah-api/configs"
"github.com/granitebps/puasa-sunnah-api/pkg/constants"
"github.com/mailgun/mailgun-go/v4"
"github.com/spf13/viper"
)
func main() {
log.Println("Starting backup process...")
config.SetupConfig(".env")
database := viper.GetString(constants.DB_NAME)
dateTime := time.Now().Format("2006-01-02_15-04-05")
sqlFileName := fmt.Sprintf("%s_%s.sql", dateTime, database)
err := dumpSqlFile(sqlFileName)
if err != nil {
err = merry.Wrap(err)
sentry.CaptureException(err)
os.Exit(1)
}
err = sendSqlToS3(sqlFileName)
if err != nil {
err = merry.Wrap(err)
sentry.CaptureException(err)
os.Exit(1)
}
err = sendEmailNotification(sqlFileName)
if err != nil {
err = merry.Wrap(err)
sentry.CaptureException(err)
os.Exit(1)
}
log.Println("Backup process finished.")
}
func dumpSqlFile(fileName string) (err error) {
host := viper.GetString(constants.DB_HOST)
username := viper.GetString(constants.DB_USER)
password := viper.GetString(constants.DB_PASS)
database := viper.GetString(constants.DB_NAME)
// Check if mysqldump is available in PATH
_, err = exec.LookPath("mysqldump")
if err != nil {
log.Println("Error: mysqldump is not available in PATH.")
err = merry.Wrap(err)
return
}
// Set the command and arguments
cmd := exec.Command("mysqldump", "-h", host, "-u", username, "-p"+password, database) // #nosec G204
// cmd := exec.Command("mysqldump", "--socket", "/tmp/mysql_3306.sock", "-h", host, "-u", username, "-p"+password, database) // #nosec G204
// Create an output file for the dump
outputFile, err := os.Create(filepath.Clean(fileName))
if err != nil {
log.Println("Failed to create dump file")
err = merry.Wrap(err)
return
}
defer outputFile.Close()
// Redirect command output to the file
cmd.Stdout = outputFile
// Run the command
err = cmd.Run()
if err != nil {
log.Printf("Failed to execute mysqldump: %s\n", err)
err = merry.Wrap(err)
return
}
log.Printf("Database dumped successfully to dump %s\n", fileName)
return nil
}
func sendSqlToS3(fileName string) (err error) {
region := viper.GetString(constants.AWS_DEFAULT_REGION)
bucket := viper.GetString(constants.AWS_BUCKET)
accessKey := viper.GetString(constants.AWS_ACCESS_KEY_ID)
secretKey := viper.GetString(constants.AWS_SECRET_ACCESS_KEY)
sess, err := session.NewSession(&aws.Config{
Region: aws.String(region),
Credentials: credentials.NewStaticCredentials(accessKey, secretKey, ""),
})
if err != nil {
err = merry.Wrap(err)
log.Println("Error creating session:", err)
return
}
svc := s3.New(sess)
file, err := os.Open(filepath.Clean(fileName))
if err != nil {
err = merry.Wrap(err)
log.Println("Error opening file:", err)
return
}
defer file.Close()
// Read the contents of the file into a buffer
var buf bytes.Buffer
_, err = io.Copy(&buf, file)
if err != nil {
err = merry.Wrap(err)
log.Println("Error reading file:", err)
return
}
// This uploads the contents of the buffer to S3
_, err = svc.PutObject(&s3.PutObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(fileName),
Body: bytes.NewReader(buf.Bytes()),
})
if err != nil {
fmt.Println("Error uploading file:", err)
return
}
// Delete the file after it's uploaded
err = os.Remove(fileName)
if err != nil {
err = merry.Wrap(err)
log.Println("Error deleting file:", err)
return
}
log.Printf("File uploaded to AWS S3 bucket: %s\n", bucket)
return
}
func sendEmailNotification(fileName string) (err error) {
secret := viper.GetString(constants.MAILGUN_SECRET)
domain := viper.GetString(constants.MAILGUN_DOMAIN)
appName := viper.GetString(constants.APP_NAME)
appEnv := viper.GetString(constants.APP_ENV)
// Create an instance of the Mailgun Client
mg := mailgun.NewMailgun(domain, secret)
sender := "info@granitebps.com"
subject := fmt.Sprintf("Successful new backup of %s (%s)", appName, appEnv)
body := fmt.Sprintf("Hello! Great news, a new backup of %s (%s) was successfully created with filename %s!", appName, appEnv, fileName)
recipient := "granitebagas28@gmail.com"
// The message object allows you to add attachments and Bcc recipients
message := mg.NewMessage(sender, subject, body, recipient)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
// Send the message with a 10 second timeout
_, _, err = mg.Send(ctx, message)
if err != nil {
err = merry.Wrap(err)
log.Println("Error sending email:", err)
return
}
log.Println("Email notification sent successfully")
return
}