-
Notifications
You must be signed in to change notification settings - Fork 5
Home
Chris McKelt edited this page Oct 3, 2017
·
8 revisions
const long fiftyGigInBytes = 50000000000;
const string Storage_drive = @"R:\Sql";
const string DDrive = @"d:\backups\"; //SSD
const string JDrive = @"j:\backups\"; //Bulk room
void Main()
{
try {
Execute();
}
catch (Exception ex)
{
RecordError("database backup finpower_production-backup.linq", ex);
}
}
public void Execute()
{
SlackMessage("perform backup started... " + DateTime.Now.ToShortTimeString());
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
if (!Directory.Exists(DDrive)) Directory.CreateDirectory(DDrive);
try
{
//PerformBackUp();
}
catch (Exception ex)
{
SlackError("ERROR...PerformBackUp " + ex.ToString());
RecordError("PerformBackUp FAILED", ex);
stopwatch.Stop();
return;
}
TimeSpan timeSpan = stopwatch.Elapsed;
// BACKUP with compression - no longer need this zipping bit
// SlackMessage($"zipping started... time so far --> hours: {timeSpan.Hours} minutes:{timeSpan.Minutes} seconds{timeSpan.Seconds}");
// try
// {
// ZipIt();
// }
// catch (Exception ex)
// {
// SlackError("ERROR...ZipIt " + ex.ToString());
// RecordError("PerformBackUp ZipIt", ex);
// stopwatch.Stop();
// return;
// }
// allow 120 secs to complete zip background process
//Thread.Sleep(12000);
SlackMessage($"CopyIt started to {Storage_drive} ... time so far --> hours: {timeSpan.Hours} minutes:{timeSpan.Minutes} seconds{timeSpan.Seconds}");
try
{
CopyIt();
}
catch (Exception ex)
{
SlackError("ERROR... CopyIt " + ex.ToString());
RecordError("PerformBackUp CopyIt", ex);
stopwatch.Stop(); ;
return;
}
finally
{
stopwatch.Stop();
}
SlackMessage($"CopyIt complete... {Storage_drive} ... time so far --> hours: {timeSpan.Hours} minutes:{timeSpan.Minutes} seconds{timeSpan.Seconds}");
CheckDriveSpaceCheck("C:");
CheckDriveSpaceCheck("D:");
CheckDriveSpaceCheck("E:");
CheckDriveSpaceCheck("J:");
MoveFilesToJDrive();
DeleteOldFiles();
}
public void PerformBackUp()
{
// perform backup
var args = new DatabaseMinder.CommandArgs();
args.DatabaseName = "FinPowerConnect_Production";
args.Backup = true;
args.Folder = DDrive;
args.PromptsEnabled = false;
args.ZipBackup = false;
args.CompressionEnabled = true;
DatabaseMinder.Handler.HandleCommand(args);
}
public void ZipIt()
{
// zip
ExecuteCommand($@"cd {DDrive} & 7z a finpowerconnect_production.zip *.bak ");
Thread.Sleep(60000);
string fileTime = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string from = $@"{DDrive}\finpowerconnect_production.zip";
string to = $@"{DDrive}\finpowerconnect_production_{fileTime}.zip";
File.Move(from, to);
}
public void CopyIt()
{
foreach (var file in Directory.GetFiles(DDrive, "*.*"))
{
var toFile = $"{Storage_drive}\\{Path.GetFileName(file)}";
SlackMessage("CopyIt", $"started moving file from {file} to {toFile}");
//ProcessXcopy(file, toFile);
File.Copy(file, $"{Storage_drive}\\{Path.GetFileName(file)}");
SlackMessage("CopyIt", $"done moving file from {file} to {toFile}");
}
}
//https://stackoverflow.com/questions/5519328/executing-batch-file-in-c-sharp
public void ExecuteCommand(string command)
{
var processInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardOutput = true;
processInfo.WorkingDirectory = DDrive;
var process = Process.Start(processInfo);
process.OutputDataReceived += (object sender, DataReceivedEventArgs e) =>
Console.WriteLine("output>>" + e.Data);
process.BeginOutputReadLine();
process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) =>
SlackError(e.Data);
process.BeginErrorReadLine();
process.WaitForExit();
if (process.ExitCode == 1)
{
SlackError($"7zip ExitCode ERROR: {process.ExitCode}");
}
process.Close();
}
private void MoveFilesToJDrive()
{
if (DateTime.Now.DayOfWeek == DayOfWeek.Thursday)
{
SlackMessage("MoveFilesToJDrive",$"Deleting old files from J: every Thursday");
//once per week delete files on J:
foreach (var file in Directory.GetFiles(DDrive, "*.*"))
{
File.Delete(file);
}
}
foreach (var file in Directory.GetFiles(DDrive, "*.*"))
{
var toFile = $"{JDrive}\\{Path.GetFileName(file)}";
SlackMessage("MoveFilesToJDrive started",$"starting move of file from {file} to {toFile}");
File.Move(file, $"{Storage_drive}\\{Path.GetFileName(file)}");
SlackMessage("MoveFilesToJDrive completed",$"done move of file from {file} to {toFile}");
}
}
/// <summary>
/// Method to Perform Xcopy to copy files/folders from Source machine to Target Machine
/// </summary>
/// <param name="SolutionDirectory"></param>
/// <param name="TargetDirectory"></param>
private void ProcessXcopy(string from, string to)
{
// Use ProcessStartInfo class
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
//Give the name as Xcopy
startInfo.FileName = "xcopy";
//make the window Hidden
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
//Send the Source and destination as Arguments to the process
startInfo.Arguments = "\"" + from + "\"" + " " + "\"" + to + "\"" + @" /h /k /y /I /q";
try
{
// Start the process with the info we specified.
// Call WaitForExit and then the using statement will close.
using (Process exeProcess = Process.Start(startInfo))
{
exeProcess.WaitForExit();
}
}
catch (Exception exp)
{
RecordError("ProcessXcopy FAILED",exp);
SlackError("ProcessXcopy FAILED");
throw exp;
}
}
private void DeleteOldFiles(string drive = DDrive)
{
var files = Directory.GetFiles(DDrive, "*.*");
foreach (string file in files)
{
SlackMessage($"DeleteOldFiles", file);
File.Delete(file);
}
}
private void CheckDriveSpaceCheck(string driveLetter = "E")
{
DriveInfo drive = new DriveInfo(driveLetter);
if (fiftyGigInBytes >= drive.AvailableFreeSpace)
{
Message.Clear();
Message.Append($"WARNING: PROD SQL {driveLetter}: has less than 50GB ");
PostToSlack("Production SQL {driveLetter}: running out of room. AUTOMATICALLY DELETED OLD BACKUPS. Free Space " + ConvertBytesToMegabytes(drive.AvailableFreeSpace));
}
}
static double ConvertBytesToMegabytes(long bytes)
{
return (bytes / 1024f) / 1024f;
}
#region Slack poster
public bool IsSlackPostEnabled = true;
public StringBuilder Message = new StringBuilder();
const string MonitorChannel = "https://hooks.slack.com/services/T06EV35NK/B0KK51076/xxxxxxxxxxxxxxxxxxxxxxxx";
private void PostToSlack(string title)
{
if (IsSlackPostEnabled)
{
var msg = new SlackMessage();
string hex = "#009900";
msg.Title(title)
.UsingLeftBarColor(hex.ToColor())
.WithMessageText($"{Message.ToString()}")
.AsUser("itnotifications");
SlackClient client = new SlackClient(MonitorChannel);
client.Send(msg);
}
else
{
Console.WriteLine();
Console.WriteLine("--------------------------");
Console.WriteLine(title);
Console.WriteLine("--------------------------");
Console.WriteLine();
Console.WriteLine(Message.ToString());
Console.WriteLine();
}
}
public void SlackMessage(string msg)
{
Message.Clear();
Message.AppendLine(msg);
PostToSlack("Database backup");
}
public void SlackMessage(string title,string msg)
{
Message.Clear();
Message.AppendLine(msg);
PostToSlack(title);
}
private void SlackError(string title)
{
if (string.IsNullOrEmpty(title)) return;
if (IsSlackPostEnabled)
{
var msg = new SlackMessage();
string hex = "#ff0000";
msg.Title(title)
.UsingLeftBarColor(hex.ToColor())
.WithMessageText($"{Message.ToString()}")
.AsUser("itnotifications");
SlackClient client = new SlackClient(MonitorChannel);
client.Send(msg);
}
else
{
Console.WriteLine();
Console.WriteLine("--------------------------");
Console.WriteLine(title);
Console.WriteLine("--------------------------");
Console.WriteLine();
Console.WriteLine(Message.ToString());
Console.WriteLine();
}
}
private void RecordError(string title, Exception exception)
{
if (IsSlackPostEnabled == false) return;
using (EventLog eventLog = new EventLog("Application"))
{
eventLog.Source = "Application";
eventLog.WriteEntry("Database backup error - " + Environment.NewLine + exception.ToString(), EventLogEntryType.Error);
}
}
#endregion