/
restore.go
174 lines (150 loc) · 6.55 KB
/
restore.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
/*
Copyright The Stash Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package pkg
import (
"path/filepath"
"strings"
api_v1beta1 "stash.appscode.dev/apimachinery/apis/stash/v1beta1"
"stash.appscode.dev/apimachinery/pkg/restic"
"github.com/appscode/go/flags"
"github.com/spf13/cobra"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
appcatalog_cs "kmodules.xyz/custom-resources/client/clientset/versioned"
v1 "kmodules.xyz/offshoot-api/api/v1"
)
func NewCmdRestore() *cobra.Command {
var (
masterURL string
kubeconfigPath string
opt = mysqlOptions{
setupOptions: restic.SetupOptions{
ScratchDir: restic.DefaultScratchDir,
EnableCache: false,
},
waitTimeout: 300,
dumpOptions: restic.DumpOptions{
Host: restic.DefaultHost,
FileName: MySqlDumpFile,
},
}
)
cmd := &cobra.Command{
Use: "restore-mysql",
Short: "Restores MySQL DB Backup",
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
flags.EnsureRequiredFlags(cmd, "appbinding", "provider", "secret-dir")
// prepare client
config, err := clientcmd.BuildConfigFromFlags(masterURL, kubeconfigPath)
if err != nil {
return err
}
opt.kubeClient, err = kubernetes.NewForConfig(config)
if err != nil {
return err
}
opt.catalogClient, err = appcatalog_cs.NewForConfig(config)
if err != nil {
return err
}
var restoreOutput *restic.RestoreOutput
restoreOutput, err = opt.restoreMySQL()
if err != nil {
restoreOutput = &restic.RestoreOutput{
HostRestoreStats: []api_v1beta1.HostRestoreStats{
{
Hostname: opt.dumpOptions.Host,
Phase: api_v1beta1.HostRestoreFailed,
Error: err.Error(),
},
},
}
}
// If output directory specified, then write the output in "output.json" file in the specified directory
if opt.outputDir != "" {
return restoreOutput.WriteOutput(filepath.Join(opt.outputDir, restic.DefaultOutputFileName))
}
return nil
},
}
cmd.Flags().StringVar(&opt.myArgs, "mysql-args", opt.myArgs, "Additional arguments")
cmd.Flags().Int32Var(&opt.waitTimeout, "wait-timeout", opt.waitTimeout, "Time limit to wait for the database to be ready")
cmd.Flags().StringVar(&masterURL, "master", masterURL, "The address of the Kubernetes API server (overrides any value in kubeconfig)")
cmd.Flags().StringVar(&kubeconfigPath, "kubeconfig", kubeconfigPath, "Path to kubeconfig file with authorization information (the master location is set by the master flag).")
cmd.Flags().StringVar(&opt.namespace, "namespace", "default", "Namespace of Backup/Restore Session")
cmd.Flags().StringVar(&opt.appBindingName, "appbinding", opt.appBindingName, "Name of the app binding")
cmd.Flags().StringVar(&opt.setupOptions.Provider, "provider", opt.setupOptions.Provider, "Backend provider (i.e. gcs, s3, azure etc)")
cmd.Flags().StringVar(&opt.setupOptions.Bucket, "bucket", opt.setupOptions.Bucket, "Name of the cloud bucket/container (keep empty for local backend)")
cmd.Flags().StringVar(&opt.setupOptions.Endpoint, "endpoint", opt.setupOptions.Endpoint, "Endpoint for s3/s3 compatible backend or REST backend URL")
cmd.Flags().StringVar(&opt.setupOptions.Region, "region", opt.setupOptions.Region, "Region for s3/s3 compatible backend")
cmd.Flags().StringVar(&opt.setupOptions.Path, "path", opt.setupOptions.Path, "Directory inside the bucket where backup will be stored")
cmd.Flags().StringVar(&opt.setupOptions.SecretDir, "secret-dir", opt.setupOptions.SecretDir, "Directory where storage secret has been mounted")
cmd.Flags().StringVar(&opt.setupOptions.ScratchDir, "scratch-dir", opt.setupOptions.ScratchDir, "Temporary directory")
cmd.Flags().BoolVar(&opt.setupOptions.EnableCache, "enable-cache", opt.setupOptions.EnableCache, "Specify whether to enable caching for restic")
cmd.Flags().Int64Var(&opt.setupOptions.MaxConnections, "max-connections", opt.setupOptions.MaxConnections, "Specify maximum concurrent connections for GCS, Azure and B2 backend")
cmd.Flags().StringVar(&opt.dumpOptions.Host, "hostname", opt.dumpOptions.Host, "Name of the host machine")
cmd.Flags().StringVar(&opt.dumpOptions.SourceHost, "source-hostname", opt.dumpOptions.SourceHost, "Name of the host from where data will be restored")
// TODO: sliceVar
cmd.Flags().StringVar(&opt.dumpOptions.Snapshot, "snapshot", opt.dumpOptions.Snapshot, "Snapshot to dump")
cmd.Flags().StringVar(&opt.outputDir, "output-dir", opt.outputDir, "Directory where output.json file will be written (keep empty if you don't need to write output in file)")
return cmd
}
func (opt *mysqlOptions) restoreMySQL() (*restic.RestoreOutput, error) {
// apply nice, ionice settings from env
var err error
opt.setupOptions.Nice, err = v1.NiceSettingsFromEnv()
if err != nil {
return nil, err
}
opt.setupOptions.IONice, err = v1.IONiceSettingsFromEnv()
if err != nil {
return nil, err
}
// get app binding
appBinding, err := opt.catalogClient.AppcatalogV1alpha1().AppBindings(opt.namespace).Get(opt.appBindingName, metav1.GetOptions{})
if err != nil {
return nil, err
}
// get secret
appBindingSecret, err := opt.kubeClient.CoreV1().Secrets(opt.namespace).Get(appBinding.Spec.Secret.Name, metav1.GetOptions{})
if err != nil {
return nil, err
}
// init restic wrapper
resticWrapper, err := restic.NewResticWrapper(opt.setupOptions)
if err != nil {
return nil, err
}
// set env for mysql
resticWrapper.SetEnv(EnvMySqlPassword, string(appBindingSecret.Data[MySqlPassword]))
// setup pipe command
opt.dumpOptions.StdoutPipeCommand = restic.Command{
Name: MySqlRestoreCMD,
Args: []interface{}{
"-u", string(appBindingSecret.Data[MySqlUser]),
"-h", appBinding.Spec.ClientConfig.Service.Name,
},
}
for _, arg := range strings.Fields(opt.myArgs) {
opt.dumpOptions.StdoutPipeCommand.Args = append(opt.dumpOptions.StdoutPipeCommand.Args, arg)
}
// wait for DB ready
err = waitForDBReady(appBinding, appBindingSecret, opt.waitTimeout)
if err != nil {
return nil, err
}
// Run dump
return resticWrapper.Dump(opt.dumpOptions)
}