forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
helper.go
230 lines (212 loc) · 6.82 KB
/
helper.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
package dockerhelper
import (
"bytes"
"errors"
"fmt"
"io"
"net"
"net/url"
"regexp"
"strconv"
"time"
"github.com/blang/semver"
dockerclient "github.com/docker/engine-api/client"
"github.com/docker/engine-api/types/registry"
docker "github.com/fsouza/go-dockerclient"
"github.com/golang/glog"
"golang.org/x/net/context"
"github.com/openshift/imagebuilder/imageprogress"
starterrors "github.com/openshift/origin/pkg/bootstrap/docker/errors"
)
const openShiftInsecureCIDR = "172.30.0.0/16"
// Helper provides utility functions to help with Docker
type Helper struct {
client *docker.Client
engineAPIClient *dockerclient.Client
}
// NewHelper creates a new Helper
func NewHelper(client *docker.Client, engineAPIClient *dockerclient.Client) *Helper {
return &Helper{
client: client,
engineAPIClient: engineAPIClient,
}
}
type RegistryConfig struct {
InsecureRegistryCIDRs []string
}
func hasCIDR(cidr string, listOfCIDRs []*registry.NetIPNet) bool {
glog.V(5).Infof("Looking for %q in %#v", cidr, listOfCIDRs)
for _, candidate := range listOfCIDRs {
candidateStr := (*net.IPNet)(candidate).String()
if candidateStr == cidr {
glog.V(5).Infof("Found %q", cidr)
return true
}
}
glog.V(5).Infof("Did not find %q", cidr)
return false
}
// HasInsecureRegistryArg checks whether the docker daemon is configured with
// the appropriate insecure registry argument
func (h *Helper) HasInsecureRegistryArg() (bool, error) {
glog.V(5).Infof("Retrieving Docker daemon info")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
if h.engineAPIClient == nil {
return false, fmt.Errorf("the Docker engine API client is not initialized")
}
info, err := h.engineAPIClient.Info(ctx)
defer cancel()
if err != nil {
glog.V(2).Infof("Could not retrieve Docker info: %v", err)
return false, err
}
glog.V(5).Infof("Docker daemon info: %#v", info)
registryConfig := info.RegistryConfig
if err != nil {
return false, err
}
return hasCIDR(openShiftInsecureCIDR, registryConfig.InsecureRegistryCIDRs), nil
}
var (
fedoraPackage = regexp.MustCompile("\\.fc[0-9_]*\\.")
rhelPackage = regexp.MustCompile("\\.el[0-9_]*\\.")
)
// Version returns the Docker version and whether it is a Red Hat distro version
func (h *Helper) Version() (*semver.Version, bool, error) {
glog.V(5).Infof("Retrieving Docker version")
env, err := h.client.Version()
if err != nil {
glog.V(2).Infof("Error retrieving version: %v", err)
return nil, false, err
}
glog.V(5).Infof("Docker version results: %#v", env)
versionStr := env.Get("Version")
if len(versionStr) == 0 {
return nil, false, errors.New("did not get a version")
}
glog.V(5).Infof("Version: %s", versionStr)
dockerVersion, err := semver.Parse(versionStr)
if err != nil {
glog.V(2).Infof("Error parsing Docker version %q", versionStr)
return nil, false, err
}
isRedHat := false
packageVersion := env.Get("PkgVersion")
if len(packageVersion) > 0 {
isRedHat = fedoraPackage.MatchString(packageVersion) || rhelPackage.MatchString(packageVersion)
}
return &dockerVersion, isRedHat, nil
}
// CheckAndPull checks whether a Docker image exists. If not, it pulls it.
func (h *Helper) CheckAndPull(image string, out io.Writer) error {
glog.V(5).Infof("Inspecting Docker image %q", image)
imageMeta, err := h.client.InspectImage(image)
if err == nil {
glog.V(5).Infof("Image %q found: %#v", image, imageMeta)
return nil
}
if err != docker.ErrNoSuchImage {
return starterrors.NewError("unexpected error inspecting image %s", image).WithCause(err)
}
glog.V(5).Infof("Image %q not found. Pulling", image)
fmt.Fprintf(out, "Pulling image %s\n", image)
logProgress := func(s string) {
fmt.Fprintf(out, "%s\n", s)
}
outputStream := imageprogress.NewPullWriter(logProgress)
if glog.V(5) {
outputStream = out
}
err = h.client.PullImage(docker.PullImageOptions{
Repository: image,
RawJSONStream: bool(!glog.V(5)),
OutputStream: outputStream,
}, docker.AuthConfiguration{})
if err != nil {
return starterrors.NewError("error pulling Docker image %s", image).WithCause(err)
}
fmt.Fprintf(out, "Image pull complete\n")
return nil
}
// GetContainerState returns whether a container exists and if it does whether it's running
func (h *Helper) GetContainerState(id string) (exists, running bool, err error) {
var container *docker.Container
glog.V(5).Infof("Inspecting docker container %q", id)
container, err = h.client.InspectContainer(id)
if err != nil {
if _, notFound := err.(*docker.NoSuchContainer); notFound {
glog.V(5).Infof("Container %q was not found", id)
err = nil
return
}
glog.V(5).Infof("An error occurred inspecting container %q: %v", id, err)
return
}
exists = true
running = container.State.Running
glog.V(5).Infof("Container inspect result: %#v", container)
glog.V(5).Infof("Container exists = %v, running = %v", exists, running)
return
}
// RemoveContainer removes the container with the given id
func (h *Helper) RemoveContainer(id string) error {
glog.V(5).Infof("Removing container %q", id)
err := h.client.RemoveContainer(docker.RemoveContainerOptions{
ID: id,
})
if err != nil {
return starterrors.NewError("cannot delete container %s", id).WithCause(err)
}
glog.V(5).Infof("Removed container %q", id)
return nil
}
// HostIP returns the IP of the Docker host if connecting via TCP
func (h *Helper) HostIP() string {
// By default, if the Docker client uses tcp, then use the Docker daemon's address
endpoint := h.client.Endpoint()
u, err := url.Parse(endpoint)
if err == nil && (u.Scheme == "tcp" || u.Scheme == "http" || u.Scheme == "https") {
glog.V(2).Infof("Using the Docker host %s for the server IP", endpoint)
if host, _, serr := net.SplitHostPort(u.Host); serr == nil {
return host
}
return u.Host
}
glog.V(5).Infof("Cannot use Docker endpoint (%s) because it is not using one of the following protocols: tcp, http, https", endpoint)
return ""
}
func (h *Helper) ContainerLog(container string, numLines int) string {
output := &bytes.Buffer{}
err := h.client.Logs(docker.LogsOptions{
Container: container,
Tail: strconv.Itoa(numLines),
OutputStream: output,
ErrorStream: output,
Stdout: true,
Stderr: true,
})
if err != nil {
glog.V(1).Infof("Error getting container %q log: %v", container, err)
}
return output.String()
}
func (h *Helper) StopAndRemoveContainer(container string) error {
err := h.client.StopContainer(container, 10)
if err != nil {
glog.V(2).Infof("Cannot stop container %s: %v", container, err)
}
return h.RemoveContainer(container)
}
func (h *Helper) ListContainerNames() ([]string, error) {
containers, err := h.client.ListContainers(docker.ListContainersOptions{All: true})
if err != nil {
return nil, err
}
names := []string{}
for _, c := range containers {
if len(c.Names) > 0 {
names = append(names, c.Names[0])
}
}
return names, nil
}