forked from hyperledger/fabric
/
dockercontroller.go
277 lines (241 loc) · 9.28 KB
/
dockercontroller.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
/*
Copyright IBM Corp. 2016 All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package dockercontroller
import (
"bytes"
"fmt"
"io"
"strings"
"github.com/fsouza/go-dockerclient"
"github.com/hyperledger/fabric/core/container/ccintf"
cutil "github.com/hyperledger/fabric/core/container/util"
"github.com/op/go-logging"
"github.com/spf13/viper"
"golang.org/x/net/context"
)
var (
dockerLogger = logging.MustGetLogger("dockercontroller")
hostConfig *docker.HostConfig
)
//DockerVM is a vm. It is identified by an image id
type DockerVM struct {
id string
}
func getDockerHostConfig() *docker.HostConfig {
if hostConfig != nil {
return hostConfig
}
dockerKey := func(key string) string {
return "vm.docker.hostConfig." + key
}
getInt64 := func(key string) int64 {
defer func() {
if err := recover(); err != nil {
dockerLogger.Warningf("load vm.docker.hostConfig.%s failed, error: %v", key, err)
}
}()
n := viper.GetInt(dockerKey(key))
return int64(n)
}
var logConfig docker.LogConfig
err := viper.UnmarshalKey(dockerKey("LogConfig"), &logConfig)
if err != nil {
dockerLogger.Warningf("load docker HostConfig.LogConfig failed, error: %s", err.Error())
}
networkMode := viper.GetString(dockerKey("NetworkMode"))
if networkMode == "" {
networkMode = "host"
}
dockerLogger.Debugf("docker container hostconfig NetworkMode: %s", networkMode)
hostConfig = &docker.HostConfig{
CapAdd: viper.GetStringSlice(dockerKey("CapAdd")),
CapDrop: viper.GetStringSlice(dockerKey("CapDrop")),
DNS: viper.GetStringSlice(dockerKey("Dns")),
DNSSearch: viper.GetStringSlice(dockerKey("DnsSearch")),
ExtraHosts: viper.GetStringSlice(dockerKey("ExtraHosts")),
NetworkMode: networkMode,
IpcMode: viper.GetString(dockerKey("IpcMode")),
PidMode: viper.GetString(dockerKey("PidMode")),
UTSMode: viper.GetString(dockerKey("UTSMode")),
LogConfig: logConfig,
ReadonlyRootfs: viper.GetBool(dockerKey("ReadonlyRootfs")),
SecurityOpt: viper.GetStringSlice(dockerKey("SecurityOpt")),
CgroupParent: viper.GetString(dockerKey("CgroupParent")),
Memory: getInt64("Memory"),
MemorySwap: getInt64("MemorySwap"),
MemorySwappiness: getInt64("MemorySwappiness"),
OOMKillDisable: viper.GetBool(dockerKey("OomKillDisable")),
CPUShares: getInt64("CpuShares"),
CPUSet: viper.GetString(dockerKey("Cpuset")),
CPUSetCPUs: viper.GetString(dockerKey("CpusetCPUs")),
CPUSetMEMs: viper.GetString(dockerKey("CpusetMEMs")),
CPUQuota: getInt64("CpuQuota"),
CPUPeriod: getInt64("CpuPeriod"),
BlkioWeight: getInt64("BlkioWeight"),
}
return hostConfig
}
func (vm *DockerVM) createContainer(ctxt context.Context, client *docker.Client, imageID string, containerID string, args []string, env []string, attachstdin bool, attachstdout bool) error {
config := docker.Config{Cmd: args, Image: imageID, Env: env, AttachStdin: attachstdin, AttachStdout: attachstdout}
copts := docker.CreateContainerOptions{Name: containerID, Config: &config, HostConfig: getDockerHostConfig()}
dockerLogger.Debugf("Create container: %s", containerID)
_, err := client.CreateContainer(copts)
if err != nil {
return err
}
dockerLogger.Debugf("Created container: %s", imageID)
return nil
}
func (vm *DockerVM) deployImage(client *docker.Client, ccid ccintf.CCID, args []string, env []string, attachstdin bool, attachstdout bool, reader io.Reader) error {
id, _ := vm.GetVMName(ccid)
outputbuf := bytes.NewBuffer(nil)
opts := docker.BuildImageOptions{
Name: id,
Pull: false,
InputStream: reader,
OutputStream: outputbuf,
}
if err := client.BuildImage(opts); err != nil {
dockerLogger.Errorf("Error building images: %s", err)
dockerLogger.Errorf("Image Output:\n********************\n%s\n********************", outputbuf.String())
return err
}
dockerLogger.Debugf("Created image: %s", id)
return nil
}
//Deploy use the reader containing targz to create a docker image
//for docker inputbuf is tar reader ready for use by docker.Client
//the stream from end client to peer could directly be this tar stream
//talk to docker daemon using docker Client and build the image
func (vm *DockerVM) Deploy(ctxt context.Context, ccid ccintf.CCID, args []string, env []string, attachstdin bool, attachstdout bool, reader io.Reader) error {
client, err := cutil.NewDockerClient()
switch err {
case nil:
if err = vm.deployImage(client, ccid, args, env, attachstdin, attachstdout, reader); err != nil {
return err
}
default:
return fmt.Errorf("Error creating docker client: %s", err)
}
return nil
}
//Start starts a container using a previously created docker image
func (vm *DockerVM) Start(ctxt context.Context, ccid ccintf.CCID, args []string, env []string, attachstdin bool, attachstdout bool, reader io.Reader) error {
imageID, _ := vm.GetVMName(ccid)
client, err := cutil.NewDockerClient()
if err != nil {
dockerLogger.Debugf("start - cannot create client %s", err)
return err
}
containerID := strings.Replace(imageID, ":", "_", -1)
//stop,force remove if necessary
dockerLogger.Debugf("Cleanup container %s", containerID)
vm.stopInternal(ctxt, client, containerID, 0, false, false)
dockerLogger.Debugf("Start container %s", containerID)
err = vm.createContainer(ctxt, client, imageID, containerID, args, env, attachstdin, attachstdout)
if err != nil {
//if image not found try to create image and retry
if err == docker.ErrNoSuchImage {
if reader != nil {
dockerLogger.Debugf("start-could not find image ...attempt to recreate image %s", err)
if err = vm.deployImage(client, ccid, args, env, attachstdin, attachstdout, reader); err != nil {
return err
}
dockerLogger.Debug("start-recreated image successfully")
if err = vm.createContainer(ctxt, client, imageID, containerID, args, env, attachstdin, attachstdout); err != nil {
dockerLogger.Errorf("start-could not recreate container post recreate image: %s", err)
return err
}
} else {
dockerLogger.Errorf("start-could not find image: %s", err)
return err
}
} else {
dockerLogger.Errorf("start-could not recreate container %s", err)
return err
}
}
// start container with HostConfig was deprecated since v1.10 and removed in v1.2
err = client.StartContainer(containerID, nil)
if err != nil {
dockerLogger.Errorf("start-could not start container %s", err)
return err
}
dockerLogger.Debugf("Started container %s", containerID)
return nil
}
//Stop stops a running chaincode
func (vm *DockerVM) Stop(ctxt context.Context, ccid ccintf.CCID, timeout uint, dontkill bool, dontremove bool) error {
id, _ := vm.GetVMName(ccid)
client, err := cutil.NewDockerClient()
if err != nil {
dockerLogger.Debugf("stop - cannot create client %s", err)
return err
}
id = strings.Replace(id, ":", "_", -1)
err = vm.stopInternal(ctxt, client, id, timeout, dontkill, dontremove)
return err
}
func (vm *DockerVM) stopInternal(ctxt context.Context, client *docker.Client, id string, timeout uint, dontkill bool, dontremove bool) error {
err := client.StopContainer(id, timeout)
if err != nil {
dockerLogger.Debugf("Stop container %s(%s)", id, err)
} else {
dockerLogger.Debugf("Stopped container %s", id)
}
if !dontkill {
err = client.KillContainer(docker.KillContainerOptions{ID: id})
if err != nil {
dockerLogger.Debugf("Kill container %s (%s)", id, err)
} else {
dockerLogger.Debugf("Killed container %s", id)
}
}
if !dontremove {
err = client.RemoveContainer(docker.RemoveContainerOptions{ID: id, Force: true})
if err != nil {
dockerLogger.Debugf("Remove container %s (%s)", id, err)
} else {
dockerLogger.Debugf("Removed container %s", id)
}
}
return err
}
//Destroy destroys an image
func (vm *DockerVM) Destroy(ctxt context.Context, ccid ccintf.CCID, force bool, noprune bool) error {
id, _ := vm.GetVMName(ccid)
client, err := cutil.NewDockerClient()
if err != nil {
dockerLogger.Errorf("destroy-cannot create client %s", err)
return err
}
id = strings.Replace(id, ":", "_", -1)
err = client.RemoveImageExtended(id, docker.RemoveImageOptions{Force: force, NoPrune: noprune})
if err != nil {
dockerLogger.Errorf("error while destroying image: %s", err)
} else {
dockerLogger.Debug("Destroyed image %s", id)
}
return err
}
//GetVMName generates the docker image from peer information given the hashcode. This is needed to
//keep image name's unique in a single host, multi-peer environment (such as a development environment)
func (vm *DockerVM) GetVMName(ccid ccintf.CCID) (string, error) {
if ccid.NetworkID != "" {
return fmt.Sprintf("%s-%s-%s", ccid.NetworkID, ccid.PeerID, ccid.ChaincodeSpec.ChaincodeID.Name), nil
} else if ccid.PeerID != "" {
return fmt.Sprintf("%s-%s", ccid.PeerID, ccid.ChaincodeSpec.ChaincodeID.Name), nil
} else {
return ccid.ChaincodeSpec.ChaincodeID.Name, nil
}
}