/
client.go
109 lines (94 loc) · 2.17 KB
/
client.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
package flexvolume
import (
"fmt"
"os"
"github.com/golang/protobuf/ptypes/empty"
"github.com/sirupsen/logrus"
"golang.org/x/net/context"
)
type client struct {
apiClient APIClient
}
const (
volumeIDKey = "volumeID"
)
var (
successBytes = []byte(`{"Status":"Success"}`)
)
func newClient(apiClient APIClient) *client {
return &client{apiClient}
}
func (c *client) Init() error {
_, err := c.apiClient.Init(
context.Background(),
&empty.Empty{},
)
return err
}
func (c *client) Attach(jsonOptions map[string]string) error {
_, err := c.apiClient.Attach(
context.Background(),
&AttachRequest{
JsonOptions: jsonOptions,
},
)
if err == nil {
writeOutput(newAttachSuccessOutput(jsonOptions[volumeIDKey]))
} else {
writeOutput(newFailureBytes(err))
}
return err
}
func (c *client) Detach(mountDevice string, options map[string]string) error {
_, err := c.apiClient.Detach(
context.Background(),
&DetachRequest{
MountDevice: mountDevice,
},
)
writeOutput(newOutput(err))
return err
}
func (c *client) Mount(targetMountDir string, mountDevice string, jsonOptions map[string]string) error {
if err := os.MkdirAll(targetMountDir, os.ModeDir); err != nil {
writeOutput(newOutput(err))
return err
}
_, err := c.apiClient.Mount(
context.Background(),
&MountRequest{
TargetMountDir: targetMountDir,
MountDevice: mountDevice,
JsonOptions: jsonOptions,
},
)
writeOutput(newOutput(err))
return err
}
func (c *client) Unmount(mountDir string, options map[string]string) error {
_, err := c.apiClient.Unmount(
context.Background(),
&UnmountRequest{
MountDir: mountDir,
},
)
writeOutput(newOutput(err))
return err
}
func newFailureBytes(err error) []byte {
return []byte(fmt.Sprintf(`{"Status":"Failure", "Message":"%s"}`, err.Error()))
}
func newOutput(err error) []byte {
if err != nil {
return newFailureBytes(err)
}
return successBytes
}
func newAttachSuccessOutput(deviceID string) []byte {
return []byte(fmt.Sprintf(`{"Status":"Success", "Device":"%s"}`, deviceID))
}
func writeOutput(output []byte) {
if _, err := os.Stdout.Write(output); err != nil {
logrus.Warnf("Unable to write output to stdout : %s", err.Error())
}
}