-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
263 lines (225 loc) · 11.9 KB
/
Program.cs
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
using Azure.Storage.Blobs;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace PostgreSqlBackuptoAzureTool
{
class Program
{
public static IConfigurationRoot Configuration;
static void Main(string[] args)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.SetBasePath(Path.Combine(AppContext.BaseDirectory))
.AddJsonFile("appSettings.json", optional: true);
Configuration = builder.Build();
try
{
GetDataForBackup();
}
catch (Exception ex)
{
ErrorLog(Configuration.GetSection("BackupSettings:BackupPath").Value + "\\ErrorLog" + DateTime.Now.ToString("yyyy-dd-M") + ".txt", "ExceptionMain- " + ex.Message);
using (var context = new AppDBContext(Configuration))
{
ExceptionLog log = new ExceptionLog();
log.DMSServiceInfoId = 0;
if (ex.InnerException == null)
log.InnerException = string.Empty;
else
log.InnerException = ex.InnerException.Message;
if (ex.StackTrace == null)
log.StackTrace = string.Empty;
else
log.StackTrace = ex.StackTrace.ToString();
log.ExceptionMessage = "Error Executing while Backup- " + ex.Message.ToString();
context.ExceptionLogs.Add(log);
context.SaveChanges();
}
throw ex;
}
}
public static void ErrorLog(string sPathName, string sErrMsg)
{
StreamWriter sw = new StreamWriter(sPathName, true);
sw.WriteLine(sErrMsg + "\n");
sw.Flush();
sw.Close();
}
public static void GetDataForBackup()
{
string backuppath = Configuration.GetSection("BackupSettings:BackupPath").Value;
using (var context = new AppDBContext(Configuration))
{
var watch = new System.Diagnostics.Stopwatch();
watch.Start();
List<DBBackupInfo> dbBackupList = new List<DBBackupInfo>();
dbBackupList = context.DBBackupInfo.AsNoTracking()
.Where(x => x.WantBackup)
.OrderBy(x => x.Id).ToList();
watch.Stop();
ErrorLog(backuppath + "\\ErrorLog" + DateTime.Now.ToString("yyyy-dd-M") + ".txt", "Count is- " + dbBackupList.Count().ToString());
ErrorLog(backuppath + "\\ErrorLog" + DateTime.Now.ToString("yyyy-dd-M") + ".txt", "Time taken for fetchign data from DB is- " + watch.ElapsedMilliseconds.ToString() + "ms");
foreach (var db in dbBackupList)
{
try
{
string dbname = db.DatabaseName.ToLower();
string server = db.DatabaseServer.ToLower();
string backupFile = backuppath + dbname + Configuration.GetSection("BackupSettings:Extension").Value;
string destcontaineName= Configuration.GetSection("GenericStorageSettings:ContainerName").Value.ToLower();
ErrorLog(backuppath + "\\ErrorLog" + DateTime.Now.ToString("yyyy-dd-M") + ".txt", dbname + server);
if (!watch.IsRunning)
watch.Restart();
TakeBackupofPostgreSql(db, backupFile);
watch.Stop();
ErrorLog(backuppath + "\\ErrorLog" + DateTime.Now.ToString("yyyy-dd-M") + ".txt", "Time taken for Backup of DB is- " + watch.ElapsedMilliseconds.ToString() + "ms and DB is- " + db.DatabaseName);
string destinationConnectionString = Configuration.GetSection("GenericStorageSettings:ConnectionString").Value;
BlobServiceClient destBlobClient = new BlobServiceClient(destinationConnectionString);
var destContainers = destBlobClient.GetBlobContainers();
if (destContainers.Where(b => b.Name == destcontaineName).Count() == 0)
{
destBlobClient.CreateBlobContainer(destcontaineName);
}
BlobContainerClient destContainerClient = destBlobClient.GetBlobContainerClient(destcontaineName);
if (!watch.IsRunning)
watch.Restart();
DeleteOldFiles(destContainerClient,dbname);
watch.Stop();
ErrorLog(backuppath + "\\ErrorLog" + DateTime.Now.ToString("yyyy-dd-M") + ".txt", "Time taken for Deleting files over Azure is- " + watch.ElapsedMilliseconds.ToString() + "ms");
if (!watch.IsRunning)
watch.Restart();
ExecuteCopyOverAzure(destContainerClient, server, dbname, backupFile.ToLower(), db, context);
watch.Stop();
ErrorLog(backuppath + "\\ErrorLog" + DateTime.Now.ToString("yyyy-dd-M") + ".txt", "Time taken for uploading the backup pver azure is- " + watch.ElapsedMilliseconds.ToString() + "ms");
}
catch (Exception ex)
{
ErrorLog(Configuration.GetSection("BackupSettings:BackupPath").Value + "\\ErrorLog" + DateTime.Now.ToString("yyyy-dd-M") + ".txt", "Exception1- " + ex.Message);
//ErrorLog(Configuration.GetSection("BackupSettings:BackupPath").Value + "\\ErrorLog" + DateTime.Now.ToString("yyyy-dd-M") + ".txt", "Exception1 Deatila- " + db.Id.ToString() + "-" + ex.InnerException.ToString() + "-" + ex.StackTrace.ToString());
ExceptionLog log = new ExceptionLog();
log.DMSServiceInfoId = db.Id;
if (ex.InnerException == null)
log.InnerException = string.Empty;
else
log.InnerException = ex.InnerException.Message;
if (ex.StackTrace == null)
log.StackTrace = string.Empty;
else
log.StackTrace = ex.StackTrace.ToString();
log.ExceptionMessage = "Error Executing while Backup- " + ex.Message.ToString();
context.ExceptionLogs.Add(log);
context.SaveChanges();
throw ex;
}
}
}
}
public static void TakeBackupofPostgreSql(DBBackupInfo db, string backupFile)
{
string server = db.DatabaseServer;
string port = db.DatabasePort;
string user = db.DatabaseUserName;
string password = db.DatabasePassword;
string dbname = db.DatabaseName;
string backupCommandDir = Path.Combine(AppContext.BaseDirectory) + "lib\\";
string command = "-h " + server + " -p " + port + " -U " + user + " -F c -b -v -f " + backupFile + " " + dbname;
using (Process p = new Process())
{
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = backupCommandDir + "pg_dump.exe";
p.StartInfo.EnvironmentVariables.Add("PGPASSWORD", password);
p.StartInfo.Arguments = command;
ErrorLog(Configuration.GetSection("BackupSettings:BackupPath").Value + "\\ErrorLog" + DateTime.Now.ToString("yyyy-dd-M") + ".txt", "Inside Process- Arguments is- " + command);
p.Start();
p.WaitForExit();
p.Close();
}
ErrorLog(Configuration.GetSection("BackupSettings:BackupPath").Value + "\\ErrorLog" + DateTime.Now.ToString("yyyy-dd-M") + ".txt", "Inside Process- Arguments is- " + command);
}
public static void DeleteOldFiles(BlobContainerClient destContainerClient,string dbName)
{
var blobs = destContainerClient.GetBlobs().ToList();
bool dailyBackup = Configuration.GetSection("ScheduleSettings:Daily").Value.ToLower() == "true" ? true : false;
bool weeklyBackup = Configuration.GetSection("ScheduleSettings:Weekly").Value.ToLower() == "true" ? true : false;
foreach (var blob in blobs)
{
if (dailyBackup && blob.Name.Contains(dbName+"-Daily"))
{
destContainerClient.DeleteBlob(blob.Name);
}
if (weeklyBackup && blob.Name.Contains(dbName+"-Weekly"))
{
destContainerClient.DeleteBlob(blob.Name);
}
}
}
public static void ExecuteCopyOverAzure(BlobContainerClient destContainerClient, string server, string dbname, string backupFile, DBBackupInfo db, AppDBContext context)
{
bool dailyBackup = Configuration.GetSection("ScheduleSettings:Daily").Value.ToLower() == "true" ? true : false;
bool weeklyBackup = Configuration.GetSection("ScheduleSettings:Weekly").Value.ToLower() == "true" ? true : false;
int dailyCounter = 0;
int weeklyCounter = 0;
string fileName = dbname + Configuration.GetSection("BackupSettings:Extension").Value;
if (dailyBackup)
{
BlobClient destBlob = destContainerClient.GetBlobClient(server + "/"+dbname+"-Daily/" + fileName);
try
{
// Start the copy operation.
destBlob.Upload(backupFile);
dailyCounter = dailyCounter + 1;
}
catch (Exception ex)
{
throw ex;
}
}
if (weeklyBackup)
{
BlobClient destBlob = destContainerClient.GetBlobClient(server + "/" + dbname +"-Weekly/" + fileName);
// Start the copy operation.
destBlob.Upload(backupFile);
weeklyCounter = weeklyCounter + 1;
}
if (dailyBackup)
{
PostgreBackupLogs log = new PostgreBackupLogs();
log.Category = "Daily";
log.DatabaseName = db.DatabaseName;
log.DatabasePassword = db.DatabasePassword;
log.DatabaseUserName = db.DatabaseUserName;
log.DatabaseServer = db.DatabaseServer;
log.NoOfBackupFiles = dailyCounter;
log.DBBackupInfoId = db.Id;
log.DatabasePort = db.DatabasePort;
log.CreatedOn = DateTime.Now;
context.PostgreBackupLogs.Add(log);
}
if (weeklyBackup)
{
PostgreBackupLogs log = new PostgreBackupLogs();
log.Category = "Weekly";
log.DatabaseName = db.DatabaseName;
log.DatabasePassword = db.DatabasePassword;
log.DatabaseUserName = db.DatabaseUserName;
log.DatabaseServer = db.DatabaseServer;
log.NoOfBackupFiles = dailyCounter;
log.DBBackupInfoId = db.Id;
log.DatabasePort = db.DatabasePort;
log.CreatedOn = DateTime.Now;
context.PostgreBackupLogs.Add(log);
}
context.SaveChanges();
}
}
}