github.com/walkingsparrow/docker@v1.4.2-0.20151218153551-b708a2249bfa/pkg/plugins/discovery.go (about) 1 package plugins 2 3 import ( 4 "encoding/json" 5 "errors" 6 "fmt" 7 "io/ioutil" 8 "net/url" 9 "os" 10 "path/filepath" 11 "strings" 12 ) 13 14 var ( 15 // ErrNotFound plugin not found 16 ErrNotFound = errors.New("Plugin not found") 17 socketsPath = "/run/docker/plugins" 18 specsPaths = []string{"/etc/docker/plugins", "/usr/lib/docker/plugins"} 19 ) 20 21 // localRegistry defines a registry that is local (using unix socket). 22 type localRegistry struct{} 23 24 func newLocalRegistry() localRegistry { 25 return localRegistry{} 26 } 27 28 // Plugin returns the plugin registered with the given name (or returns an error). 29 func (l *localRegistry) Plugin(name string) (*Plugin, error) { 30 socketpaths := pluginPaths(socketsPath, name, ".sock") 31 32 for _, p := range socketpaths { 33 if fi, err := os.Stat(p); err == nil && fi.Mode()&os.ModeSocket != 0 { 34 return newLocalPlugin(name, "unix://"+p), nil 35 } 36 } 37 38 var txtspecpaths []string 39 for _, p := range specsPaths { 40 txtspecpaths = append(txtspecpaths, pluginPaths(p, name, ".spec")...) 41 txtspecpaths = append(txtspecpaths, pluginPaths(p, name, ".json")...) 42 } 43 44 for _, p := range txtspecpaths { 45 if _, err := os.Stat(p); err == nil { 46 if strings.HasSuffix(p, ".json") { 47 return readPluginJSONInfo(name, p) 48 } 49 return readPluginInfo(name, p) 50 } 51 } 52 return nil, ErrNotFound 53 } 54 55 func readPluginInfo(name, path string) (*Plugin, error) { 56 content, err := ioutil.ReadFile(path) 57 if err != nil { 58 return nil, err 59 } 60 addr := strings.TrimSpace(string(content)) 61 62 u, err := url.Parse(addr) 63 if err != nil { 64 return nil, err 65 } 66 67 if len(u.Scheme) == 0 { 68 return nil, fmt.Errorf("Unknown protocol") 69 } 70 71 return newLocalPlugin(name, addr), nil 72 } 73 74 func readPluginJSONInfo(name, path string) (*Plugin, error) { 75 f, err := os.Open(path) 76 if err != nil { 77 return nil, err 78 } 79 defer f.Close() 80 81 var p Plugin 82 if err := json.NewDecoder(f).Decode(&p); err != nil { 83 return nil, err 84 } 85 p.Name = name 86 if len(p.TLSConfig.CAFile) == 0 { 87 p.TLSConfig.InsecureSkipVerify = true 88 } 89 90 return &p, nil 91 } 92 93 func pluginPaths(base, name, ext string) []string { 94 return []string{ 95 filepath.Join(base, name+ext), 96 filepath.Join(base, name, name+ext), 97 } 98 }