-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPG14_Backup.Rmd
199 lines (149 loc) · 7.42 KB
/
PG14_Backup.Rmd
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
---
title: "PG14_back_up"
author: "Farshad Ebrahimi"
date: "`r lubridate::now()`"
output: html_document
params:
database: "mars14_datav2"
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
#Dplyr stuff
library(magrittr)
library(tidyverse)
library(lubridate)
#Database Stuff
library(odbc)
library(DBI)
#Other stuff
library(openssl)
library(knitr)
options(stringsAsFactors=FALSE)
```
```{r Section 1 - Back up , include = FALSE}
## Back up the database
#which database to backup? what format?
format_archive <- "c"
format <- paste("--format=",format_archive, sep = "")
database_archive <-"mars_data"
db <- paste("--dbname=",shQuote(database_archive), sep ="")
#specify other details: the pathway to find pg_dump, where to save archive, naming format, database server specs, and username credentials
datestring <- Sys.time() %>% format("%Y%m%dT%H%M")
extension <- "pgdump"
filename <- paste0(datestring, "_", "mars_data", ".", extension)
filepath <- paste0("\\\\pwdoows\\oows\\Watershed Sciences\\GSI Monitoring\\07 Databases and Tracking Spreadsheets\\18 MARS Database Back Up Files\\PG 14\\", filename)
filepath <- shQuote(filepath)
pg_dump <- "C:\\Program Files\\pgAdmin 4\\v6\\runtime\\pg_dump.exe"
pg_dump <- shQuote(pg_dump)
host <- "PWDMARSDBS1"
host <- shQuote(host)
port <- "5434"
port <- shQuote(port)
username <- "mars_admin"
username <- shQuote(username)
role <- "mars_admin"
role <- shQuote(role)
#Assemble the entire pg_dump string
pgdumpstring <- paste(pg_dump,
"--file",filepath,
"--host",host,
"--port", port,
"--username",username,
"--no-password",
"--role",role,
format,
db)
# run the command line using system function
results_dump <- system(pgdumpstring, intern = TRUE, wait = FALSE)
```
The `r params$database` database was `r ifelse(length(results_dump) == 0, "SUCCESSFULLY", "NOT")` backed up.`r if(length(results_dump) == 0){ paste("The file is located at", gsub("\\\\", "/", filepath)) }`
```{r Section 2 - Create Test DB, include = FALSE}
## Create a database to host the test DB
#create db
#testdbname <- paste(database_archive,"_","archivetest_",datestring, sep = "") longnames don't get recognize by pg_restore
con <- dbConnect(odbc::odbc(), dsn = params$database, uid = Sys.getenv("shiny_uid"), pwd = Sys.getenv("shiny_pwd"))
error_db <- NULL
tryCatch({
testdatabase <- paste("db",Sys.time() %>% format("%Y%m%d"), sep = "_")
query_str <- "CREATE DATABASE %s WITH TEMPLATE = template0 OWNER = mars_admin"
sql_query <- paste(sprintf(query_str,testdatabase),collapse="")
results_createdb <- dbSendQuery(con, sql_query)
},error=function(e){
error_db <<- toString(conditionMessage(e))
}
)
dbDisconnect(con)
```
```{r Section 3 - Restoring the backup, include = FALSE}
## Restore the archive
pg_restore <- "C:\\Program Files\\pgAdmin 4\\v6\\runtime\\pg_restore.exe"
pg_restore <- shQuote(pg_restore)
#Assemble the entire pg_restore string
pgrestorestring <- paste(pg_restore,
"--host",host,
"--port", port,
"--username",username,
"--no-password",
"--role",role,
"--jobs=5",
paste("--dbname=",shQuote(testdatabase), sep=""),
filepath)
results_restore <- system(pgrestorestring, intern = TRUE, wait = FALSE)
```
The scratch database was `r ifelse(is.null(error_db), "SUCCESSFULLY", "NOT")` created on the MARS postgres server. `r if(is.null(error_db)){ paste("The database is named", testdatabase) }`
The scratch database was `r ifelse(length(results_restore) == 0, "SUCCESSFULLY", "NOT")` populated by the database archive located at `r gsub("\\\\", "/", filepath)`
```{r Section 4 - Prune old backups, include = FALSE}
## Pruning old back ups
#get a list of backup files from the backup directory
backups <- list.files("\\\\pwdoows\\oows\\Watershed Sciences\\GSI Monitoring\\07 Databases and Tracking Spreadsheets\\18 MARS Database Back Up Files\\PG 14")
backup_pathway <- paste("\\\\pwdoows\\oows\\Watershed Sciences\\GSI Monitoring\\07 Databases and Tracking Spreadsheets\\18 MARS Database Back Up Files\\PG 14", backups, sep = "\\")
#extract the backup date from the backup name and reformat it as Date
backup_datestrings <- str_trunc(backups,8, "right", ellipsis = "")
Dates <- as.Date(backup_datestrings, format="%Y%m%d")
#add the weekdays
backup_dates <-as.data.frame(Dates)
backup_dates$W_Days <- weekdays(backup_dates$Dates)
backup_dates$M_Days<- day(backup_dates$Dates)
backup_dates$Days_Ago <- as.Date(Sys.time() %>% format("%Y-%m-%d"))-backup_dates$Dates
backup_dates$M_number <- backup_dates$Dates %>%
format("%Y-%m")
#Count how many back up exist in each month-this is to prevent deleting the only back up existing for a month
backup_count <- backup_dates %>%
group_by(M_number) %>%
summarise(M_count = n())
#join the count to the back up dataframe
backup_dates <- backup_dates %>%
inner_join(backup_count, by="M_number")
#get index of those rows that are older than 7 days, and are not day 28 or Friday
delete_lastmonth <- which(backup_dates$Days_Ago > 6 & backup_dates$Days_Ago < 30 & backup_dates$W_Days !="Friday" & backup_dates$M_Days !=28)
#note the backup_dates$count !=1 condition (making sure we have at least one back up per month)
delete_older <- which(backup_dates$Days_Ago > 29 & backup_dates$M_Days !=28 & backup_dates$M_count !=1)
#prune the delete index
removed_files <- ifelse(length(c(delete_lastmonth,delete_older)) > 0,
paste(backups[c(delete_lastmonth,delete_older)], collapse = ", "), NA)
results_prune <- file.remove(backup_pathway[c(delete_lastmonth,delete_older)])
```
```{r Section 5 - Log Table, include = FALSE}
# DB
con <- dbConnect(odbc::odbc(), dsn = params$database, uid = Sys.getenv("shiny_uid"), pwd = Sys.getenv("shiny_pwd"))
time_stamp <- Sys.time()
success <- c(ifelse(length(results_dump) == 0,TRUE,FALSE),
ifelse(length(results_restore) == 0 & is.null(error_db),TRUE,FALSE),
ifelse(length(results_prune) != 0, TRUE,FALSE))
error <- c(ifelse(length(results_dump) == 0, NA, results_dump),
ifelse(length(results_restore) == 0 & is.null(error_db), NA, paste(results_restore, error_db)),
ifelse(length(results_prune) != 0, NA,"No back up file was deleted!"))
pruned_files <- c(NA, NA, removed_files)
record_log <- data.frame(operation = c("backup","restore","prune"),
success = success,
time = c(time_stamp,time_stamp,time_stamp),
error = error,
backup_path = c(filepath,filepath,filepath),
pruned_files)
dbWriteTable(con, SQL("admin.tbl_backup_logs"), record_log, append= TRUE, row.names = FALSE)
dbDisconnect(con)
```
The back/restore/prune activities are summarised below and written to "admin.tbl_backup_logs":
```{r Section 6 - Log Table peek,echo=FALSE, results='asis'}
kable(record_log, caption = "Log Table")
```