-
Notifications
You must be signed in to change notification settings - Fork 3
/
cephfs-provisioner.go
305 lines (274 loc) · 8.75 KB
/
cephfs-provisioner.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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
package main
import (
"encoding/json"
"errors"
"flag"
"fmt"
"os/exec"
"strings"
"time"
"github.com/golang/glog"
"github.com/kubernetes-incubator/nfs-provisioner/controller"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/pkg/api/v1"
storage "k8s.io/client-go/pkg/apis/storage/v1beta1"
"k8s.io/client-go/pkg/types"
"k8s.io/client-go/pkg/util/uuid"
"k8s.io/client-go/pkg/util/wait"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)
const (
resyncPeriod = 15 * time.Second
provisionerName = "ceph.com/cephfs"
exponentialBackOffOnError = false
failedRetryThreshold = 5
provisionCmd = "/usr/local/bin/cephfs_provisioner"
provisionerIdAnn = "cephFSProvisionerIdentity"
cephShareAnn = "cephShare"
)
type provisionOutput struct {
Path string `json:"path"`
User string `json:"user"`
Secret string `json:"auth"`
}
type cephFSProvisioner struct {
// Kubernetes Client. Use to retrieve Ceph admin secret
client kubernetes.Interface
// Identity of this cephFSProvisioner, generated. Used to identify "this"
// provisioner's PVs.
identity types.UID
}
func NewCephFSProvisioner(client kubernetes.Interface) controller.Provisioner {
return &cephFSProvisioner{
client: client,
identity: uuid.NewUUID(),
}
}
var _ controller.Provisioner = &cephFSProvisioner{}
// Provision creates a storage asset and returns a PV object representing it.
func (p *cephFSProvisioner) Provision(options controller.VolumeOptions) (*v1.PersistentVolume, error) {
if options.PVC.Spec.Selector != nil {
return nil, fmt.Errorf("claim Selector is not supported")
}
cluster, adminId, adminSecret, mon, err := p.parseParameters(options.Parameters)
if err != nil {
return nil, err
}
// create random share name
share := fmt.Sprintf("kubernetes-dynamic-pvc-%s", uuid.NewUUID())
// create random user id
user := fmt.Sprintf("kubernetes-dynamic-user-%s", uuid.NewUUID())
// provision share
// create cmd
cmd := exec.Command(provisionCmd, "-n", share, "-u", user)
// set env
cmd.Env = []string{
"CEPH_CLUSTER_NAME=" + cluster,
"CEPH_MON=" + strings.Join(mon[:], ","),
"CEPH_AUTH_ID=" + adminId,
"CEPH_AUTH_KEY=" + adminSecret}
output, cmdErr := cmd.CombinedOutput()
if cmdErr != nil {
glog.Errorf("failed to provision share %q for %q, err: %v, output: %v", share, user, cmdErr, string(output))
return nil, cmdErr
}
// validate output
res := &provisionOutput{}
json.Unmarshal([]byte(output), &res)
if res.User == "" || res.Secret == "" || res.Path == "" {
return nil, fmt.Errorf("invalid provisioner output")
}
// create secret in PVC's namespace
nameSpace := options.PVC.Namespace
secretName := "ceph-" + user + "-secret"
secret := &v1.Secret{
ObjectMeta: v1.ObjectMeta{
Namespace: nameSpace,
Name: secretName,
},
Data: map[string][]byte{
"key": []byte(res.Secret),
},
Type: "Opaque",
}
_, err = p.client.Core().Secrets(nameSpace).Create(secret)
if err != nil {
return nil, fmt.Errorf("failed to create secret")
}
if err != nil {
glog.Errorf("Cephfs Provisioner: create volume failed, err: %v", err)
return nil, err
}
pv := &v1.PersistentVolume{
ObjectMeta: v1.ObjectMeta{
Name: options.PVName,
Annotations: map[string]string{
provisionerIdAnn: string(p.identity),
cephShareAnn: share,
},
},
Spec: v1.PersistentVolumeSpec{
PersistentVolumeReclaimPolicy: options.PersistentVolumeReclaimPolicy,
AccessModes: []v1.PersistentVolumeAccessMode{
v1.ReadWriteOnce,
v1.ReadOnlyMany,
v1.ReadWriteMany,
},
Capacity: v1.ResourceList{ //FIXME: kernel cephfs doesn't enforce quota, capacity is not meaningless here.
v1.ResourceName(v1.ResourceStorage): options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)],
},
PersistentVolumeSource: v1.PersistentVolumeSource{
CephFS: &v1.CephFSVolumeSource{
Monitors: mon,
Path: res.Path[strings.Index(res.Path, "/"):],
SecretRef: &v1.LocalObjectReference{
Name: secretName,
},
User: user,
},
},
},
}
glog.Infof("successfully created CephFS share %+v", pv.Spec.PersistentVolumeSource.CephFS)
return pv, nil
}
// Delete removes the storage asset that was created by Provision represented
// by the given PV.
func (p *cephFSProvisioner) Delete(volume *v1.PersistentVolume) error {
ann, ok := volume.Annotations[provisionerIdAnn]
if !ok {
return errors.New("identity annotation not found on PV")
}
if ann != string(p.identity) {
return &controller.IgnoredError{"identity annotation on PV does not match ours"}
}
share, ok := volume.Annotations[cephShareAnn]
if !ok {
return errors.New("ceph share annotation not found on PV")
}
// delete CephFS
class, err := p.getClassForVolume(volume)
if err != nil {
return err
}
cluster, adminId, adminSecret, mon, err := p.parseParameters(class.Parameters)
if err != nil {
return err
}
user := volume.Spec.PersistentVolumeSource.CephFS.User
// create cmd
cmd := exec.Command(provisionCmd, "-r", "-n", share, "-u", user)
// set env
cmd.Env = []string{
"CEPH_CLUSTER_NAME=" + cluster,
"CEPH_MON=" + strings.Join(mon[:], ","),
"CEPH_AUTH_ID=" + adminId,
"CEPH_AUTH_KEY=" + adminSecret}
output, cmdErr := cmd.CombinedOutput()
if cmdErr != nil {
glog.Errorf("failed to delete share %q for %q, err: %v, output: %v", share, user, cmdErr, string(output))
return cmdErr
}
return nil
}
func (p *cephFSProvisioner) parseParameters(parameters map[string]string) (string, string, string, []string, error) {
var (
err error
mon []string
cluster, adminId, adminSecretName, adminSecretNamespace, adminSecret string
)
adminSecretNamespace = "default"
adminId = "admin"
cluster = "ceph"
for k, v := range parameters {
switch strings.ToLower(k) {
case "cluster":
cluster = v
case "monitors":
arr := strings.Split(v, ",")
for _, m := range arr {
mon = append(mon, m)
}
case "adminid":
adminId = v
case "adminsecretname":
adminSecretName = v
case "adminsecretnamespace":
adminSecretNamespace = v
default:
return "", "", "", nil, fmt.Errorf("invalid option %q", k)
}
}
// sanity check
if adminSecretName == "" {
return "", "", "", nil, fmt.Errorf("missing Ceph admin secret name")
}
if adminSecret, err = p.parsePVSecret(adminSecretNamespace, adminSecretName); err != nil {
return "", "", "", nil, fmt.Errorf("failed to get admin secret from [%q/%q]: %v", adminSecretNamespace, adminSecretName, err)
}
if len(mon) < 1 {
return "", "", "", nil, fmt.Errorf("missing Ceph monitors")
}
return cluster, adminId, adminSecret, mon, nil
}
func (p *cephFSProvisioner) parsePVSecret(namespace, secretName string) (string, error) {
if p.client == nil {
return "", fmt.Errorf("Cannot get kube client")
}
secrets, err := p.client.Core().Secrets(namespace).Get(secretName)
if err != nil {
return "", err
}
for _, data := range secrets.Data {
return string(data), nil
}
// If not found, the last secret in the map wins as done before
return "", fmt.Errorf("no secret found")
}
func (p *cephFSProvisioner) getClassForVolume(pv *v1.PersistentVolume) (*storage.StorageClass, error) {
className, found := pv.Annotations["volume.beta.kubernetes.io/storage-class"]
if !found {
return nil, fmt.Errorf("Volume has no class annotation")
}
class, err := p.client.Storage().StorageClasses().Get(className)
if err != nil {
return nil, err
}
return class, nil
}
var (
master = flag.String("master", "", "Master URL")
kubeconfig = flag.String("kubeconfig", "", "Absolute path to the kubeconfig")
)
func main() {
flag.Parse()
flag.Set("logtostderr", "true")
var config *rest.Config
var err error
if *master != "" || *kubeconfig != "" {
config, err = clientcmd.BuildConfigFromFlags(*master, *kubeconfig)
} else {
config, err = rest.InClusterConfig()
}
if err != nil {
glog.Fatalf("Failed to create config: %v", err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
glog.Fatalf("Failed to create client: %v", err)
}
// The controller needs to know what the server version is because out-of-tree
// provisioners aren't officially supported until 1.5
serverVersion, err := clientset.Discovery().ServerVersion()
if err != nil {
glog.Fatalf("Error getting server version: %v", err)
}
// Create the provisioner: it implements the Provisioner interface expected by
// the controller
cephFSProvisioner := NewCephFSProvisioner(clientset)
// Start the provision controller which will dynamically provision cephFS
// PVs
pc := controller.NewProvisionController(clientset, resyncPeriod, provisionerName, cephFSProvisioner, serverVersion.GitVersion, exponentialBackOffOnError, failedRetryThreshold)
pc.Run(wait.NeverStop)
}