forked from torchbox/k8s-hostpath-provisioner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhostpath-provisioner.go
294 lines (256 loc) · 8.15 KB
/
hostpath-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
/* vim:set sw=8 ts=8 noet:
*
* Copyright 2016 The Kubernetes Authors.
* Copyright 2017 Torchbox Ltd.
*
* 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 main
import (
"context"
"errors"
"flag"
"fmt"
"os"
"path"
"strconv"
"strings"
"time"
"github.com/golang/glog"
"sigs.k8s.io/sig-storage-lib-external-provisioner/v7/controller"
"sigs.k8s.io/sig-storage-lib-external-provisioner/v7/util"
"github.com/pkg/xattr"
"k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"syscall"
)
/* Our constants */
const (
resyncPeriod = 15 * time.Second
provisionerName = "torchbox.com/hostpath"
provisionerIDAnn = "torchbox.com/hostpath-provisioner-id"
)
/* Our provisioner class, which implements the controller API. */
type hostPathProvisioner struct {
client kubernetes.Interface /* Kubernetes client for accessing the cluster during provision */
identity string /* Our unique provisioner identity */
}
/* Storage the parsed configuration from the storage class */
type hostPathParameters struct {
pvDir string /* On-disk path of the PV root */
cephFSQuota bool /* Whether to set CephFS quota xattrs */
}
/*
* Create a new provisioner from a given client and identity.
*/
func NewHostPathProvisioner(client kubernetes.Interface, id string) controller.Provisioner {
return &hostPathProvisioner{
client: client,
identity: id,
}
}
var _ controller.Provisioner = &hostPathProvisioner{}
/*
* Provision: create the physical on-disk path for this PV and return a new
* volume referencing it as a hostPath. The volume is annotated with our
* provisioner id, so multiple provisioners can run on the same cluster.
*/
func (p *hostPathProvisioner) Provision(ctx context.Context, options controller.ProvisionOptions) (*v1.PersistentVolume, controller.ProvisioningState, error) {
/*
* Fetch the PV root directory from the PV storage class.
*/
params, err := p.parseParameters(options.StorageClass.Parameters)
if err != nil {
return nil, controller.ProvisioningFinished, err
}
/*
* Extract the PV capacity as bytes. We can use this to set CephFS
* quotas.
*/
capacity := options.PVC.Spec.Resources.Requests[v1.ResourceStorage]
volbytes := capacity.Value()
glog.Infof("pv storage: %+v", volbytes)
if volbytes <= 0 {
return nil, controller.ProvisioningFinished, fmt.Errorf("storage capacity must be >= 0 (not %+v)", capacity.String())
}
/* Create the on-disk directory. */
path := path.Join(params.pvDir, options.PVName)
if err := os.MkdirAll(path, 0777); err != nil {
glog.Errorf("failed to mkdir %s: %s", path, err)
return nil, controller.ProvisioningFinished, err
}
if err := os.Chmod(path, 0777); err != nil {
glog.Errorf("failed to chmod %s, %s", path, err)
return nil, controller.ProvisioningFinished, err
}
/* Set CephFS quota, if enabled */
if params.cephFSQuota {
err := xattr.Set(path, "ceph.quota.max_bytes", []byte(strconv.FormatInt(volbytes, 10)))
if err != nil {
glog.Errorf("could not set CephFS quota on %s (%s): %s",
options.PVName, path, err)
os.RemoveAll(path)
return nil, controller.ProvisioningFinished, err
}
}
/* The actual PV we will create */
pv := &v1.PersistentVolume{
ObjectMeta: metav1.ObjectMeta{
Name: options.PVName,
Annotations: map[string]string{
provisionerIDAnn: p.identity,
},
},
Spec: v1.PersistentVolumeSpec{
PersistentVolumeReclaimPolicy: *options.StorageClass.ReclaimPolicy,
AccessModes: options.PVC.Spec.AccessModes,
Capacity: v1.ResourceList{
v1.ResourceStorage: options.PVC.Spec.Resources.Requests[v1.ResourceStorage],
},
PersistentVolumeSource: v1.PersistentVolumeSource{
HostPath: &v1.HostPathVolumeSource{
Path: path,
},
},
},
}
glog.Infof("successfully created hostpath volume %s (%s)",
options.PVName, path)
return pv, controller.ProvisioningFinished, nil
}
/*
* Delete: remove a PV from the disk by deleting its directory.
*/
func (p *hostPathProvisioner) Delete(ctx context.Context, volume *v1.PersistentVolume) error {
/* Ensure this volume was provisioned by us */
ann, ok := volume.Annotations[provisionerIDAnn]
if !ok {
glog.Infof("not removing volume <%s>: identity annotation <%s> missing",
volume.Name, provisionerIDAnn)
return errors.New("identity annotation not found on PV")
}
if ann != p.identity {
glog.Infof("not removing volume <%s>: identity annotation <%s> does not match ours <%s>",
volume.Name, p.identity, provisionerIDAnn)
return &controller.IgnoredError{Reason: "identity annotation on PV does not match ours"}
}
/*
* Fetch the PV class to get the pvDir. I don't think there would be
* any security implications from using the hostPath in the volume
* directly, but this feels more correct.
*/
class, err := p.client.StorageV1().StorageClasses().Get(
ctx,
util.GetPersistentVolumeClass(volume),
metav1.GetOptions{})
if err != nil {
glog.Infof("not removing volume <%s>: failed to fetch storageclass: %s",
volume.Name, err)
return err
}
params, err := p.parseParameters(class.Parameters)
if err != nil {
glog.Infof("not removing volume <%s>: failed to parse storageclass parameters: %s",
volume.Name, err)
return err
}
/*
* Construct the on-disk path based on the pvDir and volume name, then
* delete it.
*/
path := path.Join(params.pvDir, volume.Name)
if err := os.RemoveAll(path); err != nil {
glog.Errorf("failed to remove PV %s (%s): %v",
volume.Name, path, err)
return err
}
return nil
}
func (p *hostPathProvisioner) parseParameters(parameters map[string]string) (*hostPathParameters, error) {
var params hostPathParameters
for k, v := range parameters {
switch strings.ToLower(k) {
case "pvdir":
params.pvDir = v
case "cephfsquota":
switch v {
case "true":
params.cephFSQuota = true
case "false":
params.cephFSQuota = false
default:
return nil, fmt.Errorf("invalid value for cephFSQuota: %s (should be true or false)", v)
}
default:
return nil, fmt.Errorf("invalid option %q", k)
}
}
if params.pvDir == "" {
return nil, fmt.Errorf("missing PV directory (pvDir)")
}
return ¶ms, nil
}
var (
master = flag.String("master", "", "Master URL")
kubeconfig = flag.String("kubeconfig", "", "Absolute path to the kubeconfig")
name = flag.String("name", "", "Provisioner name")
id = flag.String("id", "", "Unique provisioner identity")
)
func main() {
syscall.Umask(022)
flag.Parse()
flag.Set("logtostderr", "true")
/* Configure the client based on our command line. */
var config *rest.Config
var err error
if *master != "" || *kubeconfig != "" {
glog.Infof("using out-of-cluster configuration")
config, err = clientcmd.BuildConfigFromFlags(*master, *kubeconfig)
} else {
glog.Infof("using in-cluster configuration; use -master or -kubeconfig to change")
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)
}
/*
* Default provisioner id to the name; the user can override with the
* -id option.
*/
prID := provisionerName
if *id != "" {
prID = *id
}
prName := provisionerName
if *name != "" {
prName = *name
}
/*
* Create the provisioner, which has a standard interface (Provision,
* Delete) used by the controller to notify us what to do.
*/
hostPathProvisioner := NewHostPathProvisioner(clientset, prID)
/* Start the controller */
pc := controller.NewProvisionController(
clientset,
prName,
hostPathProvisioner)
pc.Run(context.Background())
}