-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnexentastor5-nfs-provisioner.go
376 lines (345 loc) · 12.8 KB
/
nexentastor5-nfs-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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
/*
Copyright 2016 The Kubernetes 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 main
import (
"crypto/tls"
"errors"
"time"
"fmt"
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
log "github.com/Sirupsen/logrus"
"github.com/kubernetes-incubator/external-storage/lib/controller"
"k8s.io/client-go/pkg/api/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"os"
"path/filepath"
"strings"
"syscall"
)
const (
resyncPeriod = 15 * time.Second
provisionerName = "nexenta.com/k8s-nexentastor5-nfs"
exponentialBackOffOnError = false
failedRetryThreshold = 5
leasePeriod = controller.DefaultLeaseDuration
retryPeriod = controller.DefaultRetryPeriod
renewDeadline = controller.DefaultRenewDeadline
termLimit = controller.DefaultTermLimit
defaultParentFilesystem = "kubernetes"
)
type NexentaStorProvisioner struct {
// Identity of this NexentaStorProvisioner, set to node's name. Used to identify
// "this" provisioner's PVs.
Identity string
Hostname string
Port string
Pool string
Path string
ParentFS string
Endpoint string
Auth Auth
}
type Auth struct {
Username string `json:"username"`
Password string `json:"password"`
}
func NewNexentaStorProvisioner() controller.Provisioner {
nodeName := os.Getenv("NODE_NAME")
if nodeName == "" {
log.Fatal("env variable NODE_NAME must be set so that this provisioner can identify itself")
}
hostname := os.Getenv("NEXENTA_HOSTNAME")
if hostname == "" {
log.Fatal("env variable NEXENTA_HOSTNAME must be set to communicate with via Rest API")
}
port := os.Getenv("NEXENTA_HOSTPORT")
if port == "" {
log.Fatal("env variable NEXENTA_HOSTPORT must be set to communicate with via Rest API")
}
pool := os.Getenv("NEXENTA_HOSTPOOL")
if pool == "" {
log.Fatal("env variable NEXENTA_HOSTPOOL must be set")
}
username := os.Getenv("NEXENTA_USERNAME")
if username == "" {
log.Fatal("env variable NEXENTA_USERNAME must be set")
}
password := os.Getenv("NEXENTA_PASSWORD")
if password == "" {
log.Fatal("env variable NEXENTA_PASSWORD must be set")
}
parentFS := os.Getenv("PARENT_FILESYSTEM")
if parentFS == "" {
parentFS = defaultParentFilesystem
}
auth := Auth{Username: username, Password: password}
return &NexentaStorProvisioner{
Identity: nodeName,
Hostname: hostname,
Port: port,
Pool: pool,
ParentFS: parentFS,
Path: filepath.Join(pool, parentFS),
Auth: auth,
Endpoint: fmt.Sprintf("https://%s:%d/", hostname, port),
}
}
func (p *NexentaStorProvisioner) Initialize() {
data := map[string]interface{} {
"path": filepath.Join(p.Path, p.ParentFS),
}
p.Request("POST", "storage/filesystems", data)
}
type FileSystem struct {
Path string `json:"path"`
QuotaSize int64 `json:"quotaSize"`
}
type NFS struct {
FileSystem string `json:"filesystem"`
Anon string `json:"anon"`
}
// Provision creates a storage asset and returns a PV object representing it.
func (p *NexentaStorProvisioner) Provision(options controller.VolumeOptions) (pv *v1.PersistentVolume, err error) {
log.Debug("Creating volume %s", options.PVName)
data := map[string]interface{} {
"path": filepath.Join(p.Path, options.PVName),
}
p.Request("POST", "storage/filesystems", data)
data = make(map[string]interface{})
data["anon"] = "root"
data["filesystem"] = filepath.Join(p.Path, options.PVName)
p.Request("POST", "nas/nfs", data)
url := "storage/filesystems/" + p.Pool + "%2F" + p.ParentFS + "%2F" + options.PVName
resp, err := p.Request("GET", url, nil)
r := make(map[string]interface{})
jsonerr := json.Unmarshal(resp, &r)
if (jsonerr != nil) {
log.Fatal(jsonerr)
}
pv = &v1.PersistentVolume{
ObjectMeta: metav1.ObjectMeta{
Name: options.PVName,
Annotations: map[string]string{
"nexentaStorProvisionerIdentity": p.Identity,
},
},
Spec: v1.PersistentVolumeSpec{
PersistentVolumeReclaimPolicy: options.PersistentVolumeReclaimPolicy,
AccessModes: options.PVC.Spec.AccessModes,
Capacity: v1.ResourceList{
v1.ResourceName(v1.ResourceStorage): options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)],
},
PersistentVolumeSource: v1.PersistentVolumeSource{
NFS: &v1.NFSVolumeSource{
Server: p.Hostname,
Path: r["mountPoint"].(string),
ReadOnly: false,
},
},
},
}
return
}
// Delete removes the storage asset that was created by Provision represented
// by the given PV.
func (p *NexentaStorProvisioner) Delete(volume *v1.PersistentVolume) error {
name := volume.ObjectMeta.Name
log.Debug("Deleting Volume ", name)
vname, err := p.GetVolume(name)
if vname == "" {
log.Error("Volume %s does not exist.", name)
return err
}
path := filepath.Join(p.Path, name)
body, err := p.Request("DELETE", filepath.Join("storage/filesystems/", url.QueryEscape(path)), nil)
if strings.Contains(string(body), "ENOENT") {
log.Debug("Error trying to delete volume ", name, " :", string(body))
}
return nil
}
func (p *NexentaStorProvisioner) GetVolume(name string) (vname string, err error) {
log.Debug("GetVolume ", name)
url := fmt.Sprintf("/storage/filesystems?path=%s", filepath.Join(p.Path, name))
body, err := p.Request("GET", url, nil)
r := make(map[string][]map[string]interface{})
jsonerr := json.Unmarshal(body, &r)
if (jsonerr != nil) {
log.Error(jsonerr)
}
if len(r["data"]) < 1 {
err = fmt.Errorf("Failed to find any volumes with name: %s.", name)
return vname, err
} else {
log.Info(r["data"])
if v,ok := r["data"][0]["path"].(string); ok {
vname = strings.Split(v, fmt.Sprintf("%s/", p.Path))[1]
} else {
return "", fmt.Errorf("Path is not of type string")
}
}
return vname, err
}
func (p *NexentaStorProvisioner) Request(method, endpoint string, data map[string]interface{}) (body []byte, err error) {
log.Debug("Issue request to Nexenta, endpoint: ", endpoint, " data: ", data, " method: ", method)
if p.Endpoint == "" {
log.Error("Endpoint is not set, unable to issue requests")
err = errors.New("Unable to issue json-rpc requests without specifying Endpoint")
return nil, err
}
datajson, err := json.Marshal(data)
if (err != nil) {
log.Error(err)
}
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
url := p.Endpoint + endpoint
req, err := http.NewRequest(method, url, nil)
if len(data) != 0 {
req, err = http.NewRequest(method, url, strings.NewReader(string(datajson)))
}
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
log.Debug("No auth: ", resp.StatusCode, resp.Body)
if resp.StatusCode == 401 || resp.StatusCode == 403 {
auth, err := p.https_auth()
if err != nil {
log.Error("Error while trying to https login: %s", err)
return nil, err
}
req, err = http.NewRequest(method, url, nil)
if len(data) != 0 {
req, err = http.NewRequest(method, url, strings.NewReader(string(datajson)))
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", auth))
resp, err = client.Do(req)
log.Debug("With auth: ", resp.StatusCode, resp.Body)
}
if err != nil {
log.Error("Error while handling request %s", err)
return nil, err
}
p.checkError(resp)
defer resp.Body.Close()
body, err = ioutil.ReadAll(resp.Body)
if (err != nil) {
log.Error(err)
}
if (resp.StatusCode == 202) {
body, err = p.resend202(body)
}
return body, err
}
func (p *NexentaStorProvisioner) https_auth() (token string, err error){
data := map[string]string {
"username": p.Auth.Username,
"password": p.Auth.Password,
}
datajson, err := json.Marshal(data)
url := p.Endpoint + "auth/login"
req, err := http.NewRequest("POST", url, strings.NewReader(string(datajson)))
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
log.Debug(resp.StatusCode, resp.Body)
if err != nil {
log.Error("Error while handling request: %s", err)
return "", err
}
p.checkError(resp)
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if (err != nil) {
log.Error(err)
}
r := make(map[string]interface{})
err = json.Unmarshal(body, &r)
if (err != nil) {
err = fmt.Errorf("Error while trying to unmarshal json: %s", err)
return "", err
}
return r["token"].(string), err
}
func (p *NexentaStorProvisioner) resend202(body []byte) ([]byte, error) {
time.Sleep(1000 * time.Millisecond)
r := make(map[string][]map[string]string)
err := json.Unmarshal(body, &r)
if (err != nil) {
err = fmt.Errorf("Error while trying to unmarshal json %s", err)
return body, err
}
url := p.Endpoint + r["links"][0]["href"]
req, err := http.NewRequest("GET", url, nil)
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
err = fmt.Errorf("Error while handling request %s", err)
return body, err
}
defer resp.Body.Close()
p.checkError(resp)
if resp.StatusCode == 202 {
body, err = p.resend202(body)
}
body, err = ioutil.ReadAll(resp.Body)
return body, err
}
func (p *NexentaStorProvisioner) checkError(resp *http.Response) (err error) {
if resp.StatusCode > 401 {
body, err := ioutil.ReadAll(resp.Body)
err = fmt.Errorf("Got error in response from Nexenta, status_code: %s, body: %s", resp.StatusCode, string(body))
return err
}
return err
}
func main() {
syscall.Umask(0)
// Create an InClusterConfig and use it to create a client for the controller
// to use to communicate with Kubernetes
config, err := rest.InClusterConfig()
if err != nil {
log.Fatalf("Failed to create config: %v", err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.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 {
log.Fatalf("Error getting server version: %v", err)
}
// Create the provisioner: it implements the Provisioner interface expected by
// the controller
nexentaStorProvisioner := NewNexentaStorProvisioner()
// Start the provision controller which will dynamically provision nexentaStor
// PVs
pc := controller.NewProvisionController(clientset, resyncPeriod, provisionerName, nexentaStorProvisioner, serverVersion.GitVersion, exponentialBackOffOnError, failedRetryThreshold, leasePeriod, renewDeadline, retryPeriod, termLimit)
pc.Run(wait.NeverStop)
}