forked from ContainX/docker-volume-netshare
-
Notifications
You must be signed in to change notification settings - Fork 2
/
netshare.go
379 lines (337 loc) · 13.1 KB
/
netshare.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
377
378
379
package netshare
import (
"context"
"fmt"
"os"
"path/filepath"
"strconv"
"syscall"
"github.com/ContainX/docker-volume-netshare/netshare/drivers"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/client"
"github.com/docker/go-plugins-helpers/volume"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
const (
UsernameFlag = "username"
PasswordFlag = "password"
DomainFlag = "domain"
SecurityFlag = "security"
FileModeFlag = "fileMode"
DirModeFlag = "dirMode"
VersionFlag = "version"
OptionsFlag = "options"
BasedirFlag = "basedir"
VerboseFlag = "verbose"
AvailZoneFlag = "az"
NoResolveFlag = "noresolve"
NetRCFlag = "netrc"
TCPFlag = "tcp"
PortFlag = "port"
NameServerFlag = "nameserver"
NameFlag = "name"
SecretFlag = "secret"
ContextFlag = "context"
CephMount = "sorcemount"
CephPort = "port"
CephOpts = "options"
ServerMount = "servermount"
StateFlag = "state"
CacheFlag = "cache"
LazyUmountFlag = "lazyumount"
TimeoutMountFlag = "timeoutmount"
DockerEngineAPI = "dockerapiversion"
EnvSambaUser = "NETSHARE_CIFS_USERNAME"
EnvSambaPass = "NETSHARE_CIFS_PASSWORD"
EnvSambaWG = "NETSHARE_CIFS_DOMAIN"
EnvSambaSec = "NETSHARE_CIFS_SECURITY"
EnvSambaFileMode = "NETSHARE_CIFS_FILEMODE"
EnvSambaDirMode = "NETSHARE_CIFS_DIRMODE"
EnvNfsVers = "NETSHARE_NFS_VERSION"
EnvTCP = "NETSHARE_TCP_ENABLED"
EnvTCPAddr = "NETSHARE_TCP_ADDR"
EnvSocketName = "NETSHARE_SOCKET_NAME"
PluginAlias = "netshare"
NetshareHelp = `
docker-volume-netshare (NFS V3/4, AWS EFS and CIFS Volume Driver Plugin)
Provides docker volume support for NFS v3 and 4, EFS as well as CIFS. This plugin can be run multiple times to
support different mount types.
== Version: %s - Built: %s ==
`
)
var (
rootCmd = &cobra.Command{
Use: "docker-volume-netshare",
Short: "NFS and CIFS - Docker volume driver plugin",
Long: NetshareHelp,
PersistentPreRun: setupLogger,
}
cifsCmd = &cobra.Command{
Use: "cifs",
Short: "run plugin in CIFS mode",
Run: execCIFS,
}
nfsCmd = &cobra.Command{
Use: "nfs",
Short: "run plugin in NFS mode",
Run: execNFS,
}
nfsCacheCmd = &cobra.Command{
Use: "nfscache",
Short: "run plugin in NFS/ccache mode",
Run: execNFSCACHE,
}
efsCmd = &cobra.Command{
Use: "efs",
Short: "run plugin in AWS EFS mode",
Run: execEFS,
}
cephCmd = &cobra.Command{
Use: "ceph",
Short: "run plugin in Ceph mode",
Run: execCEPH,
}
versionCmd = &cobra.Command{
Use: "version",
Short: "Display current version and build date",
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("\nVersion: %s - Built: %s\n\n", Version, BuildDate)
},
}
baseDir = ""
Version string = ""
BuildDate string = ""
)
func Execute() {
setupFlags()
rootCmd.Long = fmt.Sprintf(NetshareHelp, Version, BuildDate)
rootCmd.AddCommand(versionCmd, cifsCmd, nfsCmd, nfsCacheCmd, efsCmd, cephCmd)
rootCmd.Execute()
}
func setupFlags() {
rootCmd.PersistentFlags().StringVar(&baseDir, BasedirFlag, filepath.Join(volume.DefaultDockerRootDirectory, PluginAlias), "Mounted volume base directory")
rootCmd.PersistentFlags().Bool(TCPFlag, false, "Bind to TCP rather than Unix sockets. Can also be set via NETSHARE_TCP_ENABLED")
rootCmd.PersistentFlags().String(PortFlag, ":8877", "TCP Port if --tcp flag is true. :PORT for all interfaces or ADDRESS:PORT to bind.")
rootCmd.PersistentFlags().Bool(VerboseFlag, false, "Turns on verbose logging")
rootCmd.PersistentFlags().StringP(DockerEngineAPI, "a", "", "Docker Engine API Version. Default to latest stable.")
cifsCmd.Flags().StringP(UsernameFlag, "u", "", "Username to use for mounts. Can also set environment NETSHARE_CIFS_USERNAME")
cifsCmd.Flags().StringP(PasswordFlag, "p", "", "Password to use for mounts. Can also set environment NETSHARE_CIFS_PASSWORD")
cifsCmd.Flags().StringP(DomainFlag, "d", "", "Domain to use for mounts. Can also set environment NETSHARE_CIFS_DOMAIN")
cifsCmd.Flags().StringP(SecurityFlag, "s", "", "Security mode to use for mounts (mount.cifs's sec option). Can also set environment NETSHARE_CIFS_SECURITY.")
cifsCmd.Flags().StringP(FileModeFlag, "f", "", "Setting access rights for files (mount.cifs's file_mode option). Can also set environment NETSHARE_CIFS_FILEMODE.")
cifsCmd.Flags().StringP(DirModeFlag, "z", "", "Setting access rights for folders (mount.cifs's dir_mode option). Can also set environment NETSHARE_CIFS_DIRMODE.")
cifsCmd.Flags().StringP(NetRCFlag, "", os.Getenv("HOME"), "The default .netrc location. Default is the user.home directory")
cifsCmd.Flags().StringP(OptionsFlag, "o", "", "Options passed to Cifs mounts (ex: nounix,uid=433)")
nfsCmd.Flags().IntP(VersionFlag, "v", 4, "NFS Version to use [3 | 4]. Can also be set with NETSHARE_NFS_VERSION")
nfsCmd.Flags().StringP(OptionsFlag, "o", "", fmt.Sprintf("Options passed to nfs mounts (ex: %s)", drivers.DefaultNfsV3))
nfsCacheCmd.Flags().IntP(VersionFlag, "v", 4, "NFS Version to use [3 | 4]. Can also be set with NETSHARE_NFS_VERSION")
nfsCacheCmd.Flags().StringP(OptionsFlag, "o", "", fmt.Sprintf("Options passed to nfs mounts (ex: %s)", drivers.DefaultNfsCacheV3))
nfsCacheCmd.Flags().StringP(StateFlag, "F", "/run/nfscache.json", "State file.")
nfsCacheCmd.Flags().StringP(CacheFlag, "C", "/tmp", "Credentials cache directory.")
nfsCacheCmd.Flags().Bool(LazyUmountFlag, false, "Make the umount as soon as the filesystem is not busy anymore.")
nfsCacheCmd.Flags().IntP(TimeoutMountFlag, "t", 40, "Timeout to apply over mount execution")
efsCmd.Flags().String(AvailZoneFlag, "", "AWS Availability zone [default: \"\", looks up via metadata]")
efsCmd.Flags().String(NameServerFlag, "", "Custom DNS nameserver. [default \"\", uses /etc/resolv.conf]")
efsCmd.Flags().Bool(NoResolveFlag, false, "Indicates EFS mount sources are IP Addresses vs File System ID")
cephCmd.Flags().StringP(NameFlag, "n", "admin", "Username to use for ceph mount.")
cephCmd.Flags().StringP(SecretFlag, "s", "NoneProvided", "Password to use for Ceph Mount.")
cephCmd.Flags().StringP(ContextFlag, "c", "system_u:object_r:tmp_t:s0", "SELinux Context of Ceph Mount.")
cephCmd.Flags().StringP(CephMount, "m", "10.0.0.1", "Address of Ceph source mount.")
cephCmd.Flags().StringP(CephPort, "p", "6789", "Port to use for ceph mount.")
cephCmd.Flags().StringP(ServerMount, "S", "/mnt/ceph", "Directory to use as ceph local mount.")
cephCmd.Flags().StringP(OptionsFlag, "o", "", "Options passed to Ceph mounts ")
}
func setupLogger(cmd *cobra.Command, args []string) {
if verbose, _ := cmd.Flags().GetBool(VerboseFlag); verbose {
log.SetLevel(log.DebugLevel)
} else {
log.SetLevel(log.InfoLevel)
}
}
func setDockerEnv() {
api, _ := rootCmd.PersistentFlags().GetString(DockerEngineAPI)
if api != "" {
os.Setenv("DOCKER_API_VERSION", api)
log.Infof("DOCKER_API_VERSION: %s", api)
}
}
func execCEPH(cmd *cobra.Command, args []string) {
username, _ := cmd.Flags().GetString(NameFlag)
password, _ := cmd.Flags().GetString(SecretFlag)
context, _ := cmd.Flags().GetString(ContextFlag)
cephmount, _ := cmd.Flags().GetString(CephMount)
cephport, _ := cmd.Flags().GetString(CephPort)
servermount, _ := cmd.Flags().GetString(ServerMount)
cephopts, _ := cmd.Flags().GetString(CephOpts)
setDockerEnv()
if len(username) > 0 {
username = "name=" + username
}
if len(password) > 0 {
password = "secret=" + password
}
if len(context) > 0 {
context = "context=" + "\"" + context + "\""
}
mount := syncDockerState("ceph")
d := drivers.NewCephDriver(rootForType(drivers.CEPH), username, password, context, cephmount, cephport, servermount, cephopts, mount)
start(drivers.CEPH, d)
}
func execNFS(cmd *cobra.Command, args []string) {
version, _ := cmd.Flags().GetInt(VersionFlag)
setDockerEnv()
if os.Getenv(EnvNfsVers) != "" {
if v, err := strconv.Atoi(os.Getenv(EnvNfsVers)); err == nil {
if v == 3 || v == 4 {
version = v
}
}
}
options, _ := cmd.Flags().GetString(OptionsFlag)
mount := syncDockerState("nfs")
d := drivers.NewNFSDriver(rootForType(drivers.NFS), version, options, mount)
startOutput(fmt.Sprintf("NFS Version %d :: options: '%s'", version, options))
start(drivers.NFS, d)
}
func execNFSCACHE(cmd *cobra.Command, args []string) {
version, _ := cmd.Flags().GetInt(VersionFlag)
stateFile, _ := cmd.Flags().GetString(StateFlag)
cacheDir, _ := cmd.Flags().GetString(CacheFlag)
lazyUmount, _ := cmd.Flags().GetBool(LazyUmountFlag)
timeoutMount, _ := cmd.Flags().GetInt(TimeoutMountFlag)
setDockerEnv()
if os.Getenv(EnvNfsVers) != "" {
if v, err := strconv.Atoi(os.Getenv(EnvNfsVers)); err == nil {
if v == 3 || v == 4 {
version = v
}
}
}
options, _ := cmd.Flags().GetString(OptionsFlag)
mount := syncDockerState("nfs")
d := drivers.NewNFSCacheDriver(rootForType(drivers.NFS), version, options, mount, cacheDir, stateFile, lazyUmount, timeoutMount)
startOutput(fmt.Sprintf("NFS CCache Version %d :: options: '%s', cache: '%s', state: '%s', lazy umount: %v, Timeout mount: %d", version, options, cacheDir, stateFile, lazyUmount, timeoutMount))
start(drivers.NFS, d)
}
func execEFS(cmd *cobra.Command, args []string) {
resolve, _ := cmd.Flags().GetBool(NoResolveFlag)
ns, _ := cmd.Flags().GetString(NameServerFlag)
setDockerEnv()
mount := syncDockerState("efs")
d := drivers.NewEFSDriver(rootForType(drivers.EFS), ns, !resolve, mount)
startOutput(fmt.Sprintf("EFS :: resolve: %v, ns: %s", resolve, ns))
start(drivers.EFS, d)
}
func execCIFS(cmd *cobra.Command, args []string) {
user := typeOrEnv(cmd, UsernameFlag, EnvSambaUser)
pass := typeOrEnv(cmd, PasswordFlag, EnvSambaPass)
domain := typeOrEnv(cmd, DomainFlag, EnvSambaWG)
security := typeOrEnv(cmd, SecurityFlag, EnvSambaSec)
fileMode := typeOrEnv(cmd, FileModeFlag, EnvSambaFileMode)
dirMode := typeOrEnv(cmd, DirModeFlag, EnvSambaDirMode)
netrc, _ := cmd.Flags().GetString(NetRCFlag)
options, _ := cmd.Flags().GetString(OptionsFlag)
setDockerEnv()
creds := drivers.NewCifsCredentials(user, pass, domain, security, fileMode, dirMode)
mount := syncDockerState("cifs")
d := drivers.NewCIFSDriver(rootForType(drivers.CIFS), creds, netrc, options, mount)
if len(user) > 0 {
startOutput(fmt.Sprintf("CIFS :: %s, opts: %s", creds, options))
} else {
startOutput(fmt.Sprintf("CIFS :: netrc: %s, opts: %s", netrc, options))
}
start(drivers.CIFS, d)
}
func startOutput(info string) {
log.Infof("== docker-volume-netshare :: Version: %s - Built: %s ==", Version, BuildDate)
log.Infof("Starting %s", info)
}
func typeOrEnv(cmd *cobra.Command, flag, envname string) string {
val, _ := cmd.Flags().GetString(flag)
if val == "" {
val = os.Getenv(envname)
}
return val
}
func rootForType(dt drivers.DriverType) string {
return filepath.Join(baseDir, dt.String())
}
func start(dt drivers.DriverType, driver volume.Driver) {
h := volume.NewHandler(driver)
if isTCPEnabled() {
addr := os.Getenv(EnvTCPAddr)
if addr == "" {
addr, _ = rootCmd.PersistentFlags().GetString(PortFlag)
}
// TODO: if platform == windows, use WindowsDefaultDaemonRootDir()
fmt.Println(h.ServeTCP(dt.String(), addr, "", nil))
} else {
socketName := os.Getenv(EnvSocketName)
if socketName == "" {
socketName = dt.String()
}
fmt.Println(h.ServeUnix(socketName, syscall.Getgid()))
}
}
func isTCPEnabled() bool {
if tcp, _ := rootCmd.PersistentFlags().GetBool(TCPFlag); tcp {
return tcp
}
if os.Getenv(EnvTCP) != "" {
ev, _ := strconv.ParseBool(os.Getenv(EnvTCP))
fmt.Println(ev)
return ev
}
return false
}
func syncDockerState(driverName string) *drivers.MountManager {
log.Infof("Checking for the references of volumes in docker daemon.")
mount := newMountManager()
cli, err := client.NewEnvClient()
if err != nil {
log.Error(err)
}
volumes, err := cli.VolumeList(context.Background(), filters.Args{})
if err != nil {
log.Fatal(err, ". Use -a flag to setup the DOCKER_API_VERSION. Run 'docker-volume-netshare --help' for usage.")
}
for _, vol := range volumes.Volumes {
if !(vol.Driver == driverName) {
continue
}
connections := activeConnections(vol.Name)
log.Infof("Recovered state: %s , %s , %s , %s , %d ", vol.Name, vol.Mountpoint, vol.Driver, vol.CreatedAt, connections)
mount.AddMount(vol.Name, vol.Mountpoint, connections)
}
return mount
}
func newMountManager() *drivers.MountManager {
mount := drivers.NewVolumeManager()
return mount
}
// The number of running containers using Volume
func activeConnections(volumeName string) int {
cli, err := client.NewEnvClient()
if err != nil {
log.Error(err)
}
var counter = 0
ContainerListResponse, err := cli.ContainerList(context.Background(), types.ContainerListOptions{}) //Only check the running containers using volume
if err != nil {
log.Fatal(err, ". Use -a flag to setup the DOCKER_API_VERSION. Run 'docker-volume-netshare --help' for usage.")
}
for _, container := range ContainerListResponse {
if len(container.Mounts) == 0 {
continue
}
for _, mounts := range container.Mounts {
if !(mounts.Name == volumeName) {
continue
}
counter++
}
}
return counter
}