forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
node.go
322 lines (281 loc) · 11.2 KB
/
node.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
package kubernetes
import (
"fmt"
"net"
"os"
"os/exec"
"path/filepath"
"time"
dockerclient "github.com/fsouza/go-dockerclient"
"github.com/golang/glog"
kubeletapp "k8s.io/kubernetes/cmd/kubelet/app"
kapi "k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/client/record"
"k8s.io/kubernetes/pkg/kubelet/cadvisor"
"k8s.io/kubernetes/pkg/kubelet/cm"
"k8s.io/kubernetes/pkg/kubelet/dockertools"
proxy "k8s.io/kubernetes/pkg/proxy"
pconfig "k8s.io/kubernetes/pkg/proxy/config"
"k8s.io/kubernetes/pkg/proxy/iptables"
"k8s.io/kubernetes/pkg/proxy/userspace"
utildbus "k8s.io/kubernetes/pkg/util/dbus"
kexec "k8s.io/kubernetes/pkg/util/exec"
utiliptables "k8s.io/kubernetes/pkg/util/iptables"
cmdutil "github.com/openshift/origin/pkg/cmd/util"
dockerutil "github.com/openshift/origin/pkg/cmd/util/docker"
)
type commandExecutor interface {
LookPath(executable string) (string, error)
Run(command string, args ...string) error
}
type defaultCommandExecutor struct{}
func (ce defaultCommandExecutor) LookPath(executable string) (string, error) {
return exec.LookPath(executable)
}
func (ce defaultCommandExecutor) Run(command string, args ...string) error {
c := exec.Command(command, args...)
return c.Run()
}
const minimumDockerAPIVersionWithPullByID = "1.18"
// EnsureDocker attempts to connect to the Docker daemon defined by the helper,
// and if it is unable to it will print a warning.
func (c *NodeConfig) EnsureDocker(docker *dockerutil.Helper) {
dockerClient, dockerAddr := docker.GetClientOrExit()
if err := dockerClient.Ping(); err != nil {
c.HandleDockerError(fmt.Sprintf("Docker could not be reached at %s. Docker must be installed and running to start containers.\n%v", dockerAddr, err))
return
}
glog.Infof("Connecting to Docker at %s", dockerAddr)
env, err := dockerClient.Version()
if err != nil {
c.HandleDockerError(fmt.Sprintf("Unable to check for Docker server version.\n%v", err))
return
}
serverVersionString := env.Get("ApiVersion")
serverVersion, err := dockerclient.NewAPIVersion(serverVersionString)
if err != nil {
c.HandleDockerError(fmt.Sprintf("Unable to determine Docker server version from %q.\n%v", serverVersionString, err))
return
}
minimumPullByIDVersion, err := dockerclient.NewAPIVersion(minimumDockerAPIVersionWithPullByID)
if err != nil {
c.HandleDockerError(fmt.Sprintf("Unable to check for Docker server version.\n%v", err))
return
}
if serverVersion.LessThan(minimumPullByIDVersion) {
c.HandleDockerError(fmt.Sprintf("Docker 1.6 or later (server API version 1.18 or later) required."))
return
}
c.DockerClient = dockerClient
}
// HandleDockerError handles an an error from the docker daemon
func (c *NodeConfig) HandleDockerError(message string) {
if !c.AllowDisabledDocker {
glog.Fatalf("ERROR: %s", message)
}
glog.Errorf("WARNING: %s", message)
c.DockerClient = &dockertools.FakeDockerClient{VersionInfo: dockerclient.Env([]string{"ApiVersion=1.18"})}
}
// EnsureVolumeDir attempts to convert the provided volume directory argument to
// an absolute path and create the directory if it does not exist. Will exit if
// an error is encountered.
func (c *NodeConfig) EnsureVolumeDir() {
if volumeDir, err := c.initializeVolumeDir(&defaultCommandExecutor{}, c.VolumeDir); err != nil {
glog.Fatal(err)
} else {
c.VolumeDir = volumeDir
}
}
func (c *NodeConfig) initializeVolumeDir(ce commandExecutor, path string) (string, error) {
rootDirectory, err := filepath.Abs(path)
if err != nil {
return "", fmt.Errorf("Error converting volume directory to an absolute path: %v", err)
}
if _, err := os.Stat(rootDirectory); os.IsNotExist(err) {
if err := os.MkdirAll(rootDirectory, 0750); err != nil {
return "", fmt.Errorf("Couldn't create kubelet volume root directory '%s': %s", rootDirectory, err)
}
}
// always try to chcon, in case the volume dir existed prior to the node starting
if chconPath, err := ce.LookPath("chcon"); err != nil {
glog.V(2).Infof("Couldn't locate 'chcon' to set the kubelet volume root directory SELinux context: %s", err)
} else {
if err := ce.Run(chconPath, "-t", "svirt_sandbox_file_t", rootDirectory); err != nil {
glog.Warningf("Error running 'chcon' to set the kubelet volume root directory SELinux context: %s", err)
}
}
return rootDirectory, nil
}
// RunKubelet starts the Kubelet.
func (c *NodeConfig) RunKubelet() {
if c.KubeletConfig.ClusterDNS == nil {
if service, err := c.Client.Services(kapi.NamespaceDefault).Get("kubernetes"); err == nil {
if includesServicePort(service.Spec.Ports, 53, "dns") {
// Use master service if service includes "dns" port 53.
c.KubeletConfig.ClusterDNS = net.ParseIP(service.Spec.ClusterIP)
}
}
}
if c.KubeletConfig.ClusterDNS == nil {
if endpoint, err := c.Client.Endpoints(kapi.NamespaceDefault).Get("kubernetes"); err == nil {
if endpointIP, ok := firstEndpointIPWithNamedPort(endpoint, 53, "dns"); ok {
// Use first endpoint if endpoint includes "dns" port 53.
c.KubeletConfig.ClusterDNS = net.ParseIP(endpointIP)
} else if endpointIP, ok := firstEndpointIP(endpoint, 53); ok {
// Test and use first endpoint if endpoint includes any port 53.
if err := cmdutil.WaitForSuccessfulDial(false, "tcp", fmt.Sprintf("%s:%d", endpointIP, 53), 50*time.Millisecond, 0, 2); err == nil {
c.KubeletConfig.ClusterDNS = net.ParseIP(endpointIP)
}
}
}
}
c.KubeletConfig.DockerClient = c.DockerClient
// updated by NodeConfig.EnsureVolumeDir
c.KubeletConfig.RootDirectory = c.VolumeDir
// hook for overriding the cadvisor interface for integration tests
c.KubeletConfig.CAdvisorInterface = defaultCadvisorInterface
// hook for overriding the container manager interface for integration tests
c.KubeletConfig.ContainerManager = defaultContainerManagerInterface
go func() {
glog.Fatal(kubeletapp.Run(c.KubeletServer, c.KubeletConfig))
}()
}
// defaultCadvisorInterface holds the overridden default interface
// exists only to allow stubbing integration tests, should always be nil in production
var defaultCadvisorInterface cadvisor.Interface = nil
// SetFakeCadvisorInterfaceForIntegrationTest sets a fake cadvisor implementation to allow the node to run in integration tests
func SetFakeCadvisorInterfaceForIntegrationTest() {
defaultCadvisorInterface = &cadvisor.Fake{}
}
// defaultContainerManagerInterface holds the overridden default interface
// exists only to allow stubbing integration tests, should always be nil in production
var defaultContainerManagerInterface cm.ContainerManager = nil
// SetFakeContainerManagerInterfaceForIntegrationTest sets a fake container manager implementation to allow the node to run in integration tests
func SetFakeContainerManagerInterfaceForIntegrationTest() {
defaultContainerManagerInterface = cm.NewStubContainerManager()
}
func (c *NodeConfig) RunSDN() {
if c.SDNPlugin != nil {
if err := c.SDNPlugin.StartNode(c.MTU); err != nil {
glog.Fatalf("SDN Node failed: %v", err)
}
}
}
// RunProxy starts the proxy
func (c *NodeConfig) RunProxy() {
protocol := utiliptables.ProtocolIpv4
if c.ProxyConfig.BindAddress.To4() == nil {
protocol = utiliptables.ProtocolIpv6
}
eventBroadcaster := record.NewBroadcaster()
eventBroadcaster.StartRecordingToSink(c.Client.Events(""))
recorder := eventBroadcaster.NewRecorder(kapi.EventSource{Component: "kube-proxy", Host: c.KubeletConfig.NodeName})
exec := kexec.New()
dbus := utildbus.New()
iptInterface := utiliptables.New(exec, dbus, protocol)
var proxier proxy.ProxyProvider
var endpointsHandler pconfig.EndpointsConfigHandler
switch c.ProxyConfig.ProxyMode {
case "iptables":
glog.V(0).Info("Using iptables Proxier.")
proxierIptables, err := iptables.NewProxier(iptInterface, exec, c.ProxyConfig.IptablesSyncPeriod, c.ProxyConfig.MasqueradeAll)
if err != nil {
// This should be fatal, but that would break the integration tests
glog.Warningf("WARNING: Could not initialize Kubernetes Proxy. You must run this process as root to use the service proxy: %v", err)
return
}
proxier = proxierIptables
endpointsHandler = proxierIptables
// No turning back. Remove artifacts that might still exist from the userspace Proxier.
glog.V(0).Info("Tearing down userspace rules. Errors here are acceptable.")
userspace.CleanupLeftovers(iptInterface)
case "userspace":
glog.V(0).Info("Using userspace Proxier.")
loadBalancer := userspace.NewLoadBalancerRR()
endpointsHandler = loadBalancer
proxierUserspace, err := userspace.NewProxier(loadBalancer, c.ProxyConfig.BindAddress, iptInterface, c.ProxyConfig.PortRange, c.ProxyConfig.IptablesSyncPeriod, c.ProxyConfig.UDPIdleTimeout)
if err != nil {
// This should be fatal, but that would break the integration tests
glog.Warningf("WARNING: Could not initialize Kubernetes Proxy. You must run this process as root to use the service proxy: %v", err)
return
}
proxier = proxierUserspace
// Remove artifacts from the pure-iptables Proxier.
glog.V(0).Info("Tearing down pure-iptables proxy rules. Errors here are acceptable.")
iptables.CleanupLeftovers(iptInterface)
default:
glog.Fatalf("Unknown proxy mode %q", c.ProxyConfig.ProxyMode)
}
iptInterface.AddReloadFunc(proxier.Sync)
// Create configs (i.e. Watches for Services and Endpoints)
// Note: RegisterHandler() calls need to happen before creation of Sources because sources
// only notify on changes, and the initial update (on process start) may be lost if no handlers
// are registered yet.
serviceConfig := pconfig.NewServiceConfig()
serviceConfig.RegisterHandler(proxier)
endpointsConfig := pconfig.NewEndpointsConfig()
if c.FilteringEndpointsHandler == nil {
endpointsConfig.RegisterHandler(endpointsHandler)
} else {
c.FilteringEndpointsHandler.SetBaseEndpointsHandler(endpointsHandler)
endpointsConfig.RegisterHandler(c.FilteringEndpointsHandler)
}
pconfig.NewSourceAPI(
c.Client,
c.ProxyConfig.ConfigSyncPeriod,
serviceConfig.Channel("api"),
endpointsConfig.Channel("api"))
recorder.Eventf(c.ProxyConfig.NodeRef, kapi.EventTypeNormal, "Starting", "Starting kube-proxy.")
glog.Infof("Started Kubernetes Proxy on %s", c.ProxyConfig.BindAddress.String())
}
// TODO: more generic location
func includesServicePort(ports []kapi.ServicePort, port int, portName string) bool {
for _, p := range ports {
if p.Port == port && p.Name == portName {
return true
}
}
return false
}
// TODO: more generic location
func includesEndpointPort(ports []kapi.EndpointPort, port int) bool {
for _, p := range ports {
if p.Port == port {
return true
}
}
return false
}
// TODO: more generic location
func firstEndpointIP(endpoints *kapi.Endpoints, port int) (string, bool) {
for _, s := range endpoints.Subsets {
if !includesEndpointPort(s.Ports, port) {
continue
}
for _, a := range s.Addresses {
return a.IP, true
}
}
return "", false
}
// TODO: more generic location
func firstEndpointIPWithNamedPort(endpoints *kapi.Endpoints, port int, portName string) (string, bool) {
for _, s := range endpoints.Subsets {
if !includesNamedEndpointPort(s.Ports, port, portName) {
continue
}
for _, a := range s.Addresses {
return a.IP, true
}
}
return "", false
}
// TODO: more generic location
func includesNamedEndpointPort(ports []kapi.EndpointPort, port int, portName string) bool {
for _, p := range ports {
if p.Port == port && p.Name == portName {
return true
}
}
return false
}