本章我们来实现编写一个用于 etcd 还原的 operator。
前面我们已经实现了 etcd 备份的 Operator 开发,有了备份必然还需要还原,要实现还原的功能也很简单,直接指定备份好的元数据,然后使用snapshot restore
命令即可还原了。
根据前面我们设计的 EtcdBackup
这个 CRD 资源,我们可以设计一个用于还原的 EtcdRestore
资源对象:
apiVersion: etcd.ydzs.io/v1alpha1
kind: EtcdRestore
metadata:
name: etcdrestore-sample
spec:
etcdCluster: # EtcdCluster 资源对象引用
name: etcd-demo
backupStorageType: s3 # 指定备份类型
s3:
path: "foo-bucket/snapshot.db" # 数据备份的目录
secret: "secret" # 包含 accessKeyID 与 secretAccessKey
设计好了 CR 资源过后,接下来我们只需要去创建这个 API 资源,然后实现对应的控制器就可以了。
同样直接在项目目录下面执行创建 API 的命令:
$ kubebuilder create api --group etcd --version v1alpha1 --kind EtcdRestore
Create Resource [y/n]
y
Create Controller [y/n]
y
Writing scaffold for you to edit...
api/v1alpha1/etcdrestore_types.go
controllers/etcdrestore_controller.go
Running make:
$ make
/Users/ych/devs/projects/go/bin/controller-gen object:headerFile="hack/boilerplate.go.txt" paths="./..."
go fmt ./...
go vet ./...
go build -o bin/manager main.go
创建完成后,在项目中会新增 EtcdBackup 相关的 API 和对应的控制器,我们可以用上面设计的 CR 资源覆盖 samples 目录中的 EtcdBackup 对象。
然后可以根据上面的设计重新修改 etcdrestore_types.go 文件中的资源结构体:
// api/v1alpha1/etcdrestore_types.go
package v1alpha1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
type EtcdRestorePhase string
var (
EtcdRestorePhasePending EtcdRestorePhase = "Pending"
EtcdRestorePhaseFailed EtcdRestorePhase = "Failed"
EtcdRestorePhaseCompleted EtcdRestorePhase = "Completed"
)
// EtcdRestoreSpec defines the desired state of EtcdRestore
type EtcdRestoreSpec struct {
// INSERT ADDITIONAL SPEC FIELDS - desired state of cluster
// Important: Run "make" to regenerate code after modifying this file
EtcdCluster EtcdClusterRef `json:"etcdCluster"`
BackupStorageType BackupStorageType `json:"backupStorageType"`
// restore data source
RestoreSource `json:",inline"`
}
type EtcdClusterRef struct {
// Name is the EtcdCluster resource name.
Name string `json:"name"`
}
type RestoreSource struct {
S3 *S3BackupSource `json:"s3,omitempty"`
OSS *OSSBackupSource `json:"oss,omitempty"`
}
// EtcdRestoreStatus defines the observed state of EtcdRestore
type EtcdRestoreStatus struct {
Phase EtcdRestorePhase `json:"phase,omitempty"`
// Reason indicates the reason for any restore related failures.
Reason string `json:"reason,omitempty"`
}
// +kubebuilder:object:root=true
// +kubebuilder:subresource:status
// EtcdRestore is the Schema for the etcdrestores API
type EtcdRestore struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec EtcdRestoreSpec `json:"spec,omitempty"`
Status EtcdRestoreStatus `json:"status,omitempty"`
}
// +kubebuilder:object:root=true
// EtcdRestoreList contains a list of EtcdRestore
type EtcdRestoreList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []EtcdRestore `json:"items"`
}
func init() {
SchemeBuilder.Register(&EtcdRestore{}, &EtcdRestoreList{})
}
修改完成后需要执行 make
命令,