From 2281ce7e98ec983514450c33c0ef1d90262c3b4f Mon Sep 17 00:00:00 2001
From: allencloud <allen.sun@daocloud.io>
Date: Mon, 27 Jun 2016 23:41:53 +0800
Subject: [PATCH] add err handling, close fd

Signed-off-by: allencloud <allen.sun@daocloud.io>
---
 plugin/backend.go           |  5 +++++
 plugin/distribution/pull.go |  1 +
 plugin/distribution/push.go |  1 +
 plugin/manager.go           | 12 +++++++++---
 4 files changed, 16 insertions(+), 3 deletions(-)

diff --git a/plugin/backend.go b/plugin/backend.go
index 8dcca58cb3..ada623950b 100644
--- a/plugin/backend.go
+++ b/plugin/backend.go
@@ -101,11 +101,16 @@ func (pm *Manager) List() ([]types.Plugin, error) {
 // Push pushes a plugin to the store.
 func (pm *Manager) Push(name string, metaHeader http.Header, authConfig *types.AuthConfig) error {
 	p, err := pm.get(name)
+	if err != nil {
+		return err
+	}
 	dest := filepath.Join(pm.libRoot, p.P.ID)
 	config, err := os.Open(filepath.Join(dest, "manifest.json"))
 	if err != nil {
 		return err
 	}
+	defer config.Close()
+
 	rootfs, err := archive.Tar(filepath.Join(dest, "rootfs"), archive.Gzip)
 	if err != nil {
 		return err
diff --git a/plugin/distribution/pull.go b/plugin/distribution/pull.go
index 5dcc907fbe..61971b3ee6 100644
--- a/plugin/distribution/pull.go
+++ b/plugin/distribution/pull.go
@@ -191,6 +191,7 @@ func WritePullData(pd PullData, dest string, extract bool) error {
 		if !extract {
 			f, err := os.Create(filepath.Join(dest, fmt.Sprintf("layer%d.tar", i)))
 			if err != nil {
+				l.Close()
 				return err
 			}
 			io.Copy(f, l)
diff --git a/plugin/distribution/push.go b/plugin/distribution/push.go
index 9cd400a70e..45deea83bb 100644
--- a/plugin/distribution/push.go
+++ b/plugin/distribution/push.go
@@ -74,6 +74,7 @@ func Push(name string, rs registry.Service, metaHeader http.Header, authConfig *
 		r := io.TeeReader(f, h)
 		_, err = io.Copy(bw, r)
 		if err != nil {
+			f.Close()
 			logrus.Debugf("Error in io.Copy: %v", err)
 			return "", err
 		}
diff --git a/plugin/manager.go b/plugin/manager.go
index 33887ce7de..267ea2e4c0 100644
--- a/plugin/manager.go
+++ b/plugin/manager.go
@@ -155,12 +155,18 @@ func Handle(capability string, callback func(string, *plugins.Client)) {
 
 func (pm *Manager) get(name string) (*plugin, error) {
 	pm.RLock()
+	defer pm.RUnlock()
+
 	id, nameOk := pm.nameToID[name]
-	p, idOk := pm.plugins[id]
-	pm.RUnlock()
-	if !nameOk || !idOk {
+	if !nameOk {
 		return nil, ErrNotFound(name)
 	}
+
+	p, idOk := pm.plugins[id]
+	if !idOk {
+		return nil, ErrNotFound(name)
+	}
+
 	return p, nil
 }