forked from MatchbookLab/local-persist
-
Notifications
You must be signed in to change notification settings - Fork 0
/
driver.go
259 lines (200 loc) · 7.3 KB
/
driver.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
package main
import (
"fmt"
"sync"
"os"
"strconv"
"io/ioutil"
"path"
"encoding/json"
"github.com/docker/go-plugins-helpers/volume"
"github.com/docker/engine-api/client"
"github.com/docker/engine-api/types"
"github.com/fatih/color"
"golang.org/x/net/context"
)
var (
// red = color.New(color.FgRed).SprintfFunc()
// green = color.New(color.FgGreen).SprintfFunc()
yellow = color.New(color.FgYellow).SprintfFunc()
cyan = color.New(color.FgCyan).SprintfFunc()
blue = color.New(color.FgBlue).SprintfFunc()
magenta = color.New(color.FgMagenta).SprintfFunc()
white = color.New(color.FgWhite).SprintfFunc()
)
const (
stateDir = "/var/lib/docker/plugin-data/"
stateFile = "local-persist.json"
)
type localPersistDriver struct {
volumes map[string]string
mutex *sync.Mutex
debug bool
name string
}
type saveData struct {
State map[string]string `json:"state"`
}
func newLocalPersistDriver() localPersistDriver {
fmt.Printf(white("%-18s", "Starting... "))
driver := localPersistDriver{
volumes : map[string]string{},
mutex : &sync.Mutex{},
debug : true,
name : "local-persist",
}
os.Mkdir(stateDir, 0700)
_, driver.volumes = driver.findExistingVolumesFromStateFile()
fmt.Printf("Found %s volumes on startup\n", yellow(strconv.Itoa(len(driver.volumes))))
return driver
}
func (driver localPersistDriver) Get(req volume.Request) volume.Response {
fmt.Print(white("%-18s", "Get Called... "))
if driver.exists(req.Name) {
fmt.Printf("Found %s\n", cyan(req.Name))
return volume.Response{
Volume: driver.volume(req.Name),
}
}
fmt.Printf("Couldn't find %s\n", cyan(req.Name))
return volume.Response{
Err: fmt.Sprintf("No volume found with the name %s", cyan(req.Name)),
}
}
func (driver localPersistDriver) List(req volume.Request) volume.Response {
fmt.Print(white("%-18s", "List Called... "))
var volumes []*volume.Volume
for name, _ := range driver.volumes {
volumes = append(volumes, driver.volume(name))
}
fmt.Printf("Found %s volumes\n", yellow(strconv.Itoa(len(volumes))))
return volume.Response{
Volumes: volumes,
}
}
func (driver localPersistDriver) Create(req volume.Request) volume.Response {
fmt.Print(white("%-18s", "Create Called... "))
mountpoint := req.Options["mountpoint"]
if mountpoint == "" {
fmt.Printf("No %s option provided\n", blue("mountpoint"))
return volume.Response{ Err: fmt.Sprintf("The `mountpoint` option is required") }
}
driver.mutex.Lock()
defer driver.mutex.Unlock()
if driver.exists(req.Name) {
return volume.Response{ Err: fmt.Sprintf("The volume %s already exists", req.Name) }
}
err := os.MkdirAll(mountpoint, 0755)
fmt.Printf("Ensuring directory %s exists on host...\n", magenta(mountpoint))
if err != nil {
fmt.Printf("%17s Could not create directory %s\n", " ", magenta(mountpoint))
return volume.Response{ Err: err.Error() }
}
driver.volumes[req.Name] = mountpoint
e := driver.saveState(driver.volumes)
if e != nil {
fmt.Println(e.Error())
}
fmt.Printf("%17s Created volume %s with mountpoint %s\n", " ", cyan(req.Name), magenta(mountpoint))
return volume.Response{}
}
func (driver localPersistDriver) Remove(req volume.Request) volume.Response {
fmt.Print(white("%-18s", "Remove Called... "))
driver.mutex.Lock()
defer driver.mutex.Unlock()
delete(driver.volumes, req.Name)
err := driver.saveState(driver.volumes)
if err != nil {
fmt.Println(err.Error())
}
fmt.Printf("Removed %s\n", cyan(req.Name))
return volume.Response{}
}
func (driver localPersistDriver) Mount(req volume.MountRequest) volume.Response {
fmt.Print(white("%-18s", "Mount Called... "))
fmt.Printf("Mounted %s\n", cyan(req.Name))
return driver.Path(volume.Request{Name: req.Name})
}
func (driver localPersistDriver) Path(req volume.Request) volume.Response {
fmt.Print(white("%-18s", "Path Called... "))
fmt.Printf("Returned path %s\n", magenta(driver.volumes[req.Name]))
return volume.Response{ Mountpoint: driver.volumes[req.Name] }
}
func (driver localPersistDriver) Unmount(req volume.UnmountRequest) volume.Response {
fmt.Print(white("%-18s", "Unmount Called... "))
fmt.Printf("Unmounted %s\n", cyan(req.Name))
return driver.Path(volume.Request{Name: req.Name})
}
func (driver localPersistDriver) Capabilities(req volume.Request) volume.Response {
fmt.Print(white("%-18s", "Capabilities Called... "))
return volume.Response{
Capabilities: volume.Capability{ Scope: "local" },
}
}
func (driver localPersistDriver) exists(name string) bool {
return driver.volumes[name] != ""
}
func (driver localPersistDriver) volume(name string) *volume.Volume {
return &volume.Volume{
Name: name,
Mountpoint: driver.volumes[name],
}
}
func (driver localPersistDriver) findExistingVolumesFromDockerDaemon() (error, map[string]string) {
// set up the ability to make API calls to the daemon
defaultHeaders := map[string]string{"User-Agent": "engine-api-cli-1.0"}
// need at least Docker 1.9 (API v1.21) for named Volume support
cli, err := client.NewClient("unix:///var/run/docker.sock", "v1.21", nil, defaultHeaders)
if err != nil {
return err, map[string]string{}
}
// grab ALL containers...
options := types.ContainerListOptions{All: true}
containers, err := cli.ContainerList(context.Background(), options)
// ...and check to see if any of them belong to this driver and recreate their references
var volumes = map[string]string{}
for _, container := range containers {
info, err := cli.ContainerInspect(context.Background(), container.ID)
if err != nil {
// something really weird happened here... PANIC
panic(err)
}
for _, mount := range info.Mounts {
if mount.Driver == driver.name {
// @TODO there could be multiple volumes (mounts) with this { name: source } combo, and while that's okay
// what if they is the same name with a different source? could that happen? if it could,
// it'd be bad, so maybe we want to panic here?
volumes[mount.Name] = mount.Source
}
}
}
if err != nil || len(volumes) == 0 {
fmt.Print("Attempting to load from file state... ")
return driver.findExistingVolumesFromStateFile()
}
return nil, volumes
}
func (driver localPersistDriver) findExistingVolumesFromStateFile() (error, map[string]string) {
path := path.Join(stateDir, stateFile)
fileData, err := ioutil.ReadFile(path)
if err != nil {
return err, map[string]string{}
}
var data saveData
e := json.Unmarshal(fileData, &data)
if e != nil {
return e, map[string]string{}
}
return nil, data.State
}
func (driver localPersistDriver) saveState(volumes map[string]string) error {
data := saveData{
State: volumes,
}
fileData, err := json.Marshal(data)
if err != nil {
return err
}
path := path.Join(stateDir, stateFile)
return ioutil.WriteFile(path, fileData, 0600)
}