-
Notifications
You must be signed in to change notification settings - Fork 0
/
native.go
256 lines (202 loc) · 6.36 KB
/
native.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
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
package client
import (
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/spf13/viper"
)
// NativeRestoreParameters contains restore information
type NativeRestoreParameters struct {
BaseRestoreParameters
CustomDataPath string
ServerPath string
}
// DefaultServerInstallationPath path to the native SQL server installation
const DefaultServerInstallationPath = "C:\\Program Files\\Microsoft SQL Server\\MSSQL13.MSSQLSERVER\\MSSQL\\"
// NativeClient is a SQL client runs sqlcmd on a machine
type NativeClient struct{}
// IsEnvironmentSatisfied returns if this client can be run on this machine
func (c *NativeClient) IsEnvironmentSatisfied() bool {
args := []string{"-?"}
_, err := executeSQLCmd(args)
if err != nil {
return false
}
return true
}
// GetStatus returns the status of the latest backup
func (c *NativeClient) GetStatus(params *DatabaseParameters, taskID string) (string, error) {
query := "SELECT TOP 1 lifecycle FROM @s"
if taskID != "" {
query = fmt.Sprintf("SELECT lifecycle FROM @s WHERE task_id = %s", taskID)
}
statement := fmt.Sprintf(`SET NOCOUNT ON
%s
INSERT INTO @s
exec msdb.dbo.rds_task_status @db_name='%s'
%s
SET NOCOUNT OFF`, statusTableDeclaration, params.DatabaseName, query)
args := getSQLCommandArgs(params, statement)
output, err := executeSQLCmd(args)
if err != nil {
return "", err
}
return getSQLOutput(output), nil
}
// GetCompletionPercentage returns the percentage of completion of the latest backup
func (c *NativeClient) GetCompletionPercentage(params *DatabaseParameters) (string, error) {
statement := fmt.Sprintf(`SET NOCOUNT ON
%s
INSERT INTO @s
exec msdb.dbo.rds_task_status @db_name='%s'
SELECT TOP 1 complete FROM @s
SET NOCOUNT OFF`, statusTableDeclaration, params.DatabaseName)
args := getSQLCommandArgs(params, statement)
output, err := executeSQLCmd(args)
if err != nil {
return "", err
}
return getSQLOutput(output), nil
}
// GetTaskMessage returns the message of the latest backup task
func (c *NativeClient) GetTaskMessage(params *DatabaseParameters) (string, error) {
statement := fmt.Sprintf(`SET NOCOUNT ON
%s
INSERT INTO @s
exec msdb.dbo.rds_task_status @db_name='%s'
SELECT TOP 1 task_info FROM @s
SET NOCOUNT OFF`, statusTableDeclaration, params.DatabaseName)
args := getSQLCommandArgs(params, statement)
output, err := executeSQLCmd(args)
if err != nil {
return "", err
}
return getSQLOutput(output), nil
}
// StartBackup creates a new backup
func (c *NativeClient) StartBackup(params *BackupParameters) (string, error) {
statement := fmt.Sprintf(`SET NOCOUNT ON
%s
INSERT INTO @s
exec msdb.dbo.rds_backup_database
@source_db_name='%s',
@s3_arn_to_backup_to='arn:aws:s3:::%s/%s',
@overwrite_S3_backup_file=1;
SELECT TOP 1 task_id FROM @s
SET NOCOUNT OFF`,
createTableDeclaration,
params.DatabaseName,
params.BucketName,
params.Filename)
args := getSQLCommandArgs(¶ms.DatabaseParameters, statement)
output, err := executeSQLCmd(args)
if err != nil {
return "", err
}
lines := strings.Split(output, "\n")
if len(lines) < 4 {
return "", errors.New(output)
}
return strings.TrimSpace(lines[3]), nil
}
// GetLogicalNames returns the logical names of MDF and LDF
func (c *NativeClient) GetLogicalNames(params *DatabaseParameters) (string, string, error) {
dataNameQuery := "SELECT name FROM sys.master_files WHERE database_id = db_id() AND type = 0"
logNameQuery := "SELECT name FROM sys.master_files WHERE database_id = db_id() AND type = 1"
outputData, errData := executeSQLCmd(getSQLCommandArgs(params, dataNameQuery))
if errData != nil {
return "", "", errData
}
dataName := getSQLOutput(outputData)
outputLog, errLog := executeSQLCmd(getSQLCommandArgs(params, logNameQuery))
if errLog != nil {
return "", "", errLog
}
logName := getSQLOutput(outputLog)
return dataName, logName, nil
}
// RestoreNative restores a backup onto a local instance of SQL server
func RestoreNative(params *NativeRestoreParameters) error {
pathToBak := getPathToBak(¶ms.BaseRestoreParameters)
_, errFile := os.Stat(pathToBak)
if errFile != nil {
return errFile
}
serverDirectory := params.ServerPath
serverBackupDirectory := filepath.Join(serverDirectory, "Backup\\")
serverMdfDirectory := filepath.Join(serverDirectory, "DATA\\")
serverLdfDirectory := filepath.Join(serverDirectory, "LOG\\")
pathToBackup := filepath.Join(serverBackupDirectory, params.Filename)
fmt.Println("Starting to restore onto local SQL Server...")
copyFile(pathToBak, pathToBackup)
fmt.Printf("Copied from %s to %s to prepare restoration.\n", pathToBak, pathToBackup)
mdfDirectory := serverMdfDirectory
ldfDirectory := serverLdfDirectory
if params.CustomDataPath != "" {
if _, errCustomPath := os.Stat(params.CustomDataPath); os.IsNotExist(errCustomPath) {
return errCustomPath
}
mdfDirectory = params.CustomDataPath
ldfDirectory = params.CustomDataPath
}
mdfPath := filepath.Join(mdfDirectory, fmt.Sprintf("%s.mdf", params.DatabaseName))
ldfPath := filepath.Join(ldfDirectory, fmt.Sprintf("%s.ldf", params.DatabaseName))
fmt.Println("Restoring...")
restoreArgs := []string{
"-Q",
fmt.Sprintf("RESTORE DATABASE %s FROM DISK=N'%s' WITH FILE=1, NOUNLOAD, REPLACE, STATS=5, MOVE '%s' TO '%s', MOVE '%s' TO '%s'", params.DatabaseName, pathToBackup, params.DataName, mdfPath, params.LogName, ldfPath),
}
_, err := executeSQLCmd(restoreArgs)
if err != nil {
return err
}
fmt.Printf("Restore has been completed (as database '%s').\n", params.DatabaseName)
errRemove := os.Remove(pathToBackup)
if errRemove != nil {
return errRemove
}
fmt.Printf("Removed file %s. Clean up done.\n", pathToBackup)
return nil
}
func executeSQLCmd(args []string) (string, error) {
if viper.GetBool("verbose") {
fmt.Println("Command executed:", "sqlcmd", args)
}
byteOutput, err := exec.Command("sqlcmd", args...).Output()
return string(byteOutput), err
}
func getSQLCommandArgs(params *DatabaseParameters, statement string) []string {
return []string{
"-S",
params.Server,
"-d",
params.DatabaseName,
"-U",
params.Username,
"-P",
params.Password,
"-Q",
statement,
}
}
func copyFile(src, dst string) error {
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
out, err := os.Create(dst)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, in)
if err != nil {
return err
}
return out.Close()
}