Signed-off-by: Lantao Liu <lantaol@google.com>
This commit is contained in:
Lantao Liu 2019-01-02 10:50:25 -08:00
parent 6ba92a7921
commit b55c9c6c35
105 changed files with 6095 additions and 5218 deletions

View File

@ -43,7 +43,7 @@ github.com/google/go-cmp v0.1.0
go.etcd.io/bbolt v1.3.1-etcd.8 go.etcd.io/bbolt v1.3.1-etcd.8
# cri dependencies # cri dependencies
github.com/containerd/cri f913714917d2456d7e65a0be84962b1ce8acb487 # release/1.2 branch github.com/containerd/cri 4b4b2abb2eb19ad6913a6c5d2a6869a0a43a3fc1 # master
github.com/containerd/go-cni 40bcf8ec8acd7372be1d77031d585d5d8e561c90 github.com/containerd/go-cni 40bcf8ec8acd7372be1d77031d585d5d8e561c90
github.com/blang/semver v3.1.0 github.com/blang/semver v3.1.0
github.com/containernetworking/cni v0.6.0 github.com/containernetworking/cni v0.6.0
@ -53,8 +53,6 @@ github.com/docker/distribution b38e5838b7b2f2ad48e06ec4b500011976080621
github.com/docker/docker 86f080cff0914e9694068ed78d503701667c4c00 github.com/docker/docker 86f080cff0914e9694068ed78d503701667c4c00
github.com/docker/spdystream 449fdfce4d962303d702fec724ef0ad181c92528 github.com/docker/spdystream 449fdfce4d962303d702fec724ef0ad181c92528
github.com/emicklei/go-restful v2.2.1 github.com/emicklei/go-restful v2.2.1
github.com/ghodss/yaml v1.0.0
github.com/golang/glog 44145f04b68cf362d9c4df2182967c2275eaefed
github.com/google/gofuzz 44d81051d367757e1c7c6a5a86423ece9afcf63c github.com/google/gofuzz 44d81051d367757e1c7c6a5a86423ece9afcf63c
github.com/hashicorp/errwrap 7554cd9344cec97297fa6649b055a8c98c2a1e55 github.com/hashicorp/errwrap 7554cd9344cec97297fa6649b055a8c98c2a1e55
github.com/hashicorp/go-multierror ed905158d87462226a13fe39ddf685ea65f1c11f github.com/hashicorp/go-multierror ed905158d87462226a13fe39ddf685ea65f1c11f
@ -73,12 +71,14 @@ golang.org/x/oauth2 a6bd8cefa1811bd24b86f8902872e4e8225f74c4
golang.org/x/time f51c12702a4d776e4c1fa9b0fabab841babae631 golang.org/x/time f51c12702a4d776e4c1fa9b0fabab841babae631
gopkg.in/inf.v0 3887ee99ecf07df5b447e9b00d9c0b2adaa9f3e4 gopkg.in/inf.v0 3887ee99ecf07df5b447e9b00d9c0b2adaa9f3e4
gopkg.in/yaml.v2 v2.2.1 gopkg.in/yaml.v2 v2.2.1
k8s.io/api kubernetes-1.12.0 k8s.io/api kubernetes-1.13.0
k8s.io/apimachinery kubernetes-1.12.0 k8s.io/apimachinery kubernetes-1.13.0
k8s.io/apiserver kubernetes-1.12.0 k8s.io/apiserver kubernetes-1.13.0
k8s.io/client-go kubernetes-1.12.0 k8s.io/client-go kubernetes-1.13.0
k8s.io/kubernetes v1.12.0 k8s.io/klog 8139d8cb77af419532b33dfa7dd09fbc5f1d344f
k8s.io/utils cd34563cd63c2bd7c6fe88a73c4dcf34ed8a67cb k8s.io/kubernetes v1.13.0
k8s.io/utils 0d26856f57b32ec3398579285e5c8a2bfe8c5243
sigs.k8s.io/yaml v1.1.0
# zfs dependencies # zfs dependencies
github.com/containerd/zfs 9f6ef3b1fe5144bd91fe5855b4eba81bc0d17d03 github.com/containerd/zfs 9f6ef3b1fe5144bd91fe5855b4eba81bc0d17d03

View File

@ -1,7 +1,7 @@
# cri # cri
<p align="center"> <p align="center">
<img src="https://kubernetes.io/images/favicon.png" width="50" height="50"> <img src="https://kubernetes.io/images/favicon.png" width="50" height="50">
<img src="https://containerd.io/img/containerd-dark.png" width="200" > <img src="https://containerd.io/img/logos/icon/black/containerd-icon-black.png" width="50" >
</p> </p>
*Note: The standalone `cri-containerd` binary is end-of-life. `cri-containerd` is *Note: The standalone `cri-containerd` binary is end-of-life. `cri-containerd` is
@ -36,6 +36,7 @@ See [test dashboard](https://k8s-testgrid.appspot.com/sig-node-containerd)
| v1.0.0-alpha.x | | 1.7, 1.8 | v1alpha1 | | v1.0.0-alpha.x | | 1.7, 1.8 | v1alpha1 |
| v1.0.0-beta.x | | 1.9 | v1alpha1 | | v1.0.0-beta.x | | 1.9 | v1alpha1 |
| End-Of-Life | v1.1 | 1.10+ | v1alpha2 | | End-Of-Life | v1.1 | 1.10+ | v1alpha2 |
| | v1.2 | 1.10+ | v1alpha2 |
| | HEAD | 1.10+ | v1alpha2 | | | HEAD | 1.10+ | v1alpha2 |
## Production Quality Cluster on GCE ## Production Quality Cluster on GCE
@ -149,7 +150,8 @@ implementation.
For sync communication we have a community slack with a #containerd channel that For sync communication we have a community slack with a #containerd channel that
everyone is welcome to join and chat about development. everyone is welcome to join and chat about development.
**Slack:** https://dockr.ly/community **Slack:** Catch us in the #containerd and #containerd-dev channels on dockercommunity.slack.com.
[Click here for an invite to docker community slack.](https://join.slack.com/t/dockercommunity/shared_invite/enQtNDY4MDc1Mzc0MzIwLTgxZDBlMmM4ZGEyNDc1N2FkMzlhODJkYmE1YTVkYjM1MDE3ZjAwZjBkOGFlOTJkZjRmZGYzNjYyY2M3ZTUxYzQ)
## Other Communications ## Other Communications
As this project is tightly coupled to CRI and CRI-Tools and they are Kubernetes As this project is tightly coupled to CRI and CRI-Tools and they are Kubernetes

View File

@ -36,6 +36,7 @@ import (
imagespec "github.com/opencontainers/image-spec/specs-go/v1" imagespec "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"k8s.io/klog"
criconfig "github.com/containerd/cri/pkg/config" criconfig "github.com/containerd/cri/pkg/config"
"github.com/containerd/cri/pkg/constants" "github.com/containerd/cri/pkg/constants"
@ -175,16 +176,18 @@ func getServicesOpts(ic *plugin.InitContext) ([]containerd.ServicesOpt, error) {
// Set glog level. // Set glog level.
func setGLogLevel() error { func setGLogLevel() error {
l := logrus.GetLevel() l := logrus.GetLevel()
if err := flag.Set("logtostderr", "true"); err != nil { fs := flag.NewFlagSet("klog", flag.PanicOnError)
klog.InitFlags(fs)
if err := fs.Set("logtostderr", "true"); err != nil {
return err return err
} }
switch l { switch l {
case log.TraceLevel: case log.TraceLevel:
return flag.Set("v", "5") return fs.Set("v", "5")
case logrus.DebugLevel: case logrus.DebugLevel:
return flag.Set("v", "4") return fs.Set("v", "4")
case logrus.InfoLevel: case logrus.InfoLevel:
return flag.Set("v", "2") return fs.Set("v", "2")
// glog doesn't support following filters. Defaults to v=0. // glog doesn't support following filters. Defaults to v=0.
case logrus.WarnLevel: case logrus.WarnLevel:
case logrus.ErrorLevel: case logrus.ErrorLevel:

220
vendor/github.com/containerd/cri/pkg/netns/netns.go generated vendored Normal file
View File

@ -0,0 +1,220 @@
/*
Copyright 2018 The Containerd Authors.
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.
*/
// Copyright 2018 CNI authors
//
// 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 netns
import (
"crypto/rand"
"fmt"
"os"
"path"
"runtime"
"sync"
cnins "github.com/containernetworking/plugins/pkg/ns"
"github.com/docker/docker/pkg/symlink"
"github.com/pkg/errors"
"golang.org/x/sys/unix"
osinterface "github.com/containerd/cri/pkg/os"
)
const nsRunDir = "/var/run/netns"
// Some of the following functions are migrated from
// https://github.com/containernetworking/plugins/blob/master/pkg/testutils/netns_linux.go
// newNS creates a new persistent (bind-mounted) network namespace and returns the
// path to the network namespace.
func newNS() (nsPath string, err error) {
b := make([]byte, 16)
if _, err := rand.Reader.Read(b); err != nil {
return "", errors.Wrap(err, "failed to generate random netns name")
}
// Create the directory for mounting network namespaces
// This needs to be a shared mountpoint in case it is mounted in to
// other namespaces (containers)
if err := os.MkdirAll(nsRunDir, 0755); err != nil {
return "", err
}
// create an empty file at the mount point
nsName := fmt.Sprintf("cni-%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
nsPath = path.Join(nsRunDir, nsName)
mountPointFd, err := os.Create(nsPath)
if err != nil {
return "", err
}
mountPointFd.Close()
defer func() {
// Ensure the mount point is cleaned up on errors
if err != nil {
os.RemoveAll(nsPath) // nolint: errcheck
}
}()
var wg sync.WaitGroup
wg.Add(1)
// do namespace work in a dedicated goroutine, so that we can safely
// Lock/Unlock OSThread without upsetting the lock/unlock state of
// the caller of this function
go (func() {
defer wg.Done()
runtime.LockOSThread()
// Don't unlock. By not unlocking, golang will kill the OS thread when the
// goroutine is done (for go1.10+)
var origNS cnins.NetNS
origNS, err = cnins.GetNS(getCurrentThreadNetNSPath())
if err != nil {
return
}
defer origNS.Close()
// create a new netns on the current thread
err = unix.Unshare(unix.CLONE_NEWNET)
if err != nil {
return
}
// Put this thread back to the orig ns, since it might get reused (pre go1.10)
defer origNS.Set() // nolint: errcheck
// bind mount the netns from the current thread (from /proc) onto the
// mount point. This causes the namespace to persist, even when there
// are no threads in the ns.
err = unix.Mount(getCurrentThreadNetNSPath(), nsPath, "none", unix.MS_BIND, "")
if err != nil {
err = errors.Wrapf(err, "failed to bind mount ns at %s", nsPath)
}
})()
wg.Wait()
if err != nil {
return "", errors.Wrap(err, "failed to create namespace")
}
return nsPath, nil
}
// unmountNS unmounts the NS held by the netns object. unmountNS is idempotent.
func unmountNS(path string) error {
if _, err := os.Stat(path); err != nil {
if os.IsNotExist(err) {
return nil
}
return errors.Wrap(err, "failed to stat netns")
}
path, err := symlink.FollowSymlinkInScope(path, "/")
if err != nil {
return errors.Wrap(err, "failed to follow symlink")
}
if err := osinterface.Unmount(path); err != nil && !os.IsNotExist(err) {
return errors.Wrap(err, "failed to umount netns")
}
if err := os.RemoveAll(path); err != nil {
return errors.Wrap(err, "failed to remove netns")
}
return nil
}
// getCurrentThreadNetNSPath copied from pkg/ns
func getCurrentThreadNetNSPath() string {
// /proc/self/ns/net returns the namespace of the main thread, not
// of whatever thread this goroutine is running on. Make sure we
// use the thread's net namespace since the thread is switching around
return fmt.Sprintf("/proc/%d/task/%d/ns/net", os.Getpid(), unix.Gettid())
}
// NetNS holds network namespace.
type NetNS struct {
path string
}
// NewNetNS creates a network namespace.
func NewNetNS() (*NetNS, error) {
path, err := newNS()
if err != nil {
return nil, errors.Wrap(err, "failed to setup netns")
}
return &NetNS{path: path}, nil
}
// LoadNetNS loads existing network namespace.
func LoadNetNS(path string) *NetNS {
return &NetNS{path: path}
}
// Remove removes network namepace. Remove is idempotent, meaning it might
// be invoked multiple times and provides consistent result.
func (n *NetNS) Remove() error {
return unmountNS(n.path)
}
// Closed checks whether the network namespace has been closed.
func (n *NetNS) Closed() (bool, error) {
ns, err := cnins.GetNS(n.path)
if err != nil {
if _, ok := err.(cnins.NSPathNotExistErr); ok {
// The network namespace has already been removed.
return true, nil
}
if _, ok := err.(cnins.NSPathNotNSErr); ok {
// The network namespace is not mounted, remove it.
if err := os.RemoveAll(n.path); err != nil {
return false, errors.Wrap(err, "remove netns")
}
return true, nil
}
return false, errors.Wrap(err, "get netns fd")
}
if err := ns.Close(); err != nil {
return false, errors.Wrap(err, "close netns fd")
}
return false, nil
}
// GetPath returns network namespace path for sandbox container
func (n *NetNS) GetPath() string {
return n.path
}
// Do runs a function in the network namespace.
func (n *NetNS) Do(f func(cnins.NetNS) error) error {
ns, err := cnins.GetNS(n.path)
if err != nil {
return errors.Wrap(err, "get netns fd")
}
defer ns.Close() // nolint: errcheck
return ns.Do(f)
}

View File

@ -187,6 +187,7 @@ func (c *criService) CreateContainer(ctx context.Context, r *runtime.CreateConta
opts = append(opts, customopts.WithVolumes(mountMap)) opts = append(opts, customopts.WithVolumes(mountMap))
} }
meta.ImageRef = image.ID meta.ImageRef = image.ID
meta.StopSignal = image.ImageSpec.Config.StopSignal
// Get container log path. // Get container log path.
if config.GetLogPath() != "" { if config.GetLogPath() != "" {

View File

@ -24,6 +24,7 @@ import (
"golang.org/x/net/context" "golang.org/x/net/context"
runtime "k8s.io/kubernetes/pkg/kubelet/apis/cri/runtime/v1alpha2" runtime "k8s.io/kubernetes/pkg/kubelet/apis/cri/runtime/v1alpha2"
"github.com/containerd/cri/pkg/store"
containerstore "github.com/containerd/cri/pkg/store/container" containerstore "github.com/containerd/cri/pkg/store/container"
) )
@ -43,8 +44,10 @@ func (c *criService) ContainerStatus(ctx context.Context, r *runtime.ContainerSt
imageRef := container.ImageRef imageRef := container.ImageRef
image, err := c.imageStore.Get(imageRef) image, err := c.imageStore.Get(imageRef)
if err != nil { if err != nil {
if err != store.ErrNotExist {
return nil, errors.Wrapf(err, "failed to get image %q", imageRef) return nil, errors.Wrapf(err, "failed to get image %q", imageRef)
} }
} else {
repoTags, repoDigests := parseImageReferences(image.References) repoTags, repoDigests := parseImageReferences(image.References)
if len(repoTags) > 0 { if len(repoTags) > 0 {
// Based on current behavior of dockershim, this field should be // Based on current behavior of dockershim, this field should be
@ -55,6 +58,7 @@ func (c *criService) ContainerStatus(ctx context.Context, r *runtime.ContainerSt
// Based on the CRI definition, this field will be consumed by user. // Based on the CRI definition, this field will be consumed by user.
imageRef = repoDigests[0] imageRef = repoDigests[0]
} }
}
status := toCRIContainerStatus(container, spec, imageRef) status := toCRIContainerStatus(container, spec, imageRef)
info, err := toCRIContainerInfo(ctx, container, r.GetVerbose()) info, err := toCRIContainerInfo(ctx, container, r.GetVerbose())
if err != nil { if err != nil {

View File

@ -19,7 +19,6 @@ package server
import ( import (
"time" "time"
"github.com/containerd/containerd"
"github.com/containerd/containerd/errdefs" "github.com/containerd/containerd/errdefs"
"github.com/docker/docker/pkg/signal" "github.com/docker/docker/pkg/signal"
"github.com/pkg/errors" "github.com/pkg/errors"
@ -28,6 +27,7 @@ import (
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
runtime "k8s.io/kubernetes/pkg/kubelet/apis/cri/runtime/v1alpha2" runtime "k8s.io/kubernetes/pkg/kubelet/apis/cri/runtime/v1alpha2"
"github.com/containerd/cri/pkg/store"
containerstore "github.com/containerd/cri/pkg/store/container" containerstore "github.com/containerd/cri/pkg/store/container"
) )
@ -77,24 +77,36 @@ func (c *criService) stopContainer(ctx context.Context, container containerstore
// We only need to kill the task. The event handler will Delete the // We only need to kill the task. The event handler will Delete the
// task from containerd after it handles the Exited event. // task from containerd after it handles the Exited event.
if timeout > 0 { if timeout > 0 {
stopSignal := unix.SIGTERM stopSignal := "SIGTERM"
if container.StopSignal != "" {
stopSignal = container.StopSignal
} else {
// The image may have been deleted, and the `StopSignal` field is
// just introduced to handle that.
// However, for containers created before the `StopSignal` field is
// introduced, still try to get the stop signal from the image config.
// If the image has been deleted, logging an error and using the
// default SIGTERM is still better than returning error and leaving
// the container unstoppable. (See issue #990)
// TODO(random-liu): Remove this logic when containerd 1.2 is deprecated.
image, err := c.imageStore.Get(container.ImageRef) image, err := c.imageStore.Get(container.ImageRef)
if err != nil { if err != nil {
// NOTE(random-liu): It's possible that the container is stopped, if err != store.ErrNotExist {
// deleted and image is garbage collected before this point. However, return errors.Wrapf(err, "failed to get image %q", container.ImageRef)
// the chance is really slim, even it happens, it's still fine to return
// an error here.
return errors.Wrapf(err, "failed to get image metadata %q", container.ImageRef)
} }
logrus.Warningf("Image %q not found, stop container with signal %q", container.ImageRef, stopSignal)
} else {
if image.ImageSpec.Config.StopSignal != "" { if image.ImageSpec.Config.StopSignal != "" {
stopSignal, err = signal.ParseSignal(image.ImageSpec.Config.StopSignal) stopSignal = image.ImageSpec.Config.StopSignal
}
}
}
sig, err := signal.ParseSignal(stopSignal)
if err != nil { if err != nil {
return errors.Wrapf(err, "failed to parse stop signal %q", return errors.Wrapf(err, "failed to parse stop signal %q", stopSignal)
image.ImageSpec.Config.StopSignal)
} }
} logrus.Infof("Stop container %q with signal %v", id, sig)
logrus.Infof("Stop container %q with signal %v", id, stopSignal) if err = task.Kill(ctx, sig); err != nil && !errdefs.IsNotFound(err) {
if err = task.Kill(ctx, stopSignal); err != nil && !errdefs.IsNotFound(err) {
return errors.Wrapf(err, "failed to stop container %q", id) return errors.Wrapf(err, "failed to stop container %q", id)
} }
@ -105,7 +117,7 @@ func (c *criService) stopContainer(ctx context.Context, container containerstore
} }
logrus.Infof("Kill container %q", id) logrus.Infof("Kill container %q", id)
if err = task.Kill(ctx, unix.SIGKILL, containerd.WithKillAll); err != nil && !errdefs.IsNotFound(err) { if err = task.Kill(ctx, unix.SIGKILL); err != nil && !errdefs.IsNotFound(err) {
return errors.Wrapf(err, "failed to kill container %q", id) return errors.Wrapf(err, "failed to kill container %q", id)
} }
@ -113,28 +125,7 @@ func (c *criService) stopContainer(ctx context.Context, container containerstore
if err = c.waitContainerStop(ctx, container, killContainerTimeout); err == nil { if err = c.waitContainerStop(ctx, container, killContainerTimeout); err == nil {
return nil return nil
} }
logrus.WithError(err).Errorf("An error occurs during waiting for container %q to be killed", id) return errors.Wrapf(err, "an error occurs during waiting for container %q to be killed", id)
// This is a fix for `runc`, and should not break other runtimes. With
// containerd.WithKillAll, `runc` will get all processes from the container
// cgroups, and kill them. However, sometimes the processes may be moved
// out from the container cgroup, e.g. users manually move them by mistake,
// or systemd.Delegate=true is not set.
// In these cases, we should try our best to do cleanup, kill the container
// without containerd.WithKillAll, so that runc can kill the container init
// process directly.
// NOTE(random-liu): If pid namespace is shared inside the pod, non-init processes
// of this container will be left running until the pause container is stopped.
logrus.Infof("Kill container %q init process", id)
if err = task.Kill(ctx, unix.SIGKILL); err != nil && !errdefs.IsNotFound(err) {
return errors.Wrapf(err, "failed to kill container %q init process", id)
}
// Wait for a fixed timeout until container stop is observed by event monitor.
if err = c.waitContainerStop(ctx, container, killContainerTimeout); err == nil {
return nil
}
return errors.Wrapf(err, "an error occurs during waiting for container %q init process to be killed", id)
} }
// waitContainerStop waits for container to be stopped until timeout exceeds or context is cancelled. // waitContainerStop waits for container to be stopped until timeout exceeds or context is cancelled.

View File

@ -20,6 +20,7 @@ import (
"sync" "sync"
"time" "time"
"github.com/containerd/containerd"
eventtypes "github.com/containerd/containerd/api/events" eventtypes "github.com/containerd/containerd/api/events"
containerdio "github.com/containerd/containerd/cio" containerdio "github.com/containerd/containerd/cio"
"github.com/containerd/containerd/errdefs" "github.com/containerd/containerd/errdefs"
@ -31,6 +32,7 @@ import (
"golang.org/x/net/context" "golang.org/x/net/context"
"k8s.io/apimachinery/pkg/util/clock" "k8s.io/apimachinery/pkg/util/clock"
"github.com/containerd/cri/pkg/constants"
ctrdutil "github.com/containerd/cri/pkg/containerd/util" ctrdutil "github.com/containerd/cri/pkg/containerd/util"
"github.com/containerd/cri/pkg/store" "github.com/containerd/cri/pkg/store"
containerstore "github.com/containerd/cri/pkg/store/container" containerstore "github.com/containerd/cri/pkg/store/container"
@ -82,7 +84,6 @@ type backOffQueue struct {
// Create new event monitor. New event monitor will start subscribing containerd event. All events // Create new event monitor. New event monitor will start subscribing containerd event. All events
// happen after it should be monitored. // happen after it should be monitored.
func newEventMonitor(c *criService) *eventMonitor { func newEventMonitor(c *criService) *eventMonitor {
// event subscribe doesn't need namespace.
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
return &eventMonitor{ return &eventMonitor{
c: c, c: c,
@ -94,6 +95,8 @@ func newEventMonitor(c *criService) *eventMonitor {
// subscribe starts to subscribe containerd events. // subscribe starts to subscribe containerd events.
func (em *eventMonitor) subscribe(subscriber events.Subscriber) { func (em *eventMonitor) subscribe(subscriber events.Subscriber) {
// note: filters are any match, if you want any match but not in namespace foo
// then you have to manually filter namespace foo
filters := []string{ filters := []string{
`topic=="/tasks/exit"`, `topic=="/tasks/exit"`,
`topic=="/tasks/oom"`, `topic=="/tasks/oom"`,
@ -141,6 +144,10 @@ func (em *eventMonitor) start() <-chan error {
select { select {
case e := <-em.ch: case e := <-em.ch:
logrus.Debugf("Received containerd event timestamp - %v, namespace - %q, topic - %q", e.Timestamp, e.Namespace, e.Topic) logrus.Debugf("Received containerd event timestamp - %v, namespace - %q, topic - %q", e.Timestamp, e.Namespace, e.Topic)
if e.Namespace != constants.K8sContainerdNamespace {
logrus.Debugf("Ignoring events in namespace - %q", e.Namespace)
break
}
id, evt, err := convertEvent(e.Event) id, evt, err := convertEvent(e.Event)
if err != nil { if err != nil {
logrus.WithError(err).Errorf("Failed to convert event %+v", e) logrus.WithError(err).Errorf("Failed to convert event %+v", e)
@ -194,14 +201,11 @@ func (em *eventMonitor) handleEvent(any interface{}) error {
defer cancel() defer cancel()
switch any.(type) { switch any.(type) {
// If containerd-shim exits unexpectedly, there will be no corresponding event.
// However, containerd could not retrieve container state in that case, so it's
// fine to leave out that case for now.
// TODO(random-liu): [P2] Handle containerd-shim exit.
case *eventtypes.TaskExit: case *eventtypes.TaskExit:
e := any.(*eventtypes.TaskExit) e := any.(*eventtypes.TaskExit)
logrus.Infof("TaskExit event %+v", e) logrus.Infof("TaskExit event %+v", e)
cntr, err := em.c.containerStore.Get(e.ContainerID) // Use ID instead of ContainerID to rule out TaskExit event for exec.
cntr, err := em.c.containerStore.Get(e.ID)
if err == nil { if err == nil {
if err := handleContainerExit(ctx, e, cntr); err != nil { if err := handleContainerExit(ctx, e, cntr); err != nil {
return errors.Wrap(err, "failed to handle container TaskExit event") return errors.Wrap(err, "failed to handle container TaskExit event")
@ -211,7 +215,7 @@ func (em *eventMonitor) handleEvent(any interface{}) error {
return errors.Wrap(err, "can't find container for TaskExit event") return errors.Wrap(err, "can't find container for TaskExit event")
} }
// Use GetAll to include sandbox in unknown state. // Use GetAll to include sandbox in unknown state.
sb, err := em.c.sandboxStore.GetAll(e.ContainerID) sb, err := em.c.sandboxStore.GetAll(e.ID)
if err == nil { if err == nil {
if err := handleSandboxExit(ctx, e, sb); err != nil { if err := handleSandboxExit(ctx, e, sb); err != nil {
return errors.Wrap(err, "failed to handle sandbox TaskExit event") return errors.Wrap(err, "failed to handle sandbox TaskExit event")
@ -224,17 +228,12 @@ func (em *eventMonitor) handleEvent(any interface{}) error {
case *eventtypes.TaskOOM: case *eventtypes.TaskOOM:
e := any.(*eventtypes.TaskOOM) e := any.(*eventtypes.TaskOOM)
logrus.Infof("TaskOOM event %+v", e) logrus.Infof("TaskOOM event %+v", e)
// For TaskOOM, we only care which container it belongs to.
cntr, err := em.c.containerStore.Get(e.ContainerID) cntr, err := em.c.containerStore.Get(e.ContainerID)
if err != nil { if err != nil {
if err != store.ErrNotExist { if err != store.ErrNotExist {
return errors.Wrap(err, "can't find container for TaskOOM event") return errors.Wrap(err, "can't find container for TaskOOM event")
} }
if _, err = em.c.sandboxStore.Get(e.ContainerID); err != nil {
if err != store.ErrNotExist {
return errors.Wrap(err, "can't find sandbox for TaskOOM event")
}
return nil
}
return nil return nil
} }
err = cntr.Status.UpdateSync(func(status containerstore.Status) (containerstore.Status, error) { err = cntr.Status.UpdateSync(func(status containerstore.Status) (containerstore.Status, error) {
@ -263,10 +262,6 @@ func (em *eventMonitor) handleEvent(any interface{}) error {
// handleContainerExit handles TaskExit event for container. // handleContainerExit handles TaskExit event for container.
func handleContainerExit(ctx context.Context, e *eventtypes.TaskExit, cntr containerstore.Container) error { func handleContainerExit(ctx context.Context, e *eventtypes.TaskExit, cntr containerstore.Container) error {
if e.Pid != cntr.Status.Get().Pid {
// Non-init process died, ignore the event.
return nil
}
// Attach container IO so that `Delete` could cleanup the stream properly. // Attach container IO so that `Delete` could cleanup the stream properly.
task, err := cntr.Container.Task(ctx, task, err := cntr.Container.Task(ctx,
func(*containerdio.FIFOSet) (containerdio.IO, error) { func(*containerdio.FIFOSet) (containerdio.IO, error) {
@ -279,7 +274,7 @@ func handleContainerExit(ctx context.Context, e *eventtypes.TaskExit, cntr conta
} }
} else { } else {
// TODO(random-liu): [P1] This may block the loop, we may want to spawn a worker // TODO(random-liu): [P1] This may block the loop, we may want to spawn a worker
if _, err = task.Delete(ctx); err != nil { if _, err = task.Delete(ctx, containerd.WithProcessKill); err != nil {
if !errdefs.IsNotFound(err) { if !errdefs.IsNotFound(err) {
return errors.Wrap(err, "failed to stop container") return errors.Wrap(err, "failed to stop container")
} }
@ -307,10 +302,6 @@ func handleContainerExit(ctx context.Context, e *eventtypes.TaskExit, cntr conta
// handleSandboxExit handles TaskExit event for sandbox. // handleSandboxExit handles TaskExit event for sandbox.
func handleSandboxExit(ctx context.Context, e *eventtypes.TaskExit, sb sandboxstore.Sandbox) error { func handleSandboxExit(ctx context.Context, e *eventtypes.TaskExit, sb sandboxstore.Sandbox) error {
if e.Pid != sb.Status.Get().Pid {
// Non-init process died, ignore the event.
return nil
}
// No stream attached to sandbox container. // No stream attached to sandbox container.
task, err := sb.Container.Task(ctx, nil) task, err := sb.Container.Task(ctx, nil)
if err != nil { if err != nil {
@ -319,7 +310,7 @@ func handleSandboxExit(ctx context.Context, e *eventtypes.TaskExit, sb sandboxst
} }
} else { } else {
// TODO(random-liu): [P1] This may block the loop, we may want to spawn a worker // TODO(random-liu): [P1] This may block the loop, we may want to spawn a worker
if _, err = task.Delete(ctx); err != nil { if _, err = task.Delete(ctx, containerd.WithProcessKill); err != nil {
if !errdefs.IsNotFound(err) { if !errdefs.IsNotFound(err) {
return errors.Wrap(err, "failed to stop sandbox") return errors.Wrap(err, "failed to stop sandbox")
} }

View File

@ -353,7 +353,7 @@ func checkSelinuxLevel(level string) (bool, error) {
matched, err := regexp.MatchString(`^s\d(-s\d)??(:c\d{1,4}((.c\d{1,4})?,c\d{1,4})*(.c\d{1,4})?(,c\d{1,4}(.c\d{1,4})?)*)?$`, level) matched, err := regexp.MatchString(`^s\d(-s\d)??(:c\d{1,4}((.c\d{1,4})?,c\d{1,4})*(.c\d{1,4})?(,c\d{1,4}(.c\d{1,4})?)*)?$`, level)
if err != nil || !matched { if err != nil || !matched {
return false, fmt.Errorf("the format of 'level' %q is not correct: %v", level, err) return false, errors.Wrapf(err, "the format of 'level' %q is not correct", level)
} }
return true, nil return true, nil
} }

View File

@ -61,11 +61,11 @@ import (
// if we saw an image without snapshots or with in-complete contents during startup, // if we saw an image without snapshots or with in-complete contents during startup,
// should we re-pull the image? Or should we remove the entry? // should we re-pull the image? Or should we remove the entry?
// //
// yanxuean: We cann't delete image directly, because we don't know if the image // yanxuean: We can't delete image directly, because we don't know if the image
// is pulled by us. There are resource leakage. // is pulled by us. There are resource leakage.
// //
// 2) Containerd suggests user to add entry before pulling the image. However if // 2) Containerd suggests user to add entry before pulling the image. However if
// an error occurrs during the pulling, should we remove the entry from metadata // an error occurs during the pulling, should we remove the entry from metadata
// store? Or should we leave it there until next startup (resource leakage)? // store? Or should we leave it there until next startup (resource leakage)?
// //
// 3) The cri plugin only exposes "READY" (successfully pulled and unpacked) images // 3) The cri plugin only exposes "READY" (successfully pulled and unpacked) images

View File

@ -299,7 +299,7 @@ func (in *instrumentedService) PullImage(ctx context.Context, r *runtime.PullIma
if err := in.checkInitialized(); err != nil { if err := in.checkInitialized(); err != nil {
return nil, err return nil, err
} }
logrus.Infof("PullImage %q with auth config %+v", r.GetImage().GetImage(), r.GetAuth()) logrus.Infof("PullImage %q", r.GetImage().GetImage())
defer func() { defer func() {
if err != nil { if err != nil {
logrus.WithError(err).Errorf("PullImage %q failed", r.GetImage().GetImage()) logrus.WithError(err).Errorf("PullImage %q failed", r.GetImage().GetImage())

View File

@ -34,6 +34,7 @@ import (
"golang.org/x/net/context" "golang.org/x/net/context"
runtime "k8s.io/kubernetes/pkg/kubelet/apis/cri/runtime/v1alpha2" runtime "k8s.io/kubernetes/pkg/kubelet/apis/cri/runtime/v1alpha2"
"github.com/containerd/cri/pkg/netns"
cio "github.com/containerd/cri/pkg/server/io" cio "github.com/containerd/cri/pkg/server/io"
containerstore "github.com/containerd/cri/pkg/store/container" containerstore "github.com/containerd/cri/pkg/store/container"
sandboxstore "github.com/containerd/cri/pkg/store/sandbox" sandboxstore "github.com/containerd/cri/pkg/store/sandbox"
@ -145,7 +146,7 @@ func (c *criService) recover(ctx context.Context) error {
// * ListContainerStats: Not in critical code path, a default timeout will // * ListContainerStats: Not in critical code path, a default timeout will
// be applied at CRI level. // be applied at CRI level.
// * Recovery logic: We should set a time for each container/sandbox recovery. // * Recovery logic: We should set a time for each container/sandbox recovery.
// * Event montior: We should set a timeout for each container/sandbox event handling. // * Event monitor: We should set a timeout for each container/sandbox event handling.
const loadContainerTimeout = 10 * time.Second const loadContainerTimeout = 10 * time.Second
// loadContainer loads container from containerd and status checkpoint. // loadContainer loads container from containerd and status checkpoint.
@ -394,14 +395,7 @@ func loadSandbox(ctx context.Context, cntr containerd.Container) (sandboxstore.S
// Don't need to load netns for host network sandbox. // Don't need to load netns for host network sandbox.
return sandbox, nil return sandbox, nil
} }
netNS, err := sandboxstore.LoadNetNS(meta.NetNSPath) sandbox.NetNS = netns.LoadNetNS(meta.NetNSPath)
if err != nil {
if err != sandboxstore.ErrClosedNetNS {
return sandbox, errors.Wrapf(err, "failed to load netns %q", meta.NetNSPath)
}
netNS = nil
}
sandbox.NetNS = netNS
// It doesn't matter whether task is running or not. If it is running, sandbox // It doesn't matter whether task is running or not. If it is running, sandbox
// status will be `READY`; if it is not running, sandbox status will be `NOT_READY`, // status will be `READY`; if it is not running, sandbox status will be `NOT_READY`,

View File

@ -59,10 +59,12 @@ func (c *criService) portForward(id string, port int32, stream io.ReadWriteClose
securityContext := s.Config.GetLinux().GetSecurityContext() securityContext := s.Config.GetLinux().GetSecurityContext()
hostNet := securityContext.GetNamespaceOptions().GetNetwork() == runtime.NamespaceMode_NODE hostNet := securityContext.GetNamespaceOptions().GetNetwork() == runtime.NamespaceMode_NODE
if !hostNet { if !hostNet {
if s.NetNS == nil || s.NetNS.Closed() { if closed, err := s.NetNS.Closed(); err != nil {
return errors.Wrapf(err, "failed to check netwok namespace closed for sandbox %q", id)
} else if closed {
return errors.Errorf("network namespace for sandbox %q is closed", id) return errors.Errorf("network namespace for sandbox %q is closed", id)
} }
netNSDo = s.NetNS.GetNs().Do netNSDo = s.NetNS.Do
netNSPath = s.NetNS.GetPath() netNSPath = s.NetNS.GetPath()
} else { } else {
// Run the function directly for host network. // Run the function directly for host network.

View File

@ -52,8 +52,13 @@ func (c *criService) RemovePodSandbox(ctx context.Context, r *runtime.RemovePodS
} }
// Return error if sandbox network namespace is not closed yet. // Return error if sandbox network namespace is not closed yet.
if sandbox.NetNS != nil && !sandbox.NetNS.Closed() { if sandbox.NetNS != nil {
return nil, errors.Errorf("sandbox network namespace %q is not fully closed", sandbox.NetNS.GetPath()) nsPath := sandbox.NetNS.GetPath()
if closed, err := sandbox.NetNS.Closed(); err != nil {
return nil, errors.Wrapf(err, "failed to check sandbox network namespace %q closed", nsPath)
} else if !closed {
return nil, errors.Errorf("sandbox network namespace %q is not fully closed", nsPath)
}
} }
// Remove all containers inside the sandbox. // Remove all containers inside the sandbox.

View File

@ -17,6 +17,7 @@ limitations under the License.
package server package server
import ( import (
"encoding/json"
"fmt" "fmt"
"os" "os"
"strings" "strings"
@ -40,6 +41,7 @@ import (
customopts "github.com/containerd/cri/pkg/containerd/opts" customopts "github.com/containerd/cri/pkg/containerd/opts"
ctrdutil "github.com/containerd/cri/pkg/containerd/util" ctrdutil "github.com/containerd/cri/pkg/containerd/util"
"github.com/containerd/cri/pkg/log" "github.com/containerd/cri/pkg/log"
"github.com/containerd/cri/pkg/netns"
sandboxstore "github.com/containerd/cri/pkg/store/sandbox" sandboxstore "github.com/containerd/cri/pkg/store/sandbox"
"github.com/containerd/cri/pkg/util" "github.com/containerd/cri/pkg/util"
) )
@ -88,6 +90,13 @@ func (c *criService) RunPodSandbox(ctx context.Context, r *runtime.RunPodSandbox
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "failed to get sandbox image %q", c.config.SandboxImage) return nil, errors.Wrapf(err, "failed to get sandbox image %q", c.config.SandboxImage)
} }
ociRuntime, err := c.getSandboxRuntime(config, r.GetRuntimeHandler())
if err != nil {
return nil, errors.Wrap(err, "failed to get sandbox runtime")
}
logrus.Debugf("Use OCI %+v for sandbox %q", ociRuntime, id)
securityContext := config.GetLinux().GetSecurityContext() securityContext := config.GetLinux().GetSecurityContext()
//Create Network Namespace if it is not in host network //Create Network Namespace if it is not in host network
hostNet := securityContext.GetNamespaceOptions().GetNetwork() == runtime.NamespaceMode_NODE hostNet := securityContext.GetNamespaceOptions().GetNetwork() == runtime.NamespaceMode_NODE
@ -96,7 +105,7 @@ func (c *criService) RunPodSandbox(ctx context.Context, r *runtime.RunPodSandbox
// handle. NetNSPath in sandbox metadata and NetNS is non empty only for non host network // handle. NetNSPath in sandbox metadata and NetNS is non empty only for non host network
// namespaces. If the pod is in host network namespace then both are empty and should not // namespaces. If the pod is in host network namespace then both are empty and should not
// be used. // be used.
sandbox.NetNS, err = sandboxstore.NewNetNS() sandbox.NetNS, err = netns.NewNetNS()
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "failed to create network namespace for sandbox %q", id) return nil, errors.Wrapf(err, "failed to create network namespace for sandbox %q", id)
} }
@ -117,7 +126,7 @@ func (c *criService) RunPodSandbox(ctx context.Context, r *runtime.RunPodSandbox
// In this case however caching the IP will add a subtle performance enhancement by avoiding // In this case however caching the IP will add a subtle performance enhancement by avoiding
// calls to network namespace of the pod to query the IP of the veth interface on every // calls to network namespace of the pod to query the IP of the veth interface on every
// SandboxStatus request. // SandboxStatus request.
sandbox.IP, err = c.setupPod(id, sandbox.NetNSPath, config) sandbox.IP, sandbox.CNIResult, err = c.setupPod(id, sandbox.NetNSPath, config)
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "failed to setup network for sandbox %q", id) return nil, errors.Wrapf(err, "failed to setup network for sandbox %q", id)
} }
@ -131,12 +140,6 @@ func (c *criService) RunPodSandbox(ctx context.Context, r *runtime.RunPodSandbox
}() }()
} }
ociRuntime, err := c.getSandboxRuntime(config, r.GetRuntimeHandler())
if err != nil {
return nil, errors.Wrap(err, "failed to get sandbox runtime")
}
logrus.Debugf("Use OCI %+v for sandbox %q", ociRuntime, id)
// Create sandbox container. // Create sandbox container.
spec, err := c.generateSandboxContainerSpec(id, config, &image.ImageSpec.Config, sandbox.NetNSPath) spec, err := c.generateSandboxContainerSpec(id, config, &image.ImageSpec.Config, sandbox.NetNSPath)
if err != nil { if err != nil {
@ -527,9 +530,9 @@ func (c *criService) unmountSandboxFiles(id string, config *runtime.PodSandboxCo
} }
// setupPod setups up the network for a pod // setupPod setups up the network for a pod
func (c *criService) setupPod(id string, path string, config *runtime.PodSandboxConfig) (string, error) { func (c *criService) setupPod(id string, path string, config *runtime.PodSandboxConfig) (string, *cni.CNIResult, error) {
if c.netPlugin == nil { if c.netPlugin == nil {
return "", errors.New("cni config not intialized") return "", nil, errors.New("cni config not initialized")
} }
labels := getPodCNILabels(id, config) labels := getPodCNILabels(id, config)
@ -538,17 +541,18 @@ func (c *criService) setupPod(id string, path string, config *runtime.PodSandbox
cni.WithLabels(labels), cni.WithLabels(labels),
cni.WithCapabilityPortMap(toCNIPortMappings(config.GetPortMappings()))) cni.WithCapabilityPortMap(toCNIPortMappings(config.GetPortMappings())))
if err != nil { if err != nil {
return "", err return "", nil, err
} }
logDebugCNIResult(id, result)
// Check if the default interface has IP config // Check if the default interface has IP config
if configs, ok := result.Interfaces[defaultIfName]; ok && len(configs.IPConfigs) > 0 { if configs, ok := result.Interfaces[defaultIfName]; ok && len(configs.IPConfigs) > 0 {
return selectPodIP(configs.IPConfigs), nil return selectPodIP(configs.IPConfigs), result, nil
} }
// If it comes here then the result was invalid so destroy the pod network and return error // If it comes here then the result was invalid so destroy the pod network and return error
if err := c.teardownPod(id, path, config); err != nil { if err := c.teardownPod(id, path, config); err != nil {
logrus.WithError(err).Errorf("Failed to destroy network for sandbox %q", id) logrus.WithError(err).Errorf("Failed to destroy network for sandbox %q", id)
} }
return "", errors.Errorf("failed to find network info for sandbox %q", id) return "", result, errors.Errorf("failed to find network info for sandbox %q", id)
} }
// toCNIPortMappings converts CRI port mappings to CNI. // toCNIPortMappings converts CRI port mappings to CNI.
@ -638,3 +642,15 @@ func (c *criService) getSandboxRuntime(config *runtime.PodSandboxConfig, runtime
} }
return handler, nil return handler, nil
} }
func logDebugCNIResult(sandboxID string, result *cni.CNIResult) {
if logrus.GetLevel() < logrus.DebugLevel {
return
}
cniResult, err := json.Marshal(result)
if err != nil {
logrus.WithError(err).Errorf("Failed to marshal CNI result for sandbox %q: %v", sandboxID, err)
return
}
logrus.Debugf("cni result for sandbox %q: %s", sandboxID, string(cniResult))
}

View File

@ -21,6 +21,7 @@ import (
"github.com/containerd/containerd" "github.com/containerd/containerd"
"github.com/containerd/containerd/errdefs" "github.com/containerd/containerd/errdefs"
cni "github.com/containerd/go-cni"
runtimespec "github.com/opencontainers/runtime-spec/specs-go" runtimespec "github.com/opencontainers/runtime-spec/specs-go"
"github.com/pkg/errors" "github.com/pkg/errors"
"golang.org/x/net/context" "golang.org/x/net/context"
@ -36,7 +37,10 @@ func (c *criService) PodSandboxStatus(ctx context.Context, r *runtime.PodSandbox
return nil, errors.Wrap(err, "an error occurred when try to find sandbox") return nil, errors.Wrap(err, "an error occurred when try to find sandbox")
} }
ip := c.getIP(sandbox) ip, err := c.getIP(sandbox)
if err != nil {
return nil, errors.Wrap(err, "failed to get sandbox ip")
}
status := toCRISandboxStatus(sandbox.Metadata, sandbox.Status.Get(), ip) status := toCRISandboxStatus(sandbox.Metadata, sandbox.Status.Get(), ip)
if !r.GetVerbose() { if !r.GetVerbose() {
return &runtime.PodSandboxStatusResponse{Status: status}, nil return &runtime.PodSandboxStatusResponse{Status: status}, nil
@ -54,21 +58,22 @@ func (c *criService) PodSandboxStatus(ctx context.Context, r *runtime.PodSandbox
}, nil }, nil
} }
func (c *criService) getIP(sandbox sandboxstore.Sandbox) string { func (c *criService) getIP(sandbox sandboxstore.Sandbox) (string, error) {
config := sandbox.Config config := sandbox.Config
if config.GetLinux().GetSecurityContext().GetNamespaceOptions().GetNetwork() == runtime.NamespaceMode_NODE { if config.GetLinux().GetSecurityContext().GetNamespaceOptions().GetNetwork() == runtime.NamespaceMode_NODE {
// For sandboxes using the node network we are not // For sandboxes using the node network we are not
// responsible for reporting the IP. // responsible for reporting the IP.
return "" return "", nil
} }
// The network namespace has been closed. if closed, err := sandbox.NetNS.Closed(); err != nil {
if sandbox.NetNS == nil || sandbox.NetNS.Closed() { return "", errors.Wrap(err, "check network namespace closed")
return "" } else if closed {
return "", nil
} }
return sandbox.IP return sandbox.IP, nil
} }
// toCRISandboxStatus converts sandbox metadata into CRI pod sandbox status. // toCRISandboxStatus converts sandbox metadata into CRI pod sandbox status.
@ -113,6 +118,7 @@ type SandboxInfo struct {
RuntimeOptions interface{} `json:"runtimeOptions"` RuntimeOptions interface{} `json:"runtimeOptions"`
Config *runtime.PodSandboxConfig `json:"config"` Config *runtime.PodSandboxConfig `json:"config"`
RuntimeSpec *runtimespec.Spec `json:"runtimeSpec"` RuntimeSpec *runtimespec.Spec `json:"runtimeSpec"`
CNIResult *cni.CNIResult `json:"cniResult"`
} }
// toCRISandboxInfo converts internal container object information to CRI sandbox status response info map. // toCRISandboxInfo converts internal container object information to CRI sandbox status response info map.
@ -138,6 +144,7 @@ func toCRISandboxInfo(ctx context.Context, sandbox sandboxstore.Sandbox) (map[st
RuntimeHandler: sandbox.RuntimeHandler, RuntimeHandler: sandbox.RuntimeHandler,
Status: string(processStatus), Status: string(processStatus),
Config: sandbox.Config, Config: sandbox.Config,
CNIResult: sandbox.CNIResult,
} }
if si.Status == "" { if si.Status == "" {
@ -146,9 +153,13 @@ func toCRISandboxInfo(ctx context.Context, sandbox sandboxstore.Sandbox) (map[st
si.Status = "deleted" si.Status = "deleted"
} }
if sandbox.NetNSPath != "" { if sandbox.NetNS != nil {
// Add network closed information if sandbox is not using host network. // Add network closed information if sandbox is not using host network.
si.NetNSClosed = (sandbox.NetNS == nil || sandbox.NetNS.Closed()) closed, err := sandbox.NetNS.Closed()
if err != nil {
return nil, errors.Wrap(err, "failed to check network namespace closed")
}
si.NetNSClosed = closed
} }
spec, err := container.Spec(ctx) spec, err := container.Spec(ctx)

View File

@ -19,7 +19,6 @@ package server
import ( import (
"time" "time"
"github.com/containerd/containerd"
"github.com/containerd/containerd/errdefs" "github.com/containerd/containerd/errdefs"
cni "github.com/containerd/go-cni" cni "github.com/containerd/go-cni"
"github.com/pkg/errors" "github.com/pkg/errors"
@ -43,9 +42,8 @@ func (c *criService) StopPodSandbox(ctx context.Context, r *runtime.StopPodSandb
id := sandbox.ID id := sandbox.ID
// Stop all containers inside the sandbox. This terminates the container forcibly, // Stop all containers inside the sandbox. This terminates the container forcibly,
// and container may still be so production should not rely on this behavior. // and container may still be created, so production should not rely on this behavior.
// TODO(random-liu): Delete the sandbox container before this after permanent network namespace // TODO(random-liu): Introduce a state in sandbox to avoid future container creation.
// is introduced, so that no container will be started after that.
containers := c.containerStore.List() containers := c.containerStore.List()
for _, container := range containers { for _, container := range containers {
if container.SandboxID != id { if container.SandboxID != id {
@ -58,27 +56,6 @@ func (c *criService) StopPodSandbox(ctx context.Context, r *runtime.StopPodSandb
} }
} }
// Teardown network for sandbox.
if sandbox.NetNSPath != "" {
netNSPath := sandbox.NetNSPath
if sandbox.NetNS == nil || sandbox.NetNS.Closed() {
// Use empty netns path if netns is not available. This is defined in:
// https://github.com/containernetworking/cni/blob/v0.7.0-alpha1/SPEC.md
netNSPath = ""
}
if err := c.teardownPod(id, netNSPath, sandbox.Config); err != nil {
return nil, errors.Wrapf(err, "failed to destroy network for sandbox %q", id)
}
// Close the sandbox network namespace if it was created
if sandbox.NetNS != nil {
if err = sandbox.NetNS.Remove(); err != nil {
return nil, errors.Wrapf(err, "failed to remove network namespace for sandbox %q", id)
}
}
}
logrus.Infof("TearDown network for sandbox %q successfully", id)
if err := c.unmountSandboxFiles(id, sandbox.Config); err != nil { if err := c.unmountSandboxFiles(id, sandbox.Config); err != nil {
return nil, errors.Wrap(err, "failed to unmount sandbox files") return nil, errors.Wrap(err, "failed to unmount sandbox files")
} }
@ -89,6 +66,27 @@ func (c *criService) StopPodSandbox(ctx context.Context, r *runtime.StopPodSandb
return nil, errors.Wrapf(err, "failed to stop sandbox container %q", id) return nil, errors.Wrapf(err, "failed to stop sandbox container %q", id)
} }
} }
// Teardown network for sandbox.
if sandbox.NetNS != nil {
netNSPath := sandbox.NetNSPath
// Use empty netns path if netns is not available. This is defined in:
// https://github.com/containernetworking/cni/blob/v0.7.0-alpha1/SPEC.md
if closed, err := sandbox.NetNS.Closed(); err != nil {
return nil, errors.Wrap(err, "failed to check network namespace closed")
} else if closed {
netNSPath = ""
}
if err := c.teardownPod(id, netNSPath, sandbox.Config); err != nil {
return nil, errors.Wrapf(err, "failed to destroy network for sandbox %q", id)
}
if err = sandbox.NetNS.Remove(); err != nil {
return nil, errors.Wrapf(err, "failed to remove network namespace for sandbox %q", id)
}
}
logrus.Infof("TearDown network for sandbox %q successfully", id)
return &runtime.StopPodSandboxResponse{}, nil return &runtime.StopPodSandboxResponse{}, nil
} }
@ -106,18 +104,8 @@ func (c *criService) stopSandboxContainer(ctx context.Context, sandbox sandboxst
} }
// Kill the sandbox container. // Kill the sandbox container.
if err = task.Kill(ctx, unix.SIGKILL, containerd.WithKillAll); err != nil && !errdefs.IsNotFound(err) {
return errors.Wrap(err, "failed to kill sandbox container")
}
if err = c.waitSandboxStop(ctx, sandbox, killContainerTimeout); err == nil {
return nil
}
logrus.WithError(err).Errorf("An error occurs during waiting for sandbox %q to be killed", sandbox.ID)
// Kill the sandbox container init process.
if err = task.Kill(ctx, unix.SIGKILL); err != nil && !errdefs.IsNotFound(err) { if err = task.Kill(ctx, unix.SIGKILL); err != nil && !errdefs.IsNotFound(err) {
return errors.Wrap(err, "failed to kill sandbox container init process") return errors.Wrap(err, "failed to kill sandbox container")
} }
return c.waitSandboxStop(ctx, sandbox, killContainerTimeout) return c.waitSandboxStop(ctx, sandbox, killContainerTimeout)
@ -140,7 +128,7 @@ func (c *criService) waitSandboxStop(ctx context.Context, sandbox sandboxstore.S
// teardownPod removes the network from the pod // teardownPod removes the network from the pod
func (c *criService) teardownPod(id string, path string, config *runtime.PodSandboxConfig) error { func (c *criService) teardownPod(id string, path string, config *runtime.PodSandboxConfig) error {
if c.netPlugin == nil { if c.netPlugin == nil {
return errors.New("cni config not intialized") return errors.New("cni config not initialized")
} }
labels := getPodCNILabels(id, config) labels := getPodCNILabels(id, config)

View File

@ -58,6 +58,9 @@ type Metadata struct {
ImageRef string ImageRef string
// LogPath is the container log path. // LogPath is the container log path.
LogPath string LogPath string
// StopSignal is the system call signal that will be sent to the container to exit.
// TODO(random-liu): Add integration test for stop signal.
StopSignal string
} }
// MarshalJSON encodes Metadata into bytes in json format. // MarshalJSON encodes Metadata into bytes in json format.

View File

@ -19,6 +19,7 @@ package sandbox
import ( import (
"encoding/json" "encoding/json"
cni "github.com/containerd/go-cni"
"github.com/pkg/errors" "github.com/pkg/errors"
runtime "k8s.io/kubernetes/pkg/kubelet/apis/cri/runtime/v1alpha2" runtime "k8s.io/kubernetes/pkg/kubelet/apis/cri/runtime/v1alpha2"
) )
@ -56,6 +57,8 @@ type Metadata struct {
IP string IP string
// RuntimeHandler is the runtime handler name of the pod. // RuntimeHandler is the runtime handler name of the pod.
RuntimeHandler string RuntimeHandler string
// CNI result
CNIResult *cni.CNIResult
} }
// MarshalJSON encodes Metadata into bytes in json format. // MarshalJSON encodes Metadata into bytes in json format.

View File

@ -1,132 +0,0 @@
/*
Copyright 2017 The Kubernetes Authors.
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 sandbox
import (
"os"
"sync"
cnins "github.com/containernetworking/plugins/pkg/ns"
"github.com/docker/docker/pkg/symlink"
"github.com/pkg/errors"
osinterface "github.com/containerd/cri/pkg/os"
)
// The NetNS library assumes only containerd manages the lifecycle of the
// network namespace mount. The only case that netns will be unmounted by
// someone else is node reboot.
// If this assumption is broken, NetNS won't be aware of the external
// unmount, and there will be a state mismatch.
// TODO(random-liu): Don't cache state, always load from the system.
// ErrClosedNetNS is the error returned when network namespace is closed.
var ErrClosedNetNS = errors.New("network namespace is closed")
// NetNS holds network namespace for sandbox
type NetNS struct {
sync.Mutex
ns cnins.NetNS
closed bool
restored bool
}
// NewNetNS creates a network namespace for the sandbox
func NewNetNS() (*NetNS, error) {
netns, err := cnins.NewNS()
if err != nil {
return nil, errors.Wrap(err, "failed to setup network namespace")
}
n := new(NetNS)
n.ns = netns
return n, nil
}
// LoadNetNS loads existing network namespace. It returns ErrClosedNetNS
// if the network namespace has already been closed.
func LoadNetNS(path string) (*NetNS, error) {
ns, err := cnins.GetNS(path)
if err != nil {
if _, ok := err.(cnins.NSPathNotExistErr); ok {
return nil, ErrClosedNetNS
}
if _, ok := err.(cnins.NSPathNotNSErr); ok {
// Do best effort cleanup.
os.RemoveAll(path) // nolint: errcheck
return nil, ErrClosedNetNS
}
return nil, errors.Wrap(err, "failed to load network namespace")
}
return &NetNS{ns: ns, restored: true}, nil
}
// Remove removes network namepace if it exists and not closed. Remove is idempotent,
// meaning it might be invoked multiple times and provides consistent result.
func (n *NetNS) Remove() error {
n.Lock()
defer n.Unlock()
if !n.closed {
err := n.ns.Close()
if err != nil {
return errors.Wrap(err, "failed to close network namespace")
}
n.closed = true
}
if n.restored {
path := n.ns.Path()
// Check netns existence.
if _, err := os.Stat(path); err != nil {
if os.IsNotExist(err) {
return nil
}
return errors.Wrap(err, "failed to stat netns")
}
path, err := symlink.FollowSymlinkInScope(path, "/")
if err != nil {
return errors.Wrap(err, "failed to follow symlink")
}
if err := osinterface.Unmount(path); err != nil && !os.IsNotExist(err) {
return errors.Wrap(err, "failed to umount netns")
}
if err := os.RemoveAll(path); err != nil {
return errors.Wrap(err, "failed to remove netns")
}
n.restored = false
}
return nil
}
// Closed checks whether the network namespace has been closed.
func (n *NetNS) Closed() bool {
n.Lock()
defer n.Unlock()
return n.closed && !n.restored
}
// GetPath returns network namespace path for sandbox container
func (n *NetNS) GetPath() string {
n.Lock()
defer n.Unlock()
return n.ns.Path()
}
// GetNs returns the network namespace handle
func (n *NetNS) GetNs() cnins.NetNS {
n.Lock()
defer n.Unlock()
return n.ns
}

View File

@ -22,6 +22,7 @@ import (
"github.com/containerd/containerd" "github.com/containerd/containerd"
"github.com/docker/docker/pkg/truncindex" "github.com/docker/docker/pkg/truncindex"
"github.com/containerd/cri/pkg/netns"
"github.com/containerd/cri/pkg/store" "github.com/containerd/cri/pkg/store"
) )
@ -32,10 +33,12 @@ type Sandbox struct {
Metadata Metadata
// Status stores the status of the sandbox. // Status stores the status of the sandbox.
Status StatusStorage Status StatusStorage
// Container is the containerd sandbox container client // Container is the containerd sandbox container client.
Container containerd.Container Container containerd.Container
// CNI network namespace client // CNI network namespace client.
NetNS *NetNS // For hostnetwork pod, this is always nil;
// For non hostnetwork pod, this should never be nil.
NetNS *netns.NetNS
// StopCh is used to propagate the stop information of the sandbox. // StopCh is used to propagate the stop information of the sandbox.
*store.StopCh *store.StopCh
} }

View File

@ -3,7 +3,7 @@ github.com/blang/semver v3.1.0
github.com/BurntSushi/toml a368813c5e648fee92e5f6c30e3944ff9d5e8895 github.com/BurntSushi/toml a368813c5e648fee92e5f6c30e3944ff9d5e8895
github.com/containerd/cgroups 5e610833b72089b37d0e615de9a92dfc043757c2 github.com/containerd/cgroups 5e610833b72089b37d0e615de9a92dfc043757c2
github.com/containerd/console c12b1e7919c14469339a5d38f2f8ed9b64a9de23 github.com/containerd/console c12b1e7919c14469339a5d38f2f8ed9b64a9de23
github.com/containerd/containerd 15f19d7a67fa322e6de0ef4c6a1bf9da0f056554 github.com/containerd/containerd 6937c5a3ba8280edff9e9030767e3b0cb742581c
github.com/containerd/continuity bd77b46c8352f74eb12c85bdc01f4b90f69d66b4 github.com/containerd/continuity bd77b46c8352f74eb12c85bdc01f4b90f69d66b4
github.com/containerd/fifo 3d5202aec260678c48179c56f40e6f38a095738c github.com/containerd/fifo 3d5202aec260678c48179c56f40e6f38a095738c
github.com/containerd/go-cni 40bcf8ec8acd7372be1d77031d585d5d8e561c90 github.com/containerd/go-cni 40bcf8ec8acd7372be1d77031d585d5d8e561c90
@ -21,11 +21,9 @@ github.com/docker/go-metrics 4ea375f7759c82740c893fc030bc37088d2ec098
github.com/docker/go-units v0.3.1 github.com/docker/go-units v0.3.1
github.com/docker/spdystream 449fdfce4d962303d702fec724ef0ad181c92528 github.com/docker/spdystream 449fdfce4d962303d702fec724ef0ad181c92528
github.com/emicklei/go-restful v2.2.1 github.com/emicklei/go-restful v2.2.1
github.com/ghodss/yaml v1.0.0
github.com/godbus/dbus v3 github.com/godbus/dbus v3
github.com/gogo/googleapis 08a7655d27152912db7aaf4f983275eaf8d128ef github.com/gogo/googleapis 08a7655d27152912db7aaf4f983275eaf8d128ef
github.com/gogo/protobuf v1.0.0 github.com/gogo/protobuf v1.0.0
github.com/golang/glog 44145f04b68cf362d9c4df2182967c2275eaefed
github.com/golang/protobuf v1.1.0 github.com/golang/protobuf v1.1.0
github.com/google/gofuzz 44d81051d367757e1c7c6a5a86423ece9afcf63c github.com/google/gofuzz 44d81051d367757e1c7c6a5a86423ece9afcf63c
github.com/grpc-ecosystem/go-grpc-prometheus v1.1 github.com/grpc-ecosystem/go-grpc-prometheus v1.1
@ -33,15 +31,15 @@ github.com/hashicorp/errwrap 7554cd9344cec97297fa6649b055a8c98c2a1e55
github.com/hashicorp/go-multierror ed905158d87462226a13fe39ddf685ea65f1c11f github.com/hashicorp/go-multierror ed905158d87462226a13fe39ddf685ea65f1c11f
github.com/json-iterator/go 1.1.5 github.com/json-iterator/go 1.1.5
github.com/matttproud/golang_protobuf_extensions v1.0.0 github.com/matttproud/golang_protobuf_extensions v1.0.0
github.com/Microsoft/go-winio v0.4.10 github.com/Microsoft/go-winio v0.4.11
github.com/Microsoft/hcsshim v0.7.6 github.com/Microsoft/hcsshim v0.8.2
github.com/modern-go/concurrent 1.0.3 github.com/modern-go/concurrent 1.0.3
github.com/modern-go/reflect2 1.0.1 github.com/modern-go/reflect2 1.0.1
github.com/opencontainers/go-digest c9281466c8b2f606084ac71339773efd177436e7 github.com/opencontainers/go-digest c9281466c8b2f606084ac71339773efd177436e7
github.com/opencontainers/image-spec v1.0.1 github.com/opencontainers/image-spec v1.0.1
github.com/opencontainers/runc 00dc70017d222b178a002ed30e9321b12647af2d github.com/opencontainers/runc v1.0.0-rc6
github.com/opencontainers/runtime-spec eba862dc2470385a233c7507392675cbeadf7353 github.com/opencontainers/runtime-spec eba862dc2470385a233c7507392675cbeadf7353
github.com/opencontainers/runtime-tools v0.6.0 github.com/opencontainers/runtime-tools fb101d5d42ab9c040f7d0a004e78336e5d5cb197
github.com/opencontainers/selinux b6fa367ed7f534f9ba25391cc2d467085dbb445a github.com/opencontainers/selinux b6fa367ed7f534f9ba25391cc2d467085dbb445a
github.com/pkg/errors v0.8.0 github.com/pkg/errors v0.8.0
github.com/pmezard/go-difflib v1.0.0 github.com/pmezard/go-difflib v1.0.0
@ -50,7 +48,7 @@ github.com/prometheus/client_model 99fa1f4be8e564e8a6b613da7fa6f46c9edafc6c
github.com/prometheus/common 89604d197083d4781071d3c65855d24ecfb0a563 github.com/prometheus/common 89604d197083d4781071d3c65855d24ecfb0a563
github.com/prometheus/procfs cb4147076ac75738c9a7d279075a253c0cc5acbd github.com/prometheus/procfs cb4147076ac75738c9a7d279075a253c0cc5acbd
github.com/seccomp/libseccomp-golang 32f571b70023028bd57d9288c20efbcb237f3ce0 github.com/seccomp/libseccomp-golang 32f571b70023028bd57d9288c20efbcb237f3ce0
github.com/sirupsen/logrus v1.0.0 github.com/sirupsen/logrus v1.0.3
github.com/stretchr/testify v1.1.4 github.com/stretchr/testify v1.1.4
github.com/syndtr/gocapability db04d3cc01c8b54962a58ec7e491717d06cfcc16 github.com/syndtr/gocapability db04d3cc01c8b54962a58ec7e491717d06cfcc16
github.com/tchap/go-patricia v2.2.6 github.com/tchap/go-patricia v2.2.6
@ -69,10 +67,12 @@ golang.org/x/time f51c12702a4d776e4c1fa9b0fabab841babae631
google.golang.org/genproto d80a6e20e776b0b17a324d0ba1ab50a39c8e8944 google.golang.org/genproto d80a6e20e776b0b17a324d0ba1ab50a39c8e8944
google.golang.org/grpc v1.12.0 google.golang.org/grpc v1.12.0
gopkg.in/inf.v0 3887ee99ecf07df5b447e9b00d9c0b2adaa9f3e4 gopkg.in/inf.v0 3887ee99ecf07df5b447e9b00d9c0b2adaa9f3e4
gopkg.in/yaml.v2 53feefa2559fb8dfa8d81baad31be332c97d6c77 gopkg.in/yaml.v2 v2.2.1
k8s.io/api kubernetes-1.12.0 k8s.io/api kubernetes-1.13.0
k8s.io/apimachinery kubernetes-1.12.0 k8s.io/apimachinery kubernetes-1.13.0
k8s.io/apiserver kubernetes-1.12.0 k8s.io/apiserver kubernetes-1.13.0
k8s.io/client-go kubernetes-1.12.0 k8s.io/client-go kubernetes-1.13.0
k8s.io/kubernetes v1.12.0 k8s.io/klog 8139d8cb77af419532b33dfa7dd09fbc5f1d344f
k8s.io/utils cd34563cd63c2bd7c6fe88a73c4dcf34ed8a67cb k8s.io/kubernetes v1.13.0
k8s.io/utils 0d26856f57b32ec3398579285e5c8a2bfe8c5243
sigs.k8s.io/yaml v1.1.0

View File

@ -78,4 +78,23 @@ const (
// //
// Not all cloud providers support this annotation, though AWS & GCE do. // Not all cloud providers support this annotation, though AWS & GCE do.
AnnotationLoadBalancerSourceRangesKey = "service.beta.kubernetes.io/load-balancer-source-ranges" AnnotationLoadBalancerSourceRangesKey = "service.beta.kubernetes.io/load-balancer-source-ranges"
// EndpointsLastChangeTriggerTime is the annotation key, set for endpoints objects, that
// represents the timestamp (stored as RFC 3339 date-time string, e.g. '2018-10-22T19:32:52.1Z')
// of the last change, of some Pod or Service object, that triggered the endpoints object change.
// In other words, if a Pod / Service changed at time T0, that change was observed by endpoints
// controller at T1, and the Endpoints object was changed at T2, the
// EndpointsLastChangeTriggerTime would be set to T0.
//
// The "endpoints change trigger" here means any Pod or Service change that resulted in the
// Endpoints object change.
//
// Given the definition of the "endpoints change trigger", please note that this annotation will
// be set ONLY for endpoints object changes triggered by either Pod or Service change. If the
// Endpoints object changes due to other reasons, this annotation won't be set (or updated if it's
// already set).
//
// This annotation will be used to compute the in-cluster network programming latency SLI, see
// https://github.com/kubernetes/community/blob/master/sig-scalability/slos/network_programming_latency.md
EndpointsLastChangeTriggerTime = "endpoints.kubernetes.io/last-change-trigger-time"
) )

File diff suppressed because it is too large Load Diff

View File

@ -606,6 +606,9 @@ message Container {
// +optional // +optional
// +patchMergeKey=containerPort // +patchMergeKey=containerPort
// +patchStrategy=merge // +patchStrategy=merge
// +listType=map
// +listMapKey=containerPort
// +listMapKey=protocol
repeated ContainerPort ports = 6; repeated ContainerPort ports = 6;
// List of sources to populate environment variables in the container. // List of sources to populate environment variables in the container.
@ -638,7 +641,7 @@ message Container {
repeated VolumeMount volumeMounts = 9; repeated VolumeMount volumeMounts = 9;
// volumeDevices is the list of block devices to be used by the container. // volumeDevices is the list of block devices to be used by the container.
// This is an alpha feature and may change in the future. // This is a beta feature.
// +patchMergeKey=devicePath // +patchMergeKey=devicePath
// +patchStrategy=merge // +patchStrategy=merge
// +optional // +optional
@ -1370,6 +1373,30 @@ message GitRepoVolumeSource {
optional string directory = 3; optional string directory = 3;
} }
// Represents a Glusterfs mount that lasts the lifetime of a pod.
// Glusterfs volumes do not support ownership management or SELinux relabeling.
message GlusterfsPersistentVolumeSource {
// EndpointsName is the endpoint name that details Glusterfs topology.
// More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod
optional string endpoints = 1;
// Path is the Glusterfs volume path.
// More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod
optional string path = 2;
// ReadOnly here will force the Glusterfs volume to be mounted with read-only permissions.
// Defaults to false.
// More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod
// +optional
optional bool readOnly = 3;
// EndpointsNamespace is the namespace that contains Glusterfs endpoint.
// If this field is empty, the EndpointNamespace defaults to the same namespace as the bound PVC.
// More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod
// +optional
optional string endpointsNamespace = 4;
}
// Represents a Glusterfs mount that lasts the lifetime of a pod. // Represents a Glusterfs mount that lasts the lifetime of a pod.
// Glusterfs volumes do not support ownership management or SELinux relabeling. // Glusterfs volumes do not support ownership management or SELinux relabeling.
message GlusterfsVolumeSource { message GlusterfsVolumeSource {
@ -2293,7 +2320,7 @@ message PersistentVolumeClaimSpec {
// volumeMode defines what type of volume is required by the claim. // volumeMode defines what type of volume is required by the claim.
// Value of Filesystem is implied when not included in claim spec. // Value of Filesystem is implied when not included in claim spec.
// This is an alpha feature and may change in the future. // This is a beta feature.
// +optional // +optional
optional string volumeMode = 6; optional string volumeMode = 6;
@ -2386,7 +2413,7 @@ message PersistentVolumeSource {
// exposed to the pod. Provisioned by an admin. // exposed to the pod. Provisioned by an admin.
// More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md // More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md
// +optional // +optional
optional GlusterfsVolumeSource glusterfs = 4; optional GlusterfsPersistentVolumeSource glusterfs = 4;
// NFS represents an NFS mount on the host. Provisioned by an admin. // NFS represents an NFS mount on the host. Provisioned by an admin.
// More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs // More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs
@ -2509,7 +2536,7 @@ message PersistentVolumeSpec {
// volumeMode defines if a volume is intended to be used with a formatted filesystem // volumeMode defines if a volume is intended to be used with a formatted filesystem
// or to remain in raw block state. Value of Filesystem is implied when not included in spec. // or to remain in raw block state. Value of Filesystem is implied when not included in spec.
// This is an alpha feature and may change in the future. // This is a beta feature.
// +optional // +optional
optional string volumeMode = 8; optional string volumeMode = 8;
@ -3126,6 +3153,11 @@ message PodSpec {
// This is an alpha feature and may change in the future. // This is an alpha feature and may change in the future.
// +optional // +optional
optional string runtimeClassName = 29; optional string runtimeClassName = 29;
// EnableServiceLinks indicates whether information about services should be injected into pod's
// environment variables, matching the syntax of Docker links.
// +optional
optional bool enableServiceLinks = 30;
} }
// PodStatus represents information about the status of a pod. Status may trail the actual // PodStatus represents information about the status of a pod. Status may trail the actual

54
vendor/k8s.io/api/core/v1/types.go generated vendored
View File

@ -191,7 +191,7 @@ type PersistentVolumeSource struct {
// exposed to the pod. Provisioned by an admin. // exposed to the pod. Provisioned by an admin.
// More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md // More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md
// +optional // +optional
Glusterfs *GlusterfsVolumeSource `json:"glusterfs,omitempty" protobuf:"bytes,4,opt,name=glusterfs"` Glusterfs *GlusterfsPersistentVolumeSource `json:"glusterfs,omitempty" protobuf:"bytes,4,opt,name=glusterfs"`
// NFS represents an NFS mount on the host. Provisioned by an admin. // NFS represents an NFS mount on the host. Provisioned by an admin.
// More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs // More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs
// +optional // +optional
@ -326,7 +326,7 @@ type PersistentVolumeSpec struct {
MountOptions []string `json:"mountOptions,omitempty" protobuf:"bytes,7,opt,name=mountOptions"` MountOptions []string `json:"mountOptions,omitempty" protobuf:"bytes,7,opt,name=mountOptions"`
// volumeMode defines if a volume is intended to be used with a formatted filesystem // volumeMode defines if a volume is intended to be used with a formatted filesystem
// or to remain in raw block state. Value of Filesystem is implied when not included in spec. // or to remain in raw block state. Value of Filesystem is implied when not included in spec.
// This is an alpha feature and may change in the future. // This is a beta feature.
// +optional // +optional
VolumeMode *PersistentVolumeMode `json:"volumeMode,omitempty" protobuf:"bytes,8,opt,name=volumeMode,casttype=PersistentVolumeMode"` VolumeMode *PersistentVolumeMode `json:"volumeMode,omitempty" protobuf:"bytes,8,opt,name=volumeMode,casttype=PersistentVolumeMode"`
// NodeAffinity defines constraints that limit what nodes this volume can be accessed from. // NodeAffinity defines constraints that limit what nodes this volume can be accessed from.
@ -455,7 +455,7 @@ type PersistentVolumeClaimSpec struct {
StorageClassName *string `json:"storageClassName,omitempty" protobuf:"bytes,5,opt,name=storageClassName"` StorageClassName *string `json:"storageClassName,omitempty" protobuf:"bytes,5,opt,name=storageClassName"`
// volumeMode defines what type of volume is required by the claim. // volumeMode defines what type of volume is required by the claim.
// Value of Filesystem is implied when not included in claim spec. // Value of Filesystem is implied when not included in claim spec.
// This is an alpha feature and may change in the future. // This is a beta feature.
// +optional // +optional
VolumeMode *PersistentVolumeMode `json:"volumeMode,omitempty" protobuf:"bytes,6,opt,name=volumeMode,casttype=PersistentVolumeMode"` VolumeMode *PersistentVolumeMode `json:"volumeMode,omitempty" protobuf:"bytes,6,opt,name=volumeMode,casttype=PersistentVolumeMode"`
// This field requires the VolumeSnapshotDataSource alpha feature gate to be // This field requires the VolumeSnapshotDataSource alpha feature gate to be
@ -636,6 +636,30 @@ type GlusterfsVolumeSource struct {
ReadOnly bool `json:"readOnly,omitempty" protobuf:"varint,3,opt,name=readOnly"` ReadOnly bool `json:"readOnly,omitempty" protobuf:"varint,3,opt,name=readOnly"`
} }
// Represents a Glusterfs mount that lasts the lifetime of a pod.
// Glusterfs volumes do not support ownership management or SELinux relabeling.
type GlusterfsPersistentVolumeSource struct {
// EndpointsName is the endpoint name that details Glusterfs topology.
// More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod
EndpointsName string `json:"endpoints" protobuf:"bytes,1,opt,name=endpoints"`
// Path is the Glusterfs volume path.
// More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod
Path string `json:"path" protobuf:"bytes,2,opt,name=path"`
// ReadOnly here will force the Glusterfs volume to be mounted with read-only permissions.
// Defaults to false.
// More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod
// +optional
ReadOnly bool `json:"readOnly,omitempty" protobuf:"varint,3,opt,name=readOnly"`
// EndpointsNamespace is the namespace that contains Glusterfs endpoint.
// If this field is empty, the EndpointNamespace defaults to the same namespace as the bound PVC.
// More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod
// +optional
EndpointsNamespace *string `json:"endpointsNamespace,omitempty" protobuf:"bytes,4,opt,name=endpointsNamespace"`
}
// Represents a Rados Block Device mount that lasts the lifetime of a pod. // Represents a Rados Block Device mount that lasts the lifetime of a pod.
// RBD volumes support ownership management and SELinux relabeling. // RBD volumes support ownership management and SELinux relabeling.
type RBDVolumeSource struct { type RBDVolumeSource struct {
@ -2060,6 +2084,9 @@ type Container struct {
// +optional // +optional
// +patchMergeKey=containerPort // +patchMergeKey=containerPort
// +patchStrategy=merge // +patchStrategy=merge
// +listType=map
// +listMapKey=containerPort
// +listMapKey=protocol
Ports []ContainerPort `json:"ports,omitempty" patchStrategy:"merge" patchMergeKey:"containerPort" protobuf:"bytes,6,rep,name=ports"` Ports []ContainerPort `json:"ports,omitempty" patchStrategy:"merge" patchMergeKey:"containerPort" protobuf:"bytes,6,rep,name=ports"`
// List of sources to populate environment variables in the container. // List of sources to populate environment variables in the container.
// The keys defined within a source must be a C_IDENTIFIER. All invalid keys // The keys defined within a source must be a C_IDENTIFIER. All invalid keys
@ -2087,7 +2114,7 @@ type Container struct {
// +patchStrategy=merge // +patchStrategy=merge
VolumeMounts []VolumeMount `json:"volumeMounts,omitempty" patchStrategy:"merge" patchMergeKey:"mountPath" protobuf:"bytes,9,rep,name=volumeMounts"` VolumeMounts []VolumeMount `json:"volumeMounts,omitempty" patchStrategy:"merge" patchMergeKey:"mountPath" protobuf:"bytes,9,rep,name=volumeMounts"`
// volumeDevices is the list of block devices to be used by the container. // volumeDevices is the list of block devices to be used by the container.
// This is an alpha feature and may change in the future. // This is a beta feature.
// +patchMergeKey=devicePath // +patchMergeKey=devicePath
// +patchStrategy=merge // +patchStrategy=merge
// +optional // +optional
@ -2891,8 +2918,17 @@ type PodSpec struct {
// This is an alpha feature and may change in the future. // This is an alpha feature and may change in the future.
// +optional // +optional
RuntimeClassName *string `json:"runtimeClassName,omitempty" protobuf:"bytes,29,opt,name=runtimeClassName"` RuntimeClassName *string `json:"runtimeClassName,omitempty" protobuf:"bytes,29,opt,name=runtimeClassName"`
// EnableServiceLinks indicates whether information about services should be injected into pod's
// environment variables, matching the syntax of Docker links.
// +optional
EnableServiceLinks *bool `json:"enableServiceLinks,omitempty" protobuf:"varint,30,opt,name=enableServiceLinks"`
} }
const (
// The default value for enableServiceLinks attribute.
DefaultEnableServiceLinks = true
)
// HostAlias holds the mapping between IP and hostnames that will be injected as an entry in the // HostAlias holds the mapping between IP and hostnames that will be injected as an entry in the
// pod's hosts file. // pod's hosts file.
type HostAlias struct { type HostAlias struct {
@ -3273,8 +3309,8 @@ type ReplicationControllerCondition struct {
} }
// +genclient // +genclient
// +genclient:method=GetScale,verb=get,subresource=scale,result=k8s.io/api/extensions/v1beta1.Scale // +genclient:method=GetScale,verb=get,subresource=scale,result=k8s.io/api/autoscaling/v1.Scale
// +genclient:method=UpdateScale,verb=update,subresource=scale,input=k8s.io/api/extensions/v1beta1.Scale,result=k8s.io/api/extensions/v1beta1.Scale // +genclient:method=UpdateScale,verb=update,subresource=scale,input=k8s.io/api/autoscaling/v1.Scale,result=k8s.io/api/autoscaling/v1.Scale
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// ReplicationController represents the configuration of a replication controller. // ReplicationController represents the configuration of a replication controller.
@ -4987,6 +5023,10 @@ const (
TLSCertKey = "tls.crt" TLSCertKey = "tls.crt"
// TLSPrivateKeyKey is the key for the private key field in a TLS secret. // TLSPrivateKeyKey is the key for the private key field in a TLS secret.
TLSPrivateKeyKey = "tls.key" TLSPrivateKeyKey = "tls.key"
// SecretTypeBootstrapToken is used during the automated bootstrap process (first
// implemented by kubeadm). It stores tokens that are used to sign well known
// ConfigMaps. They are used for authn.
SecretTypeBootstrapToken SecretType = "bootstrap.kubernetes.io/token"
) )
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
@ -5210,7 +5250,7 @@ type SecurityContext struct {
// readonly paths and masked paths. // readonly paths and masked paths.
// This requires the ProcMountType feature flag to be enabled. // This requires the ProcMountType feature flag to be enabled.
// +optional // +optional
ProcMount *ProcMountType `json:"procMount,omitEmpty" protobuf:"bytes,9,opt,name=procMount"` ProcMount *ProcMountType `json:"procMount,omitempty" protobuf:"bytes,9,opt,name=procMount"`
} }
type ProcMountType string type ProcMountType string

View File

@ -321,7 +321,7 @@ var map_Container = map[string]string{
"env": "List of environment variables to set in the container. Cannot be updated.", "env": "List of environment variables to set in the container. Cannot be updated.",
"resources": "Compute Resources required by this container. Cannot be updated. More info: https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/", "resources": "Compute Resources required by this container. Cannot be updated. More info: https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/",
"volumeMounts": "Pod volumes to mount into the container's filesystem. Cannot be updated.", "volumeMounts": "Pod volumes to mount into the container's filesystem. Cannot be updated.",
"volumeDevices": "volumeDevices is the list of block devices to be used by the container. This is an alpha feature and may change in the future.", "volumeDevices": "volumeDevices is the list of block devices to be used by the container. This is a beta feature.",
"livenessProbe": "Periodic probe of container liveness. Container will be restarted if the probe fails. Cannot be updated. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes", "livenessProbe": "Periodic probe of container liveness. Container will be restarted if the probe fails. Cannot be updated. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes",
"readinessProbe": "Periodic probe of container service readiness. Container will be removed from service endpoints if the probe fails. Cannot be updated. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes", "readinessProbe": "Periodic probe of container service readiness. Container will be removed from service endpoints if the probe fails. Cannot be updated. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes",
"lifecycle": "Actions that the management system should take in response to container lifecycle events. Cannot be updated.", "lifecycle": "Actions that the management system should take in response to container lifecycle events. Cannot be updated.",
@ -695,6 +695,18 @@ func (GitRepoVolumeSource) SwaggerDoc() map[string]string {
return map_GitRepoVolumeSource return map_GitRepoVolumeSource
} }
var map_GlusterfsPersistentVolumeSource = map[string]string{
"": "Represents a Glusterfs mount that lasts the lifetime of a pod. Glusterfs volumes do not support ownership management or SELinux relabeling.",
"endpoints": "EndpointsName is the endpoint name that details Glusterfs topology. More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod",
"path": "Path is the Glusterfs volume path. More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod",
"readOnly": "ReadOnly here will force the Glusterfs volume to be mounted with read-only permissions. Defaults to false. More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod",
"endpointsNamespace": "EndpointsNamespace is the namespace that contains Glusterfs endpoint. If this field is empty, the EndpointNamespace defaults to the same namespace as the bound PVC. More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod",
}
func (GlusterfsPersistentVolumeSource) SwaggerDoc() map[string]string {
return map_GlusterfsPersistentVolumeSource
}
var map_GlusterfsVolumeSource = map[string]string{ var map_GlusterfsVolumeSource = map[string]string{
"": "Represents a Glusterfs mount that lasts the lifetime of a pod. Glusterfs volumes do not support ownership management or SELinux relabeling.", "": "Represents a Glusterfs mount that lasts the lifetime of a pod. Glusterfs volumes do not support ownership management or SELinux relabeling.",
"endpoints": "EndpointsName is the endpoint name that details Glusterfs topology. More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod", "endpoints": "EndpointsName is the endpoint name that details Glusterfs topology. More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod",
@ -1210,7 +1222,7 @@ var map_PersistentVolumeClaimSpec = map[string]string{
"resources": "Resources represents the minimum resources the volume should have. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#resources", "resources": "Resources represents the minimum resources the volume should have. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#resources",
"volumeName": "VolumeName is the binding reference to the PersistentVolume backing this claim.", "volumeName": "VolumeName is the binding reference to the PersistentVolume backing this claim.",
"storageClassName": "Name of the StorageClass required by the claim. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#class-1", "storageClassName": "Name of the StorageClass required by the claim. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#class-1",
"volumeMode": "volumeMode defines what type of volume is required by the claim. Value of Filesystem is implied when not included in claim spec. This is an alpha feature and may change in the future.", "volumeMode": "volumeMode defines what type of volume is required by the claim. Value of Filesystem is implied when not included in claim spec. This is a beta feature.",
"dataSource": "This field requires the VolumeSnapshotDataSource alpha feature gate to be enabled and currently VolumeSnapshot is the only supported data source. If the provisioner can support VolumeSnapshot data source, it will create a new volume and data will be restored to the volume at the same time. If the provisioner does not support VolumeSnapshot data source, volume will not be created and the failure will be reported as an event. In the future, we plan to support more data source types and the behavior of the provisioner may change.", "dataSource": "This field requires the VolumeSnapshotDataSource alpha feature gate to be enabled and currently VolumeSnapshot is the only supported data source. If the provisioner can support VolumeSnapshot data source, it will create a new volume and data will be restored to the volume at the same time. If the provisioner does not support VolumeSnapshot data source, volume will not be created and the failure will be reported as an event. In the future, we plan to support more data source types and the behavior of the provisioner may change.",
} }
@ -1288,7 +1300,7 @@ var map_PersistentVolumeSpec = map[string]string{
"persistentVolumeReclaimPolicy": "What happens to a persistent volume when released from its claim. Valid options are Retain (default for manually created PersistentVolumes), Delete (default for dynamically provisioned PersistentVolumes), and Recycle (deprecated). Recycle must be supported by the volume plugin underlying this PersistentVolume. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#reclaiming", "persistentVolumeReclaimPolicy": "What happens to a persistent volume when released from its claim. Valid options are Retain (default for manually created PersistentVolumes), Delete (default for dynamically provisioned PersistentVolumes), and Recycle (deprecated). Recycle must be supported by the volume plugin underlying this PersistentVolume. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#reclaiming",
"storageClassName": "Name of StorageClass to which this persistent volume belongs. Empty value means that this volume does not belong to any StorageClass.", "storageClassName": "Name of StorageClass to which this persistent volume belongs. Empty value means that this volume does not belong to any StorageClass.",
"mountOptions": "A list of mount options, e.g. [\"ro\", \"soft\"]. Not validated - mount will simply fail if one is invalid. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes/#mount-options", "mountOptions": "A list of mount options, e.g. [\"ro\", \"soft\"]. Not validated - mount will simply fail if one is invalid. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes/#mount-options",
"volumeMode": "volumeMode defines if a volume is intended to be used with a formatted filesystem or to remain in raw block state. Value of Filesystem is implied when not included in spec. This is an alpha feature and may change in the future.", "volumeMode": "volumeMode defines if a volume is intended to be used with a formatted filesystem or to remain in raw block state. Value of Filesystem is implied when not included in spec. This is a beta feature.",
"nodeAffinity": "NodeAffinity defines constraints that limit what nodes this volume can be accessed from. This field influences the scheduling of pods that use this volume.", "nodeAffinity": "NodeAffinity defines constraints that limit what nodes this volume can be accessed from. This field influences the scheduling of pods that use this volume.",
} }
@ -1528,6 +1540,7 @@ var map_PodSpec = map[string]string{
"dnsConfig": "Specifies the DNS parameters of a pod. Parameters specified here will be merged to the generated DNS configuration based on DNSPolicy.", "dnsConfig": "Specifies the DNS parameters of a pod. Parameters specified here will be merged to the generated DNS configuration based on DNSPolicy.",
"readinessGates": "If specified, all readiness gates will be evaluated for pod readiness. A pod is ready when all its containers are ready AND all conditions specified in the readiness gates have status equal to \"True\" More info: https://github.com/kubernetes/community/blob/master/keps/sig-network/0007-pod-ready%2B%2B.md", "readinessGates": "If specified, all readiness gates will be evaluated for pod readiness. A pod is ready when all its containers are ready AND all conditions specified in the readiness gates have status equal to \"True\" More info: https://github.com/kubernetes/community/blob/master/keps/sig-network/0007-pod-ready%2B%2B.md",
"runtimeClassName": "RuntimeClassName refers to a RuntimeClass object in the node.k8s.io group, which should be used to run this pod. If no RuntimeClass resource matches the named class, the pod will not be run. If unset or empty, the \"legacy\" RuntimeClass will be used, which is an implicit class with an empty definition that uses the default runtime handler. More info: https://github.com/kubernetes/community/blob/master/keps/sig-node/0014-runtime-class.md This is an alpha feature and may change in the future.", "runtimeClassName": "RuntimeClassName refers to a RuntimeClass object in the node.k8s.io group, which should be used to run this pod. If no RuntimeClass resource matches the named class, the pod will not be run. If unset or empty, the \"legacy\" RuntimeClass will be used, which is an implicit class with an empty definition that uses the default runtime handler. More info: https://github.com/kubernetes/community/blob/master/keps/sig-node/0014-runtime-class.md This is an alpha feature and may change in the future.",
"enableServiceLinks": "EnableServiceLinks indicates whether information about services should be injected into pod's environment variables, matching the syntax of Docker links.",
} }
func (PodSpec) SwaggerDoc() map[string]string { func (PodSpec) SwaggerDoc() map[string]string {

View File

@ -1498,6 +1498,27 @@ func (in *GitRepoVolumeSource) DeepCopy() *GitRepoVolumeSource {
return out return out
} }
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *GlusterfsPersistentVolumeSource) DeepCopyInto(out *GlusterfsPersistentVolumeSource) {
*out = *in
if in.EndpointsNamespace != nil {
in, out := &in.EndpointsNamespace, &out.EndpointsNamespace
*out = new(string)
**out = **in
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GlusterfsPersistentVolumeSource.
func (in *GlusterfsPersistentVolumeSource) DeepCopy() *GlusterfsPersistentVolumeSource {
if in == nil {
return nil
}
out := new(GlusterfsPersistentVolumeSource)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *GlusterfsVolumeSource) DeepCopyInto(out *GlusterfsVolumeSource) { func (in *GlusterfsVolumeSource) DeepCopyInto(out *GlusterfsVolumeSource) {
*out = *in *out = *in
@ -2806,8 +2827,8 @@ func (in *PersistentVolumeSource) DeepCopyInto(out *PersistentVolumeSource) {
} }
if in.Glusterfs != nil { if in.Glusterfs != nil {
in, out := &in.Glusterfs, &out.Glusterfs in, out := &in.Glusterfs, &out.Glusterfs
*out = new(GlusterfsVolumeSource) *out = new(GlusterfsPersistentVolumeSource)
**out = **in (*in).DeepCopyInto(*out)
} }
if in.NFS != nil { if in.NFS != nil {
in, out := &in.NFS, &out.NFS in, out := &in.NFS, &out.NFS
@ -3554,6 +3575,11 @@ func (in *PodSpec) DeepCopyInto(out *PodSpec) {
*out = new(string) *out = new(string)
**out = **in **out = **in
} }
if in.EnableServiceLinks != nil {
in, out := &in.EnableServiceLinks, &out.EnableServiceLinks
*out = new(bool)
**out = **in
}
return return
} }

View File

@ -20,6 +20,7 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"net/http" "net/http"
"reflect"
"strings" "strings"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@ -82,7 +83,20 @@ func (u *UnexpectedObjectError) Error() string {
func FromObject(obj runtime.Object) error { func FromObject(obj runtime.Object) error {
switch t := obj.(type) { switch t := obj.(type) {
case *metav1.Status: case *metav1.Status:
return &StatusError{*t} return &StatusError{ErrStatus: *t}
case runtime.Unstructured:
var status metav1.Status
obj := t.UnstructuredContent()
if !reflect.DeepEqual(obj["kind"], "Status") {
break
}
if err := runtime.DefaultUnstructuredConverter.FromUnstructured(t.UnstructuredContent(), &status); err != nil {
return err
}
if status.APIVersion != "v1" && status.APIVersion != "meta.k8s.io/v1" {
break
}
return &StatusError{ErrStatus: status}
} }
return &UnexpectedObjectError{obj} return &UnexpectedObjectError{obj}
} }

View File

@ -14,9 +14,8 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
// Code generated by protoc-gen-gogo. // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/api/resource/generated.proto // source: k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/api/resource/generated.proto
// DO NOT EDIT!
/* /*
Package resource is a generated protocol buffer package. Package resource is a generated protocol buffer package.

View File

@ -19,4 +19,5 @@ limitations under the License.
// +k8s:defaulter-gen=TypeMeta // +k8s:defaulter-gen=TypeMeta
// +groupName=meta.k8s.io // +groupName=meta.k8s.io
package v1 // import "k8s.io/apimachinery/pkg/apis/meta/v1" package v1 // import "k8s.io/apimachinery/pkg/apis/meta/v1"

View File

@ -14,9 +14,8 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
// Code generated by protoc-gen-gogo. // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto // source: k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto
// DO NOT EDIT!
/* /*
Package v1 is a generated protocol buffer package. Package v1 is a generated protocol buffer package.
@ -1768,24 +1767,6 @@ func (m *WatchEvent) MarshalTo(dAtA []byte) (int, error) {
return i, nil return i, nil
} }
func encodeFixed64Generated(dAtA []byte, offset int, v uint64) int {
dAtA[offset] = uint8(v)
dAtA[offset+1] = uint8(v >> 8)
dAtA[offset+2] = uint8(v >> 16)
dAtA[offset+3] = uint8(v >> 24)
dAtA[offset+4] = uint8(v >> 32)
dAtA[offset+5] = uint8(v >> 40)
dAtA[offset+6] = uint8(v >> 48)
dAtA[offset+7] = uint8(v >> 56)
return offset + 8
}
func encodeFixed32Generated(dAtA []byte, offset int, v uint32) int {
dAtA[offset] = uint8(v)
dAtA[offset+1] = uint8(v >> 8)
dAtA[offset+2] = uint8(v >> 16)
dAtA[offset+3] = uint8(v >> 24)
return offset + 4
}
func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int { func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int {
for v >= 1<<7 { for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80) dAtA[offset] = uint8(v&0x7f | 0x80)
@ -5043,7 +5024,14 @@ func (m *LabelSelector) Unmarshal(dAtA []byte) error {
if postIndex > l { if postIndex > l {
return io.ErrUnexpectedEOF return io.ErrUnexpectedEOF
} }
var keykey uint64 if m.MatchLabels == nil {
m.MatchLabels = make(map[string]string)
}
var mapkey string
var mapvalue string
for iNdEx < postIndex {
entryPreIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 { for shift := uint(0); ; shift += 7 {
if shift >= 64 { if shift >= 64 {
return ErrIntOverflowGenerated return ErrIntOverflowGenerated
@ -5053,11 +5041,13 @@ func (m *LabelSelector) Unmarshal(dAtA []byte) error {
} }
b := dAtA[iNdEx] b := dAtA[iNdEx]
iNdEx++ iNdEx++
keykey |= (uint64(b) & 0x7F) << shift wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 { if b < 0x80 {
break break
} }
} }
fieldNum := int32(wire >> 3)
if fieldNum == 1 {
var stringLenmapkey uint64 var stringLenmapkey uint64
for shift := uint(0); ; shift += 7 { for shift := uint(0); ; shift += 7 {
if shift >= 64 { if shift >= 64 {
@ -5081,27 +5071,9 @@ func (m *LabelSelector) Unmarshal(dAtA []byte) error {
if postStringIndexmapkey > l { if postStringIndexmapkey > l {
return io.ErrUnexpectedEOF return io.ErrUnexpectedEOF
} }
mapkey := string(dAtA[iNdEx:postStringIndexmapkey]) mapkey = string(dAtA[iNdEx:postStringIndexmapkey])
iNdEx = postStringIndexmapkey iNdEx = postStringIndexmapkey
if m.MatchLabels == nil { } else if fieldNum == 2 {
m.MatchLabels = make(map[string]string)
}
if iNdEx < postIndex {
var valuekey uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenerated
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
valuekey |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
var stringLenmapvalue uint64 var stringLenmapvalue uint64
for shift := uint(0); ; shift += 7 { for shift := uint(0); ; shift += 7 {
if shift >= 64 { if shift >= 64 {
@ -5125,13 +5097,24 @@ func (m *LabelSelector) Unmarshal(dAtA []byte) error {
if postStringIndexmapvalue > l { if postStringIndexmapvalue > l {
return io.ErrUnexpectedEOF return io.ErrUnexpectedEOF
} }
mapvalue := string(dAtA[iNdEx:postStringIndexmapvalue]) mapvalue = string(dAtA[iNdEx:postStringIndexmapvalue])
iNdEx = postStringIndexmapvalue iNdEx = postStringIndexmapvalue
m.MatchLabels[mapkey] = mapvalue
} else { } else {
var mapvalue string iNdEx = entryPreIndex
m.MatchLabels[mapkey] = mapvalue skippy, err := skipGenerated(dAtA[iNdEx:])
if err != nil {
return err
} }
if skippy < 0 {
return ErrInvalidLengthGenerated
}
if (iNdEx + skippy) > postIndex {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
m.MatchLabels[mapkey] = mapvalue
iNdEx = postIndex iNdEx = postIndex
case 2: case 2:
if wireType != 2 { if wireType != 2 {
@ -6146,7 +6129,14 @@ func (m *ObjectMeta) Unmarshal(dAtA []byte) error {
if postIndex > l { if postIndex > l {
return io.ErrUnexpectedEOF return io.ErrUnexpectedEOF
} }
var keykey uint64 if m.Labels == nil {
m.Labels = make(map[string]string)
}
var mapkey string
var mapvalue string
for iNdEx < postIndex {
entryPreIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 { for shift := uint(0); ; shift += 7 {
if shift >= 64 { if shift >= 64 {
return ErrIntOverflowGenerated return ErrIntOverflowGenerated
@ -6156,11 +6146,13 @@ func (m *ObjectMeta) Unmarshal(dAtA []byte) error {
} }
b := dAtA[iNdEx] b := dAtA[iNdEx]
iNdEx++ iNdEx++
keykey |= (uint64(b) & 0x7F) << shift wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 { if b < 0x80 {
break break
} }
} }
fieldNum := int32(wire >> 3)
if fieldNum == 1 {
var stringLenmapkey uint64 var stringLenmapkey uint64
for shift := uint(0); ; shift += 7 { for shift := uint(0); ; shift += 7 {
if shift >= 64 { if shift >= 64 {
@ -6184,27 +6176,9 @@ func (m *ObjectMeta) Unmarshal(dAtA []byte) error {
if postStringIndexmapkey > l { if postStringIndexmapkey > l {
return io.ErrUnexpectedEOF return io.ErrUnexpectedEOF
} }
mapkey := string(dAtA[iNdEx:postStringIndexmapkey]) mapkey = string(dAtA[iNdEx:postStringIndexmapkey])
iNdEx = postStringIndexmapkey iNdEx = postStringIndexmapkey
if m.Labels == nil { } else if fieldNum == 2 {
m.Labels = make(map[string]string)
}
if iNdEx < postIndex {
var valuekey uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenerated
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
valuekey |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
var stringLenmapvalue uint64 var stringLenmapvalue uint64
for shift := uint(0); ; shift += 7 { for shift := uint(0); ; shift += 7 {
if shift >= 64 { if shift >= 64 {
@ -6228,13 +6202,24 @@ func (m *ObjectMeta) Unmarshal(dAtA []byte) error {
if postStringIndexmapvalue > l { if postStringIndexmapvalue > l {
return io.ErrUnexpectedEOF return io.ErrUnexpectedEOF
} }
mapvalue := string(dAtA[iNdEx:postStringIndexmapvalue]) mapvalue = string(dAtA[iNdEx:postStringIndexmapvalue])
iNdEx = postStringIndexmapvalue iNdEx = postStringIndexmapvalue
m.Labels[mapkey] = mapvalue
} else { } else {
var mapvalue string iNdEx = entryPreIndex
m.Labels[mapkey] = mapvalue skippy, err := skipGenerated(dAtA[iNdEx:])
if err != nil {
return err
} }
if skippy < 0 {
return ErrInvalidLengthGenerated
}
if (iNdEx + skippy) > postIndex {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
m.Labels[mapkey] = mapvalue
iNdEx = postIndex iNdEx = postIndex
case 12: case 12:
if wireType != 2 { if wireType != 2 {
@ -6262,7 +6247,14 @@ func (m *ObjectMeta) Unmarshal(dAtA []byte) error {
if postIndex > l { if postIndex > l {
return io.ErrUnexpectedEOF return io.ErrUnexpectedEOF
} }
var keykey uint64 if m.Annotations == nil {
m.Annotations = make(map[string]string)
}
var mapkey string
var mapvalue string
for iNdEx < postIndex {
entryPreIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 { for shift := uint(0); ; shift += 7 {
if shift >= 64 { if shift >= 64 {
return ErrIntOverflowGenerated return ErrIntOverflowGenerated
@ -6272,11 +6264,13 @@ func (m *ObjectMeta) Unmarshal(dAtA []byte) error {
} }
b := dAtA[iNdEx] b := dAtA[iNdEx]
iNdEx++ iNdEx++
keykey |= (uint64(b) & 0x7F) << shift wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 { if b < 0x80 {
break break
} }
} }
fieldNum := int32(wire >> 3)
if fieldNum == 1 {
var stringLenmapkey uint64 var stringLenmapkey uint64
for shift := uint(0); ; shift += 7 { for shift := uint(0); ; shift += 7 {
if shift >= 64 { if shift >= 64 {
@ -6300,27 +6294,9 @@ func (m *ObjectMeta) Unmarshal(dAtA []byte) error {
if postStringIndexmapkey > l { if postStringIndexmapkey > l {
return io.ErrUnexpectedEOF return io.ErrUnexpectedEOF
} }
mapkey := string(dAtA[iNdEx:postStringIndexmapkey]) mapkey = string(dAtA[iNdEx:postStringIndexmapkey])
iNdEx = postStringIndexmapkey iNdEx = postStringIndexmapkey
if m.Annotations == nil { } else if fieldNum == 2 {
m.Annotations = make(map[string]string)
}
if iNdEx < postIndex {
var valuekey uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenerated
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
valuekey |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
var stringLenmapvalue uint64 var stringLenmapvalue uint64
for shift := uint(0); ; shift += 7 { for shift := uint(0); ; shift += 7 {
if shift >= 64 { if shift >= 64 {
@ -6344,13 +6320,24 @@ func (m *ObjectMeta) Unmarshal(dAtA []byte) error {
if postStringIndexmapvalue > l { if postStringIndexmapvalue > l {
return io.ErrUnexpectedEOF return io.ErrUnexpectedEOF
} }
mapvalue := string(dAtA[iNdEx:postStringIndexmapvalue]) mapvalue = string(dAtA[iNdEx:postStringIndexmapvalue])
iNdEx = postStringIndexmapvalue iNdEx = postStringIndexmapvalue
m.Annotations[mapkey] = mapvalue
} else { } else {
var mapvalue string iNdEx = entryPreIndex
m.Annotations[mapkey] = mapvalue skippy, err := skipGenerated(dAtA[iNdEx:])
if err != nil {
return err
} }
if skippy < 0 {
return ErrInvalidLengthGenerated
}
if (iNdEx + skippy) > postIndex {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
m.Annotations[mapkey] = mapvalue
iNdEx = postIndex iNdEx = postIndex
case 13: case 13:
if wireType != 2 { if wireType != 2 {

View File

@ -620,8 +620,8 @@ message ObjectMeta {
} }
// OwnerReference contains enough information to let you identify an owning // OwnerReference contains enough information to let you identify an owning
// object. Currently, an owning object must be in the same namespace, so there // object. An owning object must be in the same namespace as the dependent, or
// is no namespace field. // be cluster-scoped, so there is no namespace field.
message OwnerReference { message OwnerReference {
// API version of the referent. // API version of the referent.
optional string apiVersion = 5; optional string apiVersion = 5;

View File

@ -286,8 +286,8 @@ const (
) )
// OwnerReference contains enough information to let you identify an owning // OwnerReference contains enough information to let you identify an owning
// object. Currently, an owning object must be in the same namespace, so there // object. An owning object must be in the same namespace as the dependent, or
// is no namespace field. // be cluster-scoped, so there is no namespace field.
type OwnerReference struct { type OwnerReference struct {
// API version of the referent. // API version of the referent.
APIVersion string `json:"apiVersion" protobuf:"bytes,5,opt,name=apiVersion"` APIVersion string `json:"apiVersion" protobuf:"bytes,5,opt,name=apiVersion"`

View File

@ -240,7 +240,7 @@ func (ObjectMeta) SwaggerDoc() map[string]string {
} }
var map_OwnerReference = map[string]string{ var map_OwnerReference = map[string]string{
"": "OwnerReference contains enough information to let you identify an owning object. Currently, an owning object must be in the same namespace, so there is no namespace field.", "": "OwnerReference contains enough information to let you identify an owning object. An owning object must be in the same namespace as the dependent, or be cluster-scoped, so there is no namespace field.",
"apiVersion": "API version of the referent.", "apiVersion": "API version of the referent.",
"kind": "Kind of the referent. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds", "kind": "Kind of the referent. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds",
"name": "Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names", "name": "Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names",

View File

@ -19,4 +19,5 @@ limitations under the License.
// +k8s:defaulter-gen=TypeMeta // +k8s:defaulter-gen=TypeMeta
// +groupName=meta.k8s.io // +groupName=meta.k8s.io
package v1beta1 package v1beta1

View File

@ -14,9 +14,8 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
// Code generated by protoc-gen-gogo. // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/generated.proto // source: k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/generated.proto
// DO NOT EDIT!
/* /*
Package v1beta1 is a generated protocol buffer package. Package v1beta1 is a generated protocol buffer package.
@ -148,24 +147,6 @@ func (m *TableOptions) MarshalTo(dAtA []byte) (int, error) {
return i, nil return i, nil
} }
func encodeFixed64Generated(dAtA []byte, offset int, v uint64) int {
dAtA[offset] = uint8(v)
dAtA[offset+1] = uint8(v >> 8)
dAtA[offset+2] = uint8(v >> 16)
dAtA[offset+3] = uint8(v >> 24)
dAtA[offset+4] = uint8(v >> 32)
dAtA[offset+5] = uint8(v >> 40)
dAtA[offset+6] = uint8(v >> 48)
dAtA[offset+7] = uint8(v >> 56)
return offset + 8
}
func encodeFixed32Generated(dAtA []byte, offset int, v uint32) int {
dAtA[offset] = uint8(v)
dAtA[offset+1] = uint8(v >> 8)
dAtA[offset+2] = uint8(v >> 16)
dAtA[offset+3] = uint8(v >> 24)
return offset + 4
}
func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int { func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int {
for v >= 1<<7 { for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80) dAtA[offset] = uint8(v&0x7f | 0x80)

View File

@ -23,10 +23,10 @@ import (
"strconv" "strconv"
"strings" "strings"
"github.com/golang/glog"
"k8s.io/apimachinery/pkg/selection" "k8s.io/apimachinery/pkg/selection"
"k8s.io/apimachinery/pkg/util/sets" "k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/validation" "k8s.io/apimachinery/pkg/util/validation"
"k8s.io/klog"
) )
// Requirements is AND of all requirements. // Requirements is AND of all requirements.
@ -211,13 +211,13 @@ func (r *Requirement) Matches(ls Labels) bool {
} }
lsValue, err := strconv.ParseInt(ls.Get(r.key), 10, 64) lsValue, err := strconv.ParseInt(ls.Get(r.key), 10, 64)
if err != nil { if err != nil {
glog.V(10).Infof("ParseInt failed for value %+v in label %+v, %+v", ls.Get(r.key), ls, err) klog.V(10).Infof("ParseInt failed for value %+v in label %+v, %+v", ls.Get(r.key), ls, err)
return false return false
} }
// There should be only one strValue in r.strValues, and can be converted to a integer. // There should be only one strValue in r.strValues, and can be converted to a integer.
if len(r.strValues) != 1 { if len(r.strValues) != 1 {
glog.V(10).Infof("Invalid values count %+v of requirement %#v, for 'Gt', 'Lt' operators, exactly one value is required", len(r.strValues), r) klog.V(10).Infof("Invalid values count %+v of requirement %#v, for 'Gt', 'Lt' operators, exactly one value is required", len(r.strValues), r)
return false return false
} }
@ -225,7 +225,7 @@ func (r *Requirement) Matches(ls Labels) bool {
for i := range r.strValues { for i := range r.strValues {
rValue, err = strconv.ParseInt(r.strValues[i], 10, 64) rValue, err = strconv.ParseInt(r.strValues[i], 10, 64)
if err != nil { if err != nil {
glog.V(10).Infof("ParseInt failed for value %+v in requirement %#v, for 'Gt', 'Lt' operators, the value must be an integer", r.strValues[i], r) klog.V(10).Infof("ParseInt failed for value %+v in requirement %#v, for 'Gt', 'Lt' operators, the value must be an integer", r.strValues[i], r)
return false return false
} }
} }

View File

@ -33,7 +33,7 @@ import (
"k8s.io/apimachinery/pkg/util/json" "k8s.io/apimachinery/pkg/util/json"
utilruntime "k8s.io/apimachinery/pkg/util/runtime" utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"github.com/golang/glog" "k8s.io/klog"
) )
// UnstructuredConverter is an interface for converting between interface{} // UnstructuredConverter is an interface for converting between interface{}
@ -133,10 +133,10 @@ func (c *unstructuredConverter) FromUnstructured(u map[string]interface{}, obj i
newObj := reflect.New(t.Elem()).Interface() newObj := reflect.New(t.Elem()).Interface()
newErr := fromUnstructuredViaJSON(u, newObj) newErr := fromUnstructuredViaJSON(u, newObj)
if (err != nil) != (newErr != nil) { if (err != nil) != (newErr != nil) {
glog.Fatalf("FromUnstructured unexpected error for %v: error: %v", u, err) klog.Fatalf("FromUnstructured unexpected error for %v: error: %v", u, err)
} }
if err == nil && !c.comparison.DeepEqual(obj, newObj) { if err == nil && !c.comparison.DeepEqual(obj, newObj) {
glog.Fatalf("FromUnstructured mismatch\nobj1: %#v\nobj2: %#v", obj, newObj) klog.Fatalf("FromUnstructured mismatch\nobj1: %#v\nobj2: %#v", obj, newObj)
} }
} }
return err return err
@ -424,10 +424,10 @@ func (c *unstructuredConverter) ToUnstructured(obj interface{}) (map[string]inte
newUnstr := map[string]interface{}{} newUnstr := map[string]interface{}{}
newErr := toUnstructuredViaJSON(obj, &newUnstr) newErr := toUnstructuredViaJSON(obj, &newUnstr)
if (err != nil) != (newErr != nil) { if (err != nil) != (newErr != nil) {
glog.Fatalf("ToUnstructured unexpected error for %v: error: %v; newErr: %v", obj, err, newErr) klog.Fatalf("ToUnstructured unexpected error for %v: error: %v; newErr: %v", obj, err, newErr)
} }
if err == nil && !c.comparison.DeepEqual(u, newUnstr) { if err == nil && !c.comparison.DeepEqual(u, newUnstr) {
glog.Fatalf("ToUnstructured mismatch\nobj1: %#v\nobj2: %#v", u, newUnstr) klog.Fatalf("ToUnstructured mismatch\nobj1: %#v\nobj2: %#v", u, newUnstr)
} }
} }
if err != nil { if err != nil {

View File

@ -14,9 +14,8 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
// Code generated by protoc-gen-gogo. // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/runtime/generated.proto // source: k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/runtime/generated.proto
// DO NOT EDIT!
/* /*
Package runtime is a generated protocol buffer package. Package runtime is a generated protocol buffer package.
@ -158,24 +157,6 @@ func (m *Unknown) MarshalTo(dAtA []byte) (int, error) {
return i, nil return i, nil
} }
func encodeFixed64Generated(dAtA []byte, offset int, v uint64) int {
dAtA[offset] = uint8(v)
dAtA[offset+1] = uint8(v >> 8)
dAtA[offset+2] = uint8(v >> 16)
dAtA[offset+3] = uint8(v >> 24)
dAtA[offset+4] = uint8(v >> 32)
dAtA[offset+5] = uint8(v >> 40)
dAtA[offset+6] = uint8(v >> 48)
dAtA[offset+7] = uint8(v >> 56)
return offset + 8
}
func encodeFixed32Generated(dAtA []byte, offset int, v uint32) int {
dAtA[offset] = uint8(v)
dAtA[offset+1] = uint8(v >> 8)
dAtA[offset+2] = uint8(v >> 16)
dAtA[offset+3] = uint8(v >> 24)
return offset + 4
}
func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int { func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int {
for v >= 1<<7 { for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80) dAtA[offset] = uint8(v&0x7f | 0x80)

View File

@ -14,9 +14,8 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
// Code generated by protoc-gen-gogo. // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/runtime/schema/generated.proto // source: k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/runtime/schema/generated.proto
// DO NOT EDIT!
/* /*
Package schema is a generated protocol buffer package. Package schema is a generated protocol buffer package.

View File

@ -66,7 +66,7 @@ func (gr GroupResource) Empty() bool {
return len(gr.Group) == 0 && len(gr.Resource) == 0 return len(gr.Group) == 0 && len(gr.Resource) == 0
} }
func (gr *GroupResource) String() string { func (gr GroupResource) String() string {
if len(gr.Group) == 0 { if len(gr.Group) == 0 {
return gr.Resource return gr.Resource
} }
@ -111,7 +111,7 @@ func (gvr GroupVersionResource) GroupVersion() GroupVersion {
return GroupVersion{Group: gvr.Group, Version: gvr.Version} return GroupVersion{Group: gvr.Group, Version: gvr.Version}
} }
func (gvr *GroupVersionResource) String() string { func (gvr GroupVersionResource) String() string {
return strings.Join([]string{gvr.Group, "/", gvr.Version, ", Resource=", gvr.Resource}, "") return strings.Join([]string{gvr.Group, "/", gvr.Version, ", Resource=", gvr.Resource}, "")
} }
@ -130,7 +130,7 @@ func (gk GroupKind) WithVersion(version string) GroupVersionKind {
return GroupVersionKind{Group: gk.Group, Version: version, Kind: gk.Kind} return GroupVersionKind{Group: gk.Group, Version: version, Kind: gk.Kind}
} }
func (gk *GroupKind) String() string { func (gk GroupKind) String() string {
if len(gk.Group) == 0 { if len(gk.Group) == 0 {
return gk.Kind return gk.Kind
} }
@ -281,8 +281,8 @@ func bestMatch(kinds []GroupVersionKind, targets []GroupVersionKind) GroupVersio
// ToAPIVersionAndKind is a convenience method for satisfying runtime.Object on types that // ToAPIVersionAndKind is a convenience method for satisfying runtime.Object on types that
// do not use TypeMeta. // do not use TypeMeta.
func (gvk *GroupVersionKind) ToAPIVersionAndKind() (string, string) { func (gvk GroupVersionKind) ToAPIVersionAndKind() (string, string) {
if gvk == nil { if gvk.Empty() {
return "", "" return "", ""
} }
return gvk.GroupVersion().String(), gvk.Kind return gvk.GroupVersion().String(), gvk.Kind

View File

@ -22,9 +22,9 @@ import (
"strconv" "strconv"
"unsafe" "unsafe"
"github.com/ghodss/yaml"
jsoniter "github.com/json-iterator/go" jsoniter "github.com/json-iterator/go"
"github.com/modern-go/reflect2" "github.com/modern-go/reflect2"
"sigs.k8s.io/yaml"
"k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/runtime/schema"

View File

@ -18,6 +18,7 @@ package versioning
import ( import (
"io" "io"
"reflect"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime"
@ -90,7 +91,16 @@ func (c *codec) Decode(data []byte, defaultGVK *schema.GroupVersionKind, into ru
into = versioned.Last() into = versioned.Last()
} }
obj, gvk, err := c.decoder.Decode(data, defaultGVK, into) // If the into object is unstructured and expresses an opinion about its group/version,
// create a new instance of the type so we always exercise the conversion path (skips short-circuiting on `into == obj`)
decodeInto := into
if into != nil {
if _, ok := into.(runtime.Unstructured); ok && !into.GetObjectKind().GroupVersionKind().GroupVersion().Empty() {
decodeInto = reflect.New(reflect.TypeOf(into).Elem()).Interface().(runtime.Object)
}
}
obj, gvk, err := c.decoder.Decode(data, defaultGVK, decodeInto)
if err != nil { if err != nil {
return nil, gvk, err return nil, gvk, err
} }

View File

@ -136,12 +136,12 @@ func Handshake(req *http.Request, w http.ResponseWriter, serverProtocols []strin
negotiatedProtocol := negotiateProtocol(clientProtocols, serverProtocols) negotiatedProtocol := negotiateProtocol(clientProtocols, serverProtocols)
if len(negotiatedProtocol) == 0 { if len(negotiatedProtocol) == 0 {
w.WriteHeader(http.StatusForbidden)
for i := range serverProtocols { for i := range serverProtocols {
w.Header().Add(HeaderAcceptedProtocolVersions, serverProtocols[i]) w.Header().Add(HeaderAcceptedProtocolVersions, serverProtocols[i])
} }
fmt.Fprintf(w, "unable to upgrade: unable to negotiate protocol: client supports %v, server accepts %v", clientProtocols, serverProtocols) err := fmt.Errorf("unable to upgrade: unable to negotiate protocol: client supports %v, server accepts %v", clientProtocols, serverProtocols)
return "", fmt.Errorf("unable to upgrade: unable to negotiate protocol: client supports %v, server supports %v", clientProtocols, serverProtocols) http.Error(w, err.Error(), http.StatusForbidden)
return "", err
} }
w.Header().Add(HeaderProtocolVersion, negotiatedProtocol) w.Header().Add(HeaderProtocolVersion, negotiatedProtocol)

View File

@ -23,8 +23,8 @@ import (
"time" "time"
"github.com/docker/spdystream" "github.com/docker/spdystream"
"github.com/golang/glog"
"k8s.io/apimachinery/pkg/util/httpstream" "k8s.io/apimachinery/pkg/util/httpstream"
"k8s.io/klog"
) )
// connection maintains state about a spdystream.Connection and its associated // connection maintains state about a spdystream.Connection and its associated
@ -128,7 +128,7 @@ func (c *connection) newSpdyStream(stream *spdystream.Stream) {
err := c.newStreamHandler(stream, replySent) err := c.newStreamHandler(stream, replySent)
rejectStream := (err != nil) rejectStream := (err != nil)
if rejectStream { if rejectStream {
glog.Warningf("Stream rejected: %v", err) klog.Warningf("Stream rejected: %v", err)
stream.Reset() stream.Reset()
return return
} }

View File

@ -67,6 +67,9 @@ type SpdyRoundTripper struct {
// followRedirects indicates if the round tripper should examine responses for redirects and // followRedirects indicates if the round tripper should examine responses for redirects and
// follow them. // follow them.
followRedirects bool followRedirects bool
// requireSameHostRedirects restricts redirect following to only follow redirects to the same host
// as the original request.
requireSameHostRedirects bool
} }
var _ utilnet.TLSClientConfigHolder = &SpdyRoundTripper{} var _ utilnet.TLSClientConfigHolder = &SpdyRoundTripper{}
@ -75,14 +78,18 @@ var _ utilnet.Dialer = &SpdyRoundTripper{}
// NewRoundTripper creates a new SpdyRoundTripper that will use // NewRoundTripper creates a new SpdyRoundTripper that will use
// the specified tlsConfig. // the specified tlsConfig.
func NewRoundTripper(tlsConfig *tls.Config, followRedirects bool) httpstream.UpgradeRoundTripper { func NewRoundTripper(tlsConfig *tls.Config, followRedirects, requireSameHostRedirects bool) httpstream.UpgradeRoundTripper {
return NewSpdyRoundTripper(tlsConfig, followRedirects) return NewSpdyRoundTripper(tlsConfig, followRedirects, requireSameHostRedirects)
} }
// NewSpdyRoundTripper creates a new SpdyRoundTripper that will use // NewSpdyRoundTripper creates a new SpdyRoundTripper that will use
// the specified tlsConfig. This function is mostly meant for unit tests. // the specified tlsConfig. This function is mostly meant for unit tests.
func NewSpdyRoundTripper(tlsConfig *tls.Config, followRedirects bool) *SpdyRoundTripper { func NewSpdyRoundTripper(tlsConfig *tls.Config, followRedirects, requireSameHostRedirects bool) *SpdyRoundTripper {
return &SpdyRoundTripper{tlsConfig: tlsConfig, followRedirects: followRedirects} return &SpdyRoundTripper{
tlsConfig: tlsConfig,
followRedirects: followRedirects,
requireSameHostRedirects: requireSameHostRedirects,
}
} }
// TLSClientConfig implements pkg/util/net.TLSClientConfigHolder for proper TLS checking during // TLSClientConfig implements pkg/util/net.TLSClientConfigHolder for proper TLS checking during
@ -257,7 +264,7 @@ func (s *SpdyRoundTripper) RoundTrip(req *http.Request) (*http.Response, error)
) )
if s.followRedirects { if s.followRedirects {
conn, rawResponse, err = utilnet.ConnectWithRedirects(req.Method, req.URL, header, req.Body, s) conn, rawResponse, err = utilnet.ConnectWithRedirects(req.Method, req.URL, header, req.Body, s, s.requireSameHostRedirects)
} else { } else {
clone := utilnet.CloneRequest(req) clone := utilnet.CloneRequest(req)
clone.Header = header clone.Header = header

View File

@ -74,15 +74,15 @@ func (u responseUpgrader) UpgradeResponse(w http.ResponseWriter, req *http.Reque
connectionHeader := strings.ToLower(req.Header.Get(httpstream.HeaderConnection)) connectionHeader := strings.ToLower(req.Header.Get(httpstream.HeaderConnection))
upgradeHeader := strings.ToLower(req.Header.Get(httpstream.HeaderUpgrade)) upgradeHeader := strings.ToLower(req.Header.Get(httpstream.HeaderUpgrade))
if !strings.Contains(connectionHeader, strings.ToLower(httpstream.HeaderUpgrade)) || !strings.Contains(upgradeHeader, strings.ToLower(HeaderSpdy31)) { if !strings.Contains(connectionHeader, strings.ToLower(httpstream.HeaderUpgrade)) || !strings.Contains(upgradeHeader, strings.ToLower(HeaderSpdy31)) {
w.WriteHeader(http.StatusBadRequest) errorMsg := fmt.Sprintf("unable to upgrade: missing upgrade headers in request: %#v", req.Header)
fmt.Fprintf(w, "unable to upgrade: missing upgrade headers in request: %#v", req.Header) http.Error(w, errorMsg, http.StatusBadRequest)
return nil return nil
} }
hijacker, ok := w.(http.Hijacker) hijacker, ok := w.(http.Hijacker)
if !ok { if !ok {
w.WriteHeader(http.StatusInternalServerError) errorMsg := fmt.Sprintf("unable to upgrade: unable to hijack response")
fmt.Fprintf(w, "unable to upgrade: unable to hijack response") http.Error(w, errorMsg, http.StatusInternalServerError)
return nil return nil
} }

View File

@ -14,9 +14,8 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
// Code generated by protoc-gen-gogo. // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/util/intstr/generated.proto // source: k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/util/intstr/generated.proto
// DO NOT EDIT!
/* /*
Package intstr is a generated protocol buffer package. Package intstr is a generated protocol buffer package.
@ -81,24 +80,6 @@ func (m *IntOrString) MarshalTo(dAtA []byte) (int, error) {
return i, nil return i, nil
} }
func encodeFixed64Generated(dAtA []byte, offset int, v uint64) int {
dAtA[offset] = uint8(v)
dAtA[offset+1] = uint8(v >> 8)
dAtA[offset+2] = uint8(v >> 16)
dAtA[offset+3] = uint8(v >> 24)
dAtA[offset+4] = uint8(v >> 32)
dAtA[offset+5] = uint8(v >> 40)
dAtA[offset+6] = uint8(v >> 48)
dAtA[offset+7] = uint8(v >> 56)
return offset + 8
}
func encodeFixed32Generated(dAtA []byte, offset int, v uint32) int {
dAtA[offset] = uint8(v)
dAtA[offset+1] = uint8(v >> 8)
dAtA[offset+2] = uint8(v >> 16)
dAtA[offset+3] = uint8(v >> 24)
return offset + 4
}
func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int { func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int {
for v >= 1<<7 { for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80) dAtA[offset] = uint8(v&0x7f | 0x80)

View File

@ -25,8 +25,8 @@ import (
"strconv" "strconv"
"strings" "strings"
"github.com/golang/glog"
"github.com/google/gofuzz" "github.com/google/gofuzz"
"k8s.io/klog"
) )
// IntOrString is a type that can hold an int32 or a string. When used in // IntOrString is a type that can hold an int32 or a string. When used in
@ -58,7 +58,7 @@ const (
// TODO: convert to (val int32) // TODO: convert to (val int32)
func FromInt(val int) IntOrString { func FromInt(val int) IntOrString {
if val > math.MaxInt32 || val < math.MinInt32 { if val > math.MaxInt32 || val < math.MinInt32 {
glog.Errorf("value: %d overflows int32\n%s\n", val, debug.Stack()) klog.Errorf("value: %d overflows int32\n%s\n", val, debug.Stack())
} }
return IntOrString{Type: Int, IntVal: int32(val)} return IntOrString{Type: Int, IntVal: int32(val)}
} }

View File

@ -31,8 +31,8 @@ import (
"strconv" "strconv"
"strings" "strings"
"github.com/golang/glog"
"golang.org/x/net/http2" "golang.org/x/net/http2"
"k8s.io/klog"
) )
// JoinPreservingTrailingSlash does a path.Join of the specified elements, // JoinPreservingTrailingSlash does a path.Join of the specified elements,
@ -107,10 +107,10 @@ func SetTransportDefaults(t *http.Transport) *http.Transport {
t = SetOldTransportDefaults(t) t = SetOldTransportDefaults(t)
// Allow clients to disable http2 if needed. // Allow clients to disable http2 if needed.
if s := os.Getenv("DISABLE_HTTP2"); len(s) > 0 { if s := os.Getenv("DISABLE_HTTP2"); len(s) > 0 {
glog.Infof("HTTP2 has been explicitly disabled") klog.Infof("HTTP2 has been explicitly disabled")
} else { } else {
if err := http2.ConfigureTransport(t); err != nil { if err := http2.ConfigureTransport(t); err != nil {
glog.Warningf("Transport failed http2 configuration: %v", err) klog.Warningf("Transport failed http2 configuration: %v", err)
} }
} }
return t return t
@ -321,9 +321,10 @@ type Dialer interface {
// ConnectWithRedirects uses dialer to send req, following up to 10 redirects (relative to // ConnectWithRedirects uses dialer to send req, following up to 10 redirects (relative to
// originalLocation). It returns the opened net.Conn and the raw response bytes. // originalLocation). It returns the opened net.Conn and the raw response bytes.
func ConnectWithRedirects(originalMethod string, originalLocation *url.URL, header http.Header, originalBody io.Reader, dialer Dialer) (net.Conn, []byte, error) { // If requireSameHostRedirects is true, only redirects to the same host are permitted.
func ConnectWithRedirects(originalMethod string, originalLocation *url.URL, header http.Header, originalBody io.Reader, dialer Dialer, requireSameHostRedirects bool) (net.Conn, []byte, error) {
const ( const (
maxRedirects = 10 maxRedirects = 9 // Fail on the 10th redirect
maxResponseSize = 16384 // play it safe to allow the potential for lots of / large headers maxResponseSize = 16384 // play it safe to allow the potential for lots of / large headers
) )
@ -367,7 +368,7 @@ redirectLoop:
resp, err := http.ReadResponse(respReader, nil) resp, err := http.ReadResponse(respReader, nil)
if err != nil { if err != nil {
// Unable to read the backend response; let the client handle it. // Unable to read the backend response; let the client handle it.
glog.Warningf("Error reading backend response: %v", err) klog.Warningf("Error reading backend response: %v", err)
break redirectLoop break redirectLoop
} }
@ -387,10 +388,6 @@ redirectLoop:
resp.Body.Close() // not used resp.Body.Close() // not used
// Reset the connection.
intermediateConn.Close()
intermediateConn = nil
// Prepare to follow the redirect. // Prepare to follow the redirect.
redirectStr := resp.Header.Get("Location") redirectStr := resp.Header.Get("Location")
if redirectStr == "" { if redirectStr == "" {
@ -404,6 +401,15 @@ redirectLoop:
if err != nil { if err != nil {
return nil, nil, fmt.Errorf("malformed Location header: %v", err) return nil, nil, fmt.Errorf("malformed Location header: %v", err)
} }
// Only follow redirects to the same host. Otherwise, propagate the redirect response back.
if requireSameHostRedirects && location.Hostname() != originalLocation.Hostname() {
break redirectLoop
}
// Reset the connection.
intermediateConn.Close()
intermediateConn = nil
} }
connToReturn := intermediateConn connToReturn := intermediateConn

View File

@ -26,7 +26,7 @@ import (
"strings" "strings"
"github.com/golang/glog" "k8s.io/klog"
) )
type AddressFamily uint type AddressFamily uint
@ -193,7 +193,7 @@ func isInterfaceUp(intf *net.Interface) bool {
return false return false
} }
if intf.Flags&net.FlagUp != 0 { if intf.Flags&net.FlagUp != 0 {
glog.V(4).Infof("Interface %v is up", intf.Name) klog.V(4).Infof("Interface %v is up", intf.Name)
return true return true
} }
return false return false
@ -208,20 +208,20 @@ func isLoopbackOrPointToPoint(intf *net.Interface) bool {
func getMatchingGlobalIP(addrs []net.Addr, family AddressFamily) (net.IP, error) { func getMatchingGlobalIP(addrs []net.Addr, family AddressFamily) (net.IP, error) {
if len(addrs) > 0 { if len(addrs) > 0 {
for i := range addrs { for i := range addrs {
glog.V(4).Infof("Checking addr %s.", addrs[i].String()) klog.V(4).Infof("Checking addr %s.", addrs[i].String())
ip, _, err := net.ParseCIDR(addrs[i].String()) ip, _, err := net.ParseCIDR(addrs[i].String())
if err != nil { if err != nil {
return nil, err return nil, err
} }
if memberOf(ip, family) { if memberOf(ip, family) {
if ip.IsGlobalUnicast() { if ip.IsGlobalUnicast() {
glog.V(4).Infof("IP found %v", ip) klog.V(4).Infof("IP found %v", ip)
return ip, nil return ip, nil
} else { } else {
glog.V(4).Infof("Non-global unicast address found %v", ip) klog.V(4).Infof("Non-global unicast address found %v", ip)
} }
} else { } else {
glog.V(4).Infof("%v is not an IPv%d address", ip, int(family)) klog.V(4).Infof("%v is not an IPv%d address", ip, int(family))
} }
} }
@ -241,13 +241,13 @@ func getIPFromInterface(intfName string, forFamily AddressFamily, nw networkInte
if err != nil { if err != nil {
return nil, err return nil, err
} }
glog.V(4).Infof("Interface %q has %d addresses :%v.", intfName, len(addrs), addrs) klog.V(4).Infof("Interface %q has %d addresses :%v.", intfName, len(addrs), addrs)
matchingIP, err := getMatchingGlobalIP(addrs, forFamily) matchingIP, err := getMatchingGlobalIP(addrs, forFamily)
if err != nil { if err != nil {
return nil, err return nil, err
} }
if matchingIP != nil { if matchingIP != nil {
glog.V(4).Infof("Found valid IPv%d address %v for interface %q.", int(forFamily), matchingIP, intfName) klog.V(4).Infof("Found valid IPv%d address %v for interface %q.", int(forFamily), matchingIP, intfName)
return matchingIP, nil return matchingIP, nil
} }
} }
@ -275,14 +275,14 @@ func chooseIPFromHostInterfaces(nw networkInterfacer) (net.IP, error) {
return nil, fmt.Errorf("no interfaces found on host.") return nil, fmt.Errorf("no interfaces found on host.")
} }
for _, family := range []AddressFamily{familyIPv4, familyIPv6} { for _, family := range []AddressFamily{familyIPv4, familyIPv6} {
glog.V(4).Infof("Looking for system interface with a global IPv%d address", uint(family)) klog.V(4).Infof("Looking for system interface with a global IPv%d address", uint(family))
for _, intf := range intfs { for _, intf := range intfs {
if !isInterfaceUp(&intf) { if !isInterfaceUp(&intf) {
glog.V(4).Infof("Skipping: down interface %q", intf.Name) klog.V(4).Infof("Skipping: down interface %q", intf.Name)
continue continue
} }
if isLoopbackOrPointToPoint(&intf) { if isLoopbackOrPointToPoint(&intf) {
glog.V(4).Infof("Skipping: LB or P2P interface %q", intf.Name) klog.V(4).Infof("Skipping: LB or P2P interface %q", intf.Name)
continue continue
} }
addrs, err := nw.Addrs(&intf) addrs, err := nw.Addrs(&intf)
@ -290,7 +290,7 @@ func chooseIPFromHostInterfaces(nw networkInterfacer) (net.IP, error) {
return nil, err return nil, err
} }
if len(addrs) == 0 { if len(addrs) == 0 {
glog.V(4).Infof("Skipping: no addresses on interface %q", intf.Name) klog.V(4).Infof("Skipping: no addresses on interface %q", intf.Name)
continue continue
} }
for _, addr := range addrs { for _, addr := range addrs {
@ -299,15 +299,15 @@ func chooseIPFromHostInterfaces(nw networkInterfacer) (net.IP, error) {
return nil, fmt.Errorf("Unable to parse CIDR for interface %q: %s", intf.Name, err) return nil, fmt.Errorf("Unable to parse CIDR for interface %q: %s", intf.Name, err)
} }
if !memberOf(ip, family) { if !memberOf(ip, family) {
glog.V(4).Infof("Skipping: no address family match for %q on interface %q.", ip, intf.Name) klog.V(4).Infof("Skipping: no address family match for %q on interface %q.", ip, intf.Name)
continue continue
} }
// TODO: Decide if should open up to allow IPv6 LLAs in future. // TODO: Decide if should open up to allow IPv6 LLAs in future.
if !ip.IsGlobalUnicast() { if !ip.IsGlobalUnicast() {
glog.V(4).Infof("Skipping: non-global address %q on interface %q.", ip, intf.Name) klog.V(4).Infof("Skipping: non-global address %q on interface %q.", ip, intf.Name)
continue continue
} }
glog.V(4).Infof("Found global unicast address %q on interface %q.", ip, intf.Name) klog.V(4).Infof("Found global unicast address %q on interface %q.", ip, intf.Name)
return ip, nil return ip, nil
} }
} }
@ -381,23 +381,23 @@ func getAllDefaultRoutes() ([]Route, error) {
// an IPv4 IP, and then will look at each IPv6 route for an IPv6 IP. // an IPv4 IP, and then will look at each IPv6 route for an IPv6 IP.
func chooseHostInterfaceFromRoute(routes []Route, nw networkInterfacer) (net.IP, error) { func chooseHostInterfaceFromRoute(routes []Route, nw networkInterfacer) (net.IP, error) {
for _, family := range []AddressFamily{familyIPv4, familyIPv6} { for _, family := range []AddressFamily{familyIPv4, familyIPv6} {
glog.V(4).Infof("Looking for default routes with IPv%d addresses", uint(family)) klog.V(4).Infof("Looking for default routes with IPv%d addresses", uint(family))
for _, route := range routes { for _, route := range routes {
if route.Family != family { if route.Family != family {
continue continue
} }
glog.V(4).Infof("Default route transits interface %q", route.Interface) klog.V(4).Infof("Default route transits interface %q", route.Interface)
finalIP, err := getIPFromInterface(route.Interface, family, nw) finalIP, err := getIPFromInterface(route.Interface, family, nw)
if err != nil { if err != nil {
return nil, err return nil, err
} }
if finalIP != nil { if finalIP != nil {
glog.V(4).Infof("Found active IP %v ", finalIP) klog.V(4).Infof("Found active IP %v ", finalIP)
return finalIP, nil return finalIP, nil
} }
} }
} }
glog.V(4).Infof("No active IP found by looking at default routes") klog.V(4).Infof("No active IP found by looking at default routes")
return nil, fmt.Errorf("unable to select an IP from default routes.") return nil, fmt.Errorf("unable to select an IP from default routes.")
} }

View File

@ -22,7 +22,7 @@ import (
"sync" "sync"
"time" "time"
"github.com/golang/glog" "k8s.io/klog"
) )
var ( var (
@ -63,7 +63,11 @@ func HandleCrash(additionalHandlers ...func(interface{})) {
// logPanic logs the caller tree when a panic occurs. // logPanic logs the caller tree when a panic occurs.
func logPanic(r interface{}) { func logPanic(r interface{}) {
callers := getCallers(r) callers := getCallers(r)
glog.Errorf("Observed a panic: %#v (%v)\n%v", r, r, callers) if _, ok := r.(string); ok {
klog.Errorf("Observed a panic: %s\n%v", r, callers)
} else {
klog.Errorf("Observed a panic: %#v (%v)\n%v", r, r, callers)
}
} }
func getCallers(r interface{}) string { func getCallers(r interface{}) string {
@ -111,7 +115,7 @@ func HandleError(err error) {
// logError prints an error with the call stack of the location it was reported // logError prints an error with the call stack of the location it was reported
func logError(err error) { func logError(err error) {
glog.ErrorDepth(2, err) klog.ErrorDepth(2, err)
} }
type rudimentaryErrorBackoff struct { type rudimentaryErrorBackoff struct {

View File

@ -26,8 +26,8 @@ import (
"strings" "strings"
"unicode" "unicode"
"github.com/ghodss/yaml" "k8s.io/klog"
"github.com/golang/glog" "sigs.k8s.io/yaml"
) )
// ToJSON converts a single YAML document into a JSON document // ToJSON converts a single YAML document into a JSON document
@ -217,11 +217,11 @@ func (d *YAMLOrJSONDecoder) Decode(into interface{}) error {
if d.decoder == nil { if d.decoder == nil {
buffer, origData, isJSON := GuessJSONStream(d.r, d.bufferSize) buffer, origData, isJSON := GuessJSONStream(d.r, d.bufferSize)
if isJSON { if isJSON {
glog.V(4).Infof("decoding stream as JSON") klog.V(4).Infof("decoding stream as JSON")
d.decoder = json.NewDecoder(buffer) d.decoder = json.NewDecoder(buffer)
d.rawData = origData d.rawData = origData
} else { } else {
glog.V(4).Infof("decoding stream as YAML") klog.V(4).Infof("decoding stream as YAML")
d.decoder = NewYAMLToJSONDecoder(buffer) d.decoder = NewYAMLToJSONDecoder(buffer)
} }
} }
@ -230,7 +230,7 @@ func (d *YAMLOrJSONDecoder) Decode(into interface{}) error {
if syntax, ok := err.(*json.SyntaxError); ok { if syntax, ok := err.(*json.SyntaxError); ok {
data, readErr := ioutil.ReadAll(jsonDecoder.Buffered()) data, readErr := ioutil.ReadAll(jsonDecoder.Buffered())
if readErr != nil { if readErr != nil {
glog.V(4).Infof("reading stream failed: %v", readErr) klog.V(4).Infof("reading stream failed: %v", readErr)
} }
js := string(data) js := string(data)

View File

@ -14,6 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
// Package version supplies the type for version information collected at build time.
// +k8s:openapi-gen=true // +k8s:openapi-gen=true
// Package version supplies the type for version information collected at build time.
package version // import "k8s.io/apimachinery/pkg/version" package version // import "k8s.io/apimachinery/pkg/version"

View File

@ -20,10 +20,10 @@ import (
"io" "io"
"sync" "sync"
"github.com/golang/glog"
"k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/net" "k8s.io/apimachinery/pkg/util/net"
utilruntime "k8s.io/apimachinery/pkg/util/runtime" utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/klog"
) )
// Decoder allows StreamWatcher to watch any stream for which a Decoder can be written. // Decoder allows StreamWatcher to watch any stream for which a Decoder can be written.
@ -100,13 +100,13 @@ func (sw *StreamWatcher) receive() {
case io.EOF: case io.EOF:
// watch closed normally // watch closed normally
case io.ErrUnexpectedEOF: case io.ErrUnexpectedEOF:
glog.V(1).Infof("Unexpected EOF during watch stream event decoding: %v", err) klog.V(1).Infof("Unexpected EOF during watch stream event decoding: %v", err)
default: default:
msg := "Unable to decode an event from the watch stream: %v" msg := "Unable to decode an event from the watch stream: %v"
if net.IsProbableEOF(err) { if net.IsProbableEOF(err) {
glog.V(5).Infof(msg, err) klog.V(5).Infof(msg, err)
} else { } else {
glog.Errorf(msg, err) klog.Errorf(msg, err)
} }
} }
return return

View File

@ -20,7 +20,7 @@ import (
"fmt" "fmt"
"sync" "sync"
"github.com/golang/glog" "k8s.io/klog"
"k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime"
) )
@ -106,7 +106,7 @@ func (f *FakeWatcher) Stop() {
f.Lock() f.Lock()
defer f.Unlock() defer f.Unlock()
if !f.Stopped { if !f.Stopped {
glog.V(4).Infof("Stopping fake watcher.") klog.V(4).Infof("Stopping fake watcher.")
close(f.result) close(f.result)
f.Stopped = true f.Stopped = true
} }
@ -173,7 +173,7 @@ func (f *RaceFreeFakeWatcher) Stop() {
f.Lock() f.Lock()
defer f.Unlock() defer f.Unlock()
if !f.Stopped { if !f.Stopped {
glog.V(4).Infof("Stopping fake watcher.") klog.V(4).Infof("Stopping fake watcher.")
close(f.result) close(f.result)
f.Stopped = true f.Stopped = true
} }

View File

@ -24,7 +24,7 @@ import (
"runtime" "runtime"
"time" "time"
"github.com/golang/glog" "k8s.io/klog"
) )
// StacktracePred returns true if a stacktrace should be logged for this status. // StacktracePred returns true if a stacktrace should be logged for this status.
@ -61,7 +61,7 @@ type passthroughLogger struct{}
// Addf logs info immediately. // Addf logs info immediately.
func (passthroughLogger) Addf(format string, data ...interface{}) { func (passthroughLogger) Addf(format string, data ...interface{}) {
glog.V(2).Info(fmt.Sprintf(format, data...)) klog.V(2).Info(fmt.Sprintf(format, data...))
} }
// DefaultStacktracePred is the default implementation of StacktracePred. // DefaultStacktracePred is the default implementation of StacktracePred.
@ -143,11 +143,11 @@ func (rl *respLogger) Addf(format string, data ...interface{}) {
// Log is intended to be called once at the end of your request handler, via defer // Log is intended to be called once at the end of your request handler, via defer
func (rl *respLogger) Log() { func (rl *respLogger) Log() {
latency := time.Since(rl.startTime) latency := time.Since(rl.startTime)
if glog.V(3) { if klog.V(3) {
if !rl.hijacked { if !rl.hijacked {
glog.InfoDepth(1, fmt.Sprintf("%s %s: (%v) %v%v%v [%s %s]", rl.req.Method, rl.req.RequestURI, latency, rl.status, rl.statusStack, rl.addedInfo, rl.req.UserAgent(), rl.req.RemoteAddr)) klog.InfoDepth(1, fmt.Sprintf("%s %s: (%v) %v%v%v [%s %s]", rl.req.Method, rl.req.RequestURI, latency, rl.status, rl.statusStack, rl.addedInfo, rl.req.UserAgent(), rl.req.RemoteAddr))
} else { } else {
glog.InfoDepth(1, fmt.Sprintf("%s %s: (%v) hijacked [%s %s]", rl.req.Method, rl.req.RequestURI, latency, rl.req.UserAgent(), rl.req.RemoteAddr)) klog.InfoDepth(1, fmt.Sprintf("%s %s: (%v) hijacked [%s %s]", rl.req.Method, rl.req.RequestURI, latency, rl.req.UserAgent(), rl.req.RemoteAddr))
} }
} }
} }
@ -173,8 +173,8 @@ func (rl *respLogger) Write(b []byte) (int, error) {
func (rl *respLogger) Flush() { func (rl *respLogger) Flush() {
if flusher, ok := rl.w.(http.Flusher); ok { if flusher, ok := rl.w.(http.Flusher); ok {
flusher.Flush() flusher.Flush()
} else if glog.V(2) { } else if klog.V(2) {
glog.InfoDepth(1, fmt.Sprintf("Unable to convert %+v into http.Flusher", rl.w)) klog.InfoDepth(1, fmt.Sprintf("Unable to convert %+v into http.Flusher", rl.w))
} }
} }

View File

@ -25,8 +25,8 @@ import (
"strings" "strings"
"time" "time"
"github.com/golang/glog"
"golang.org/x/net/websocket" "golang.org/x/net/websocket"
"k8s.io/klog"
"k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/util/runtime"
) )
@ -251,7 +251,7 @@ func (conn *Conn) handle(ws *websocket.Conn) {
var data []byte var data []byte
if err := websocket.Message.Receive(ws, &data); err != nil { if err := websocket.Message.Receive(ws, &data); err != nil {
if err != io.EOF { if err != io.EOF {
glog.Errorf("Error on socket receive: %v", err) klog.Errorf("Error on socket receive: %v", err)
} }
break break
} }
@ -264,11 +264,11 @@ func (conn *Conn) handle(ws *websocket.Conn) {
} }
data = data[1:] data = data[1:]
if int(channel) >= len(conn.channels) { if int(channel) >= len(conn.channels) {
glog.V(6).Infof("Frame is targeted for a reader %d that is not valid, possible protocol error", channel) klog.V(6).Infof("Frame is targeted for a reader %d that is not valid, possible protocol error", channel)
continue continue
} }
if _, err := conn.channels[channel].DataFromSocket(data); err != nil { if _, err := conn.channels[channel].DataFromSocket(data); err != nil {
glog.Errorf("Unable to write frame to %d: %v\n%s", channel, err, string(data)) klog.Errorf("Unable to write frame to %d: %v\n%s", channel, err, string(data))
continue continue
} }
} }

24
vendor/k8s.io/client-go/README.md generated vendored
View File

@ -2,7 +2,7 @@
Go clients for talking to a [kubernetes](http://kubernetes.io/) cluster. Go clients for talking to a [kubernetes](http://kubernetes.io/) cluster.
We currently recommend using the v8.0.0 tag. See [INSTALL.md](/INSTALL.md) for We currently recommend using the v9.0.0 tag. See [INSTALL.md](/INSTALL.md) for
detailed installation instructions. `go get k8s.io/client-go/...` works, but detailed installation instructions. `go get k8s.io/client-go/...` works, but
will build `master`, which doesn't handle the dependencies well. will build `master`, which doesn't handle the dependencies well.
@ -91,16 +91,15 @@ We will backport bugfixes--but not new features--into older versions of
#### Compatibility matrix #### Compatibility matrix
| | Kubernetes 1.5 | Kubernetes 1.6 | Kubernetes 1.7 | Kubernetes 1.8 | Kubernetes 1.9 | Kubernetes 1.10 | Kubernetes 1.11 | | | Kubernetes 1.6 | Kubernetes 1.7 | Kubernetes 1.8 | Kubernetes 1.9 | Kubernetes 1.10 | Kubernetes 1.11 | Kubernetes 1.12 |
|---------------------|----------------|----------------|----------------|----------------|----------------|-----------------|-----------------| |---------------------|----------------|----------------|----------------|----------------|-----------------|-----------------|-----------------|
| client-go 1.5 | - | - | - | - | - | - | - | | client-go 3.0 | ✓ | - | +- | +- | +- | +- | +- |
| client-go 2.0 | ✓ | +- | +- | +- | +- | +- | +- | | client-go 4.0 | +- | ✓ | +- | +- | +- | +- | +- |
| client-go 3.0 | +- | ✓ | - | +- | +- | +- | +- | | client-go 5.0 | +- | +- | ✓ | +- | +- | +- | +- |
| client-go 4.0 | +- | +- | ✓ | +- | +- | +- | +- | | client-go 6.0 | +- | +- | +- | ✓ | +- | +- | +- |
| client-go 5.0 | +- | +- | +- | ✓ | +- | +- | +- | | client-go 7.0 | +- | +- | +- | +- | ✓ | +- | +- |
| client-go 6.0 | +- | +- | +- | +- | ✓ | +- | +- | | client-go 8.0 | +- | +- | +- | +- | +- | ✓ | +- |
| client-go 7.0 | +- | +- | +- | +- | +- | ✓ | +- | | client-go 9.0 | +- | +- | +- | +- | +- | +- | ✓ |
| client-go 8.0 | +- | +- | +- | +- | +- | +- | ✓ |
| client-go HEAD | +- | +- | +- | +- | +- | +- | +- | | client-go HEAD | +- | +- | +- | +- | +- | +- | +- |
Key: Key:
@ -128,9 +127,10 @@ between client-go versions.
| client-go 3.0 | Kubernetes main repo, 1.6 branch | = - | | client-go 3.0 | Kubernetes main repo, 1.6 branch | = - |
| client-go 4.0 | Kubernetes main repo, 1.7 branch | = - | | client-go 4.0 | Kubernetes main repo, 1.7 branch | = - |
| client-go 5.0 | Kubernetes main repo, 1.8 branch | = - | | client-go 5.0 | Kubernetes main repo, 1.8 branch | = - |
| client-go 6.0 | Kubernetes main repo, 1.9 branch | | | client-go 6.0 | Kubernetes main repo, 1.9 branch | = - |
| client-go 7.0 | Kubernetes main repo, 1.10 branch | ✓ | | client-go 7.0 | Kubernetes main repo, 1.10 branch | ✓ |
| client-go 8.0 | Kubernetes main repo, 1.11 branch | ✓ | | client-go 8.0 | Kubernetes main repo, 1.11 branch | ✓ |
| client-go 9.0 | Kubernetes main repo, 1.12 branch | ✓ |
| client-go HEAD | Kubernetes main repo, master branch | ✓ | | client-go HEAD | Kubernetes main repo, master branch | ✓ |
Key: Key:

View File

@ -16,4 +16,5 @@ limitations under the License.
// +k8s:deepcopy-gen=package // +k8s:deepcopy-gen=package
// +groupName=client.authentication.k8s.io // +groupName=client.authentication.k8s.io
package clientauthentication // import "k8s.io/client-go/pkg/apis/clientauthentication" package clientauthentication // import "k8s.io/client-go/pkg/apis/clientauthentication"

View File

@ -20,4 +20,5 @@ limitations under the License.
// +k8s:defaulter-gen=TypeMeta // +k8s:defaulter-gen=TypeMeta
// +groupName=client.authentication.k8s.io // +groupName=client.authentication.k8s.io
package v1alpha1 // import "k8s.io/client-go/pkg/apis/clientauthentication/v1alpha1" package v1alpha1 // import "k8s.io/client-go/pkg/apis/clientauthentication/v1alpha1"

View File

@ -20,4 +20,5 @@ limitations under the License.
// +k8s:defaulter-gen=TypeMeta // +k8s:defaulter-gen=TypeMeta
// +groupName=client.authentication.k8s.io // +groupName=client.authentication.k8s.io
package v1beta1 // import "k8s.io/client-go/pkg/apis/clientauthentication/v1beta1" package v1beta1 // import "k8s.io/client-go/pkg/apis/clientauthentication/v1beta1"

View File

@ -14,7 +14,8 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
// +k8s:openapi-gen=true
// Package version supplies version information collected at build time to // Package version supplies version information collected at build time to
// kubernetes components. // kubernetes components.
// +k8s:openapi-gen=true
package version // import "k8s.io/client-go/pkg/version" package version // import "k8s.io/client-go/pkg/version"

View File

@ -31,7 +31,6 @@ import (
"sync" "sync"
"time" "time"
"github.com/golang/glog"
"golang.org/x/crypto/ssh/terminal" "golang.org/x/crypto/ssh/terminal"
"k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime"
@ -44,6 +43,7 @@ import (
"k8s.io/client-go/tools/clientcmd/api" "k8s.io/client-go/tools/clientcmd/api"
"k8s.io/client-go/transport" "k8s.io/client-go/transport"
"k8s.io/client-go/util/connrotation" "k8s.io/client-go/util/connrotation"
"k8s.io/klog"
) )
const execInfoEnv = "KUBERNETES_EXEC_INFO" const execInfoEnv = "KUBERNETES_EXEC_INFO"
@ -228,7 +228,7 @@ func (r *roundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
Code: int32(res.StatusCode), Code: int32(res.StatusCode),
} }
if err := r.a.maybeRefreshCreds(creds, resp); err != nil { if err := r.a.maybeRefreshCreds(creds, resp); err != nil {
glog.Errorf("refreshing credentials: %v", err) klog.Errorf("refreshing credentials: %v", err)
} }
} }
return res, nil return res, nil

View File

@ -29,7 +29,6 @@ import (
"strings" "strings"
"time" "time"
"github.com/golang/glog"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/runtime/schema"
@ -37,6 +36,7 @@ import (
clientcmdapi "k8s.io/client-go/tools/clientcmd/api" clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
certutil "k8s.io/client-go/util/cert" certutil "k8s.io/client-go/util/cert"
"k8s.io/client-go/util/flowcontrol" "k8s.io/client-go/util/flowcontrol"
"k8s.io/klog"
) )
const ( const (
@ -322,7 +322,7 @@ func InClusterConfig() (*Config, error) {
return nil, ErrNotInCluster return nil, ErrNotInCluster
} }
ts := newCachedPathTokenSource(tokenFile) ts := NewCachedFileTokenSource(tokenFile)
if _, err := ts.Token(); err != nil { if _, err := ts.Token(); err != nil {
return nil, err return nil, err
@ -331,7 +331,7 @@ func InClusterConfig() (*Config, error) {
tlsClientConfig := TLSClientConfig{} tlsClientConfig := TLSClientConfig{}
if _, err := certutil.NewPool(rootCAFile); err != nil { if _, err := certutil.NewPool(rootCAFile); err != nil {
glog.Errorf("Expected to load root CA config from %s, but got err: %v", rootCAFile, err) klog.Errorf("Expected to load root CA config from %s, but got err: %v", rootCAFile, err)
} else { } else {
tlsClientConfig.CAFile = rootCAFile tlsClientConfig.CAFile = rootCAFile
} }

View File

@ -21,7 +21,7 @@ import (
"net/http" "net/http"
"sync" "sync"
"github.com/golang/glog" "k8s.io/klog"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api" clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
) )
@ -57,7 +57,7 @@ func RegisterAuthProviderPlugin(name string, plugin Factory) error {
if _, found := plugins[name]; found { if _, found := plugins[name]; found {
return fmt.Errorf("Auth Provider Plugin %q was registered twice", name) return fmt.Errorf("Auth Provider Plugin %q was registered twice", name)
} }
glog.V(4).Infof("Registered Auth Provider Plugin %q", name) klog.V(4).Infof("Registered Auth Provider Plugin %q", name)
plugins[name] = plugin plugins[name] = plugin
return nil return nil
} }

View File

@ -32,7 +32,6 @@ import (
"strings" "strings"
"time" "time"
"github.com/golang/glog"
"golang.org/x/net/http2" "golang.org/x/net/http2"
"k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@ -44,6 +43,7 @@ import (
restclientwatch "k8s.io/client-go/rest/watch" restclientwatch "k8s.io/client-go/rest/watch"
"k8s.io/client-go/tools/metrics" "k8s.io/client-go/tools/metrics"
"k8s.io/client-go/util/flowcontrol" "k8s.io/client-go/util/flowcontrol"
"k8s.io/klog"
) )
var ( var (
@ -114,7 +114,7 @@ type Request struct {
// NewRequest creates a new request helper object for accessing runtime.Objects on a server. // NewRequest creates a new request helper object for accessing runtime.Objects on a server.
func NewRequest(client HTTPClient, verb string, baseURL *url.URL, versionedAPIPath string, content ContentConfig, serializers Serializers, backoff BackoffManager, throttle flowcontrol.RateLimiter, timeout time.Duration) *Request { func NewRequest(client HTTPClient, verb string, baseURL *url.URL, versionedAPIPath string, content ContentConfig, serializers Serializers, backoff BackoffManager, throttle flowcontrol.RateLimiter, timeout time.Duration) *Request {
if backoff == nil { if backoff == nil {
glog.V(2).Infof("Not implementing request backoff strategy.") klog.V(2).Infof("Not implementing request backoff strategy.")
backoff = &NoBackoff{} backoff = &NoBackoff{}
} }
@ -527,7 +527,7 @@ func (r *Request) tryThrottle() {
r.throttle.Accept() r.throttle.Accept()
} }
if latency := time.Since(now); latency > longThrottleLatency { if latency := time.Since(now); latency > longThrottleLatency {
glog.V(4).Infof("Throttling request took %v, request: %s:%s", latency, r.verb, r.URL().String()) klog.V(4).Infof("Throttling request took %v, request: %s:%s", latency, r.verb, r.URL().String())
} }
} }
@ -683,7 +683,7 @@ func (r *Request) request(fn func(*http.Request, *http.Response)) error {
}() }()
if r.err != nil { if r.err != nil {
glog.V(4).Infof("Error in request: %v", r.err) klog.V(4).Infof("Error in request: %v", r.err)
return r.err return r.err
} }
@ -770,13 +770,13 @@ func (r *Request) request(fn func(*http.Request, *http.Response)) error {
if seeker, ok := r.body.(io.Seeker); ok && r.body != nil { if seeker, ok := r.body.(io.Seeker); ok && r.body != nil {
_, err := seeker.Seek(0, 0) _, err := seeker.Seek(0, 0)
if err != nil { if err != nil {
glog.V(4).Infof("Could not retry request, can't Seek() back to beginning of body for %T", r.body) klog.V(4).Infof("Could not retry request, can't Seek() back to beginning of body for %T", r.body)
fn(req, resp) fn(req, resp)
return true return true
} }
} }
glog.V(4).Infof("Got a Retry-After %ds response for attempt %d to %v", seconds, retries, url) klog.V(4).Infof("Got a Retry-After %ds response for attempt %d to %v", seconds, retries, url)
r.backoffMgr.Sleep(time.Duration(seconds) * time.Second) r.backoffMgr.Sleep(time.Duration(seconds) * time.Second)
return false return false
} }
@ -844,13 +844,13 @@ func (r *Request) transformResponse(resp *http.Response, req *http.Request) Resu
// 2. Apiserver sends back the headers and then part of the body // 2. Apiserver sends back the headers and then part of the body
// 3. Apiserver closes connection. // 3. Apiserver closes connection.
// 4. client-go should catch this and return an error. // 4. client-go should catch this and return an error.
glog.V(2).Infof("Stream error %#v when reading response body, may be caused by closed connection.", err) klog.V(2).Infof("Stream error %#v when reading response body, may be caused by closed connection.", err)
streamErr := fmt.Errorf("Stream error %#v when reading response body, may be caused by closed connection. Please retry.", err) streamErr := fmt.Errorf("Stream error %#v when reading response body, may be caused by closed connection. Please retry.", err)
return Result{ return Result{
err: streamErr, err: streamErr,
} }
default: default:
glog.Errorf("Unexpected error when reading response body: %#v", err) klog.Errorf("Unexpected error when reading response body: %#v", err)
unexpectedErr := fmt.Errorf("Unexpected error %#v when reading response body. Please retry.", err) unexpectedErr := fmt.Errorf("Unexpected error %#v when reading response body. Please retry.", err)
return Result{ return Result{
err: unexpectedErr, err: unexpectedErr,
@ -914,11 +914,11 @@ func (r *Request) transformResponse(resp *http.Response, req *http.Request) Resu
func truncateBody(body string) string { func truncateBody(body string) string {
max := 0 max := 0
switch { switch {
case bool(glog.V(10)): case bool(klog.V(10)):
return body return body
case bool(glog.V(9)): case bool(klog.V(9)):
max = 10240 max = 10240
case bool(glog.V(8)): case bool(klog.V(8)):
max = 1024 max = 1024
} }
@ -933,13 +933,13 @@ func truncateBody(body string) string {
// allocating a new string for the body output unless necessary. Uses a simple heuristic to determine // allocating a new string for the body output unless necessary. Uses a simple heuristic to determine
// whether the body is printable. // whether the body is printable.
func glogBody(prefix string, body []byte) { func glogBody(prefix string, body []byte) {
if glog.V(8) { if klog.V(8) {
if bytes.IndexFunc(body, func(r rune) bool { if bytes.IndexFunc(body, func(r rune) bool {
return r < 0x0a return r < 0x0a
}) != -1 { }) != -1 {
glog.Infof("%s:\n%s", prefix, truncateBody(hex.Dump(body))) klog.Infof("%s:\n%s", prefix, truncateBody(hex.Dump(body)))
} else { } else {
glog.Infof("%s: %s", prefix, truncateBody(string(body))) klog.Infof("%s: %s", prefix, truncateBody(string(body)))
} }
} }
} }
@ -1141,7 +1141,7 @@ func (r Result) Error() error {
// to be backwards compatible with old servers that do not return a version, default to "v1" // to be backwards compatible with old servers that do not return a version, default to "v1"
out, _, err := r.decoder.Decode(r.body, &schema.GroupVersionKind{Version: "v1"}, nil) out, _, err := r.decoder.Decode(r.body, &schema.GroupVersionKind{Version: "v1"}, nil)
if err != nil { if err != nil {
glog.V(5).Infof("body was not decodable (unable to check for Status): %v", err) klog.V(5).Infof("body was not decodable (unable to check for Status): %v", err)
return r.err return r.err
} }
switch t := out.(type) { switch t := out.(type) {

View File

@ -24,8 +24,8 @@ import (
"sync" "sync"
"time" "time"
"github.com/golang/glog"
"golang.org/x/oauth2" "golang.org/x/oauth2"
"k8s.io/klog"
) )
// TokenSourceWrapTransport returns a WrapTransport that injects bearer tokens // TokenSourceWrapTransport returns a WrapTransport that injects bearer tokens
@ -42,7 +42,9 @@ func TokenSourceWrapTransport(ts oauth2.TokenSource) func(http.RoundTripper) htt
} }
} }
func newCachedPathTokenSource(path string) oauth2.TokenSource { // NewCachedFileTokenSource returns a oauth2.TokenSource reads a token from a
// file at a specified path and periodically reloads it.
func NewCachedFileTokenSource(path string) oauth2.TokenSource {
return &cachingTokenSource{ return &cachingTokenSource{
now: time.Now, now: time.Now,
leeway: 1 * time.Minute, leeway: 1 * time.Minute,
@ -129,7 +131,7 @@ func (ts *cachingTokenSource) Token() (*oauth2.Token, error) {
if ts.tok == nil { if ts.tok == nil {
return nil, err return nil, err
} }
glog.Errorf("Unable to rotate token: %v", err) klog.Errorf("Unable to rotate token: %v", err)
return ts.tok, nil return ts.tok, nil
} }

View File

@ -20,9 +20,9 @@ import (
"net/url" "net/url"
"time" "time"
"github.com/golang/glog"
"k8s.io/apimachinery/pkg/util/sets" "k8s.io/apimachinery/pkg/util/sets"
"k8s.io/client-go/util/flowcontrol" "k8s.io/client-go/util/flowcontrol"
"k8s.io/klog"
) )
// Set of resp. Codes that we backoff for. // Set of resp. Codes that we backoff for.
@ -64,7 +64,7 @@ func (n *NoBackoff) Sleep(d time.Duration) {
// Disable makes the backoff trivial, i.e., sets it to zero. This might be used // Disable makes the backoff trivial, i.e., sets it to zero. This might be used
// by tests which want to run 1000s of mock requests without slowing down. // by tests which want to run 1000s of mock requests without slowing down.
func (b *URLBackoff) Disable() { func (b *URLBackoff) Disable() {
glog.V(4).Infof("Disabling backoff strategy") klog.V(4).Infof("Disabling backoff strategy")
b.Backoff = flowcontrol.NewBackOff(0*time.Second, 0*time.Second) b.Backoff = flowcontrol.NewBackOff(0*time.Second, 0*time.Second)
} }
@ -76,7 +76,7 @@ func (b *URLBackoff) baseUrlKey(rawurl *url.URL) string {
// in the future. // in the future.
host, err := url.Parse(rawurl.String()) host, err := url.Parse(rawurl.String())
if err != nil { if err != nil {
glog.V(4).Infof("Error extracting url: %v", rawurl) klog.V(4).Infof("Error extracting url: %v", rawurl)
panic("bad url!") panic("bad url!")
} }
return host.Host return host.Host
@ -89,7 +89,7 @@ func (b *URLBackoff) UpdateBackoff(actualUrl *url.URL, err error, responseCode i
b.Backoff.Next(b.baseUrlKey(actualUrl), b.Backoff.Clock.Now()) b.Backoff.Next(b.baseUrlKey(actualUrl), b.Backoff.Clock.Now())
return return
} else if responseCode >= 300 || err != nil { } else if responseCode >= 300 || err != nil {
glog.V(4).Infof("Client is returning errors: code %v, error %v", responseCode, err) klog.V(4).Infof("Client is returning errors: code %v, error %v", responseCode, err)
} }
//If we got this far, there is no backoff required for this URL anymore. //If we got this far, there is no backoff required for this URL anymore.

View File

@ -15,4 +15,5 @@ limitations under the License.
*/ */
// +k8s:deepcopy-gen=package // +k8s:deepcopy-gen=package
package api package api

41
vendor/k8s.io/client-go/tools/remotecommand/reader.go generated vendored Normal file
View File

@ -0,0 +1,41 @@
/*
Copyright 2018 The Kubernetes Authors.
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 remotecommand
import (
"io"
)
// readerWrapper delegates to an io.Reader so that only the io.Reader interface is implemented,
// to keep io.Copy from doing things we don't want when copying from the reader to the data stream.
//
// If the Stdin io.Reader provided to remotecommand implements a WriteTo function (like bytes.Buffer does[1]),
// io.Copy calls that method[2] to attempt to write the entire buffer to the stream in one call.
// That results in an oversized call to spdystream.Stream#Write [3],
// which results in a single oversized data frame[4] that is too large.
//
// [1] https://golang.org/pkg/bytes/#Buffer.WriteTo
// [2] https://golang.org/pkg/io/#Copy
// [3] https://github.com/kubernetes/kubernetes/blob/90295640ef87db9daa0144c5617afe889e7992b2/vendor/github.com/docker/spdystream/stream.go#L66-L73
// [4] https://github.com/kubernetes/kubernetes/blob/90295640ef87db9daa0144c5617afe889e7992b2/vendor/github.com/docker/spdystream/spdy/write.go#L302-L304
type readerWrapper struct {
reader io.Reader
}
func (r readerWrapper) Read(p []byte) (int, error) {
return r.reader.Read(p)
}

View File

@ -22,7 +22,7 @@ import (
"net/http" "net/http"
"net/url" "net/url"
"github.com/golang/glog" "k8s.io/klog"
"k8s.io/apimachinery/pkg/util/httpstream" "k8s.io/apimachinery/pkg/util/httpstream"
"k8s.io/apimachinery/pkg/util/remotecommand" "k8s.io/apimachinery/pkg/util/remotecommand"
@ -132,7 +132,7 @@ func (e *streamExecutor) Stream(options StreamOptions) error {
case remotecommand.StreamProtocolV2Name: case remotecommand.StreamProtocolV2Name:
streamer = newStreamProtocolV2(options) streamer = newStreamProtocolV2(options)
case "": case "":
glog.V(4).Infof("The server did not negotiate a streaming protocol version. Falling back to %s", remotecommand.StreamProtocolV1Name) klog.V(4).Infof("The server did not negotiate a streaming protocol version. Falling back to %s", remotecommand.StreamProtocolV1Name)
fallthrough fallthrough
case remotecommand.StreamProtocolV1Name: case remotecommand.StreamProtocolV1Name:
streamer = newStreamProtocolV1(options) streamer = newStreamProtocolV1(options)

View File

@ -22,9 +22,9 @@ import (
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"github.com/golang/glog"
"k8s.io/api/core/v1" "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/util/httpstream" "k8s.io/apimachinery/pkg/util/httpstream"
"k8s.io/klog"
) )
// streamProtocolV1 implements the first version of the streaming exec & attach // streamProtocolV1 implements the first version of the streaming exec & attach
@ -53,10 +53,10 @@ func (p *streamProtocolV1) stream(conn streamCreator) error {
errorChan := make(chan error) errorChan := make(chan error)
cp := func(s string, dst io.Writer, src io.Reader) { cp := func(s string, dst io.Writer, src io.Reader) {
glog.V(6).Infof("Copying %s", s) klog.V(6).Infof("Copying %s", s)
defer glog.V(6).Infof("Done copying %s", s) defer klog.V(6).Infof("Done copying %s", s)
if _, err := io.Copy(dst, src); err != nil && err != io.EOF { if _, err := io.Copy(dst, src); err != nil && err != io.EOF {
glog.Errorf("Error copying %s: %v", s, err) klog.Errorf("Error copying %s: %v", s, err)
} }
if s == v1.StreamTypeStdout || s == v1.StreamTypeStderr { if s == v1.StreamTypeStdout || s == v1.StreamTypeStderr {
doneChan <- struct{}{} doneChan <- struct{}{}
@ -127,7 +127,7 @@ func (p *streamProtocolV1) stream(conn streamCreator) error {
// because stdin is not closed until the process exits. If we try to call // because stdin is not closed until the process exits. If we try to call
// stdin.Close(), it returns no error but doesn't unblock the copy. It will // stdin.Close(), it returns no error but doesn't unblock the copy. It will
// exit when the process exits, instead. // exit when the process exits, instead.
go cp(v1.StreamTypeStdin, p.remoteStdin, p.Stdin) go cp(v1.StreamTypeStdin, p.remoteStdin, readerWrapper{p.Stdin})
} }
waitCount := 0 waitCount := 0

View File

@ -101,7 +101,7 @@ func (p *streamProtocolV2) copyStdin() {
// the executed command will remain running. // the executed command will remain running.
defer once.Do(func() { p.remoteStdin.Close() }) defer once.Do(func() { p.remoteStdin.Close() })
if _, err := io.Copy(p.remoteStdin, p.Stdin); err != nil { if _, err := io.Copy(p.remoteStdin, readerWrapper{p.Stdin}); err != nil {
runtime.HandleError(err) runtime.HandleError(err)
} }
}() }()

View File

@ -22,7 +22,7 @@ import (
"strings" "strings"
"time" "time"
"github.com/golang/glog" "k8s.io/klog"
utilnet "k8s.io/apimachinery/pkg/util/net" utilnet "k8s.io/apimachinery/pkg/util/net"
) )
@ -62,13 +62,13 @@ func HTTPWrappersForConfig(config *Config, rt http.RoundTripper) (http.RoundTrip
// DebugWrappers wraps a round tripper and logs based on the current log level. // DebugWrappers wraps a round tripper and logs based on the current log level.
func DebugWrappers(rt http.RoundTripper) http.RoundTripper { func DebugWrappers(rt http.RoundTripper) http.RoundTripper {
switch { switch {
case bool(glog.V(9)): case bool(klog.V(9)):
rt = newDebuggingRoundTripper(rt, debugCurlCommand, debugURLTiming, debugResponseHeaders) rt = newDebuggingRoundTripper(rt, debugCurlCommand, debugURLTiming, debugResponseHeaders)
case bool(glog.V(8)): case bool(klog.V(8)):
rt = newDebuggingRoundTripper(rt, debugJustURL, debugRequestHeaders, debugResponseStatus, debugResponseHeaders) rt = newDebuggingRoundTripper(rt, debugJustURL, debugRequestHeaders, debugResponseStatus, debugResponseHeaders)
case bool(glog.V(7)): case bool(klog.V(7)):
rt = newDebuggingRoundTripper(rt, debugJustURL, debugRequestHeaders, debugResponseStatus) rt = newDebuggingRoundTripper(rt, debugJustURL, debugRequestHeaders, debugResponseStatus)
case bool(glog.V(6)): case bool(klog.V(6)):
rt = newDebuggingRoundTripper(rt, debugURLTiming) rt = newDebuggingRoundTripper(rt, debugURLTiming)
} }
@ -138,7 +138,7 @@ func (rt *authProxyRoundTripper) CancelRequest(req *http.Request) {
if canceler, ok := rt.rt.(requestCanceler); ok { if canceler, ok := rt.rt.(requestCanceler); ok {
canceler.CancelRequest(req) canceler.CancelRequest(req)
} else { } else {
glog.Errorf("CancelRequest not implemented by %T", rt.rt) klog.Errorf("CancelRequest not implemented by %T", rt.rt)
} }
} }
@ -166,7 +166,7 @@ func (rt *userAgentRoundTripper) CancelRequest(req *http.Request) {
if canceler, ok := rt.rt.(requestCanceler); ok { if canceler, ok := rt.rt.(requestCanceler); ok {
canceler.CancelRequest(req) canceler.CancelRequest(req)
} else { } else {
glog.Errorf("CancelRequest not implemented by %T", rt.rt) klog.Errorf("CancelRequest not implemented by %T", rt.rt)
} }
} }
@ -197,7 +197,7 @@ func (rt *basicAuthRoundTripper) CancelRequest(req *http.Request) {
if canceler, ok := rt.rt.(requestCanceler); ok { if canceler, ok := rt.rt.(requestCanceler); ok {
canceler.CancelRequest(req) canceler.CancelRequest(req)
} else { } else {
glog.Errorf("CancelRequest not implemented by %T", rt.rt) klog.Errorf("CancelRequest not implemented by %T", rt.rt)
} }
} }
@ -257,7 +257,7 @@ func (rt *impersonatingRoundTripper) CancelRequest(req *http.Request) {
if canceler, ok := rt.delegate.(requestCanceler); ok { if canceler, ok := rt.delegate.(requestCanceler); ok {
canceler.CancelRequest(req) canceler.CancelRequest(req)
} else { } else {
glog.Errorf("CancelRequest not implemented by %T", rt.delegate) klog.Errorf("CancelRequest not implemented by %T", rt.delegate)
} }
} }
@ -288,7 +288,7 @@ func (rt *bearerAuthRoundTripper) CancelRequest(req *http.Request) {
if canceler, ok := rt.rt.(requestCanceler); ok { if canceler, ok := rt.rt.(requestCanceler); ok {
canceler.CancelRequest(req) canceler.CancelRequest(req)
} else { } else {
glog.Errorf("CancelRequest not implemented by %T", rt.rt) klog.Errorf("CancelRequest not implemented by %T", rt.rt)
} }
} }
@ -372,7 +372,7 @@ func (rt *debuggingRoundTripper) CancelRequest(req *http.Request) {
if canceler, ok := rt.delegatedRoundTripper.(requestCanceler); ok { if canceler, ok := rt.delegatedRoundTripper.(requestCanceler); ok {
canceler.CancelRequest(req) canceler.CancelRequest(req)
} else { } else {
glog.Errorf("CancelRequest not implemented by %T", rt.delegatedRoundTripper) klog.Errorf("CancelRequest not implemented by %T", rt.delegatedRoundTripper)
} }
} }
@ -380,17 +380,17 @@ func (rt *debuggingRoundTripper) RoundTrip(req *http.Request) (*http.Response, e
reqInfo := newRequestInfo(req) reqInfo := newRequestInfo(req)
if rt.levels[debugJustURL] { if rt.levels[debugJustURL] {
glog.Infof("%s %s", reqInfo.RequestVerb, reqInfo.RequestURL) klog.Infof("%s %s", reqInfo.RequestVerb, reqInfo.RequestURL)
} }
if rt.levels[debugCurlCommand] { if rt.levels[debugCurlCommand] {
glog.Infof("%s", reqInfo.toCurl()) klog.Infof("%s", reqInfo.toCurl())
} }
if rt.levels[debugRequestHeaders] { if rt.levels[debugRequestHeaders] {
glog.Infof("Request Headers:") klog.Infof("Request Headers:")
for key, values := range reqInfo.RequestHeaders { for key, values := range reqInfo.RequestHeaders {
for _, value := range values { for _, value := range values {
glog.Infof(" %s: %s", key, value) klog.Infof(" %s: %s", key, value)
} }
} }
} }
@ -402,16 +402,16 @@ func (rt *debuggingRoundTripper) RoundTrip(req *http.Request) (*http.Response, e
reqInfo.complete(response, err) reqInfo.complete(response, err)
if rt.levels[debugURLTiming] { if rt.levels[debugURLTiming] {
glog.Infof("%s %s %s in %d milliseconds", reqInfo.RequestVerb, reqInfo.RequestURL, reqInfo.ResponseStatus, reqInfo.Duration.Nanoseconds()/int64(time.Millisecond)) klog.Infof("%s %s %s in %d milliseconds", reqInfo.RequestVerb, reqInfo.RequestURL, reqInfo.ResponseStatus, reqInfo.Duration.Nanoseconds()/int64(time.Millisecond))
} }
if rt.levels[debugResponseStatus] { if rt.levels[debugResponseStatus] {
glog.Infof("Response Status: %s in %d milliseconds", reqInfo.ResponseStatus, reqInfo.Duration.Nanoseconds()/int64(time.Millisecond)) klog.Infof("Response Status: %s in %d milliseconds", reqInfo.ResponseStatus, reqInfo.Duration.Nanoseconds()/int64(time.Millisecond))
} }
if rt.levels[debugResponseHeaders] { if rt.levels[debugResponseHeaders] {
glog.Infof("Response Headers:") klog.Infof("Response Headers:")
for key, values := range reqInfo.ResponseHeaders { for key, values := range reqInfo.ResponseHeaders {
for _, value := range values { for _, value := range values {
glog.Infof(" %s: %s", key, value) klog.Infof(" %s: %s", key, value)
} }
} }
} }

View File

@ -38,7 +38,7 @@ func RoundTripperFor(config *restclient.Config) (http.RoundTripper, Upgrader, er
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
upgradeRoundTripper := spdy.NewRoundTripper(tlsConfig, true) upgradeRoundTripper := spdy.NewRoundTripper(tlsConfig, true, false)
wrapper, err := restclient.HTTPWrappersForConfig(config, upgradeRoundTripper) wrapper, err := restclient.HTTPWrappersForConfig(config, upgradeRoundTripper)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err

View File

@ -18,6 +18,7 @@ package cert
import ( import (
"bytes" "bytes"
"crypto"
"crypto/ecdsa" "crypto/ecdsa"
"crypto/elliptic" "crypto/elliptic"
"crypto/rand" "crypto/rand"
@ -64,7 +65,7 @@ func NewPrivateKey() (*rsa.PrivateKey, error) {
} }
// NewSelfSignedCACert creates a CA certificate // NewSelfSignedCACert creates a CA certificate
func NewSelfSignedCACert(cfg Config, key *rsa.PrivateKey) (*x509.Certificate, error) { func NewSelfSignedCACert(cfg Config, key crypto.Signer) (*x509.Certificate, error) {
now := time.Now() now := time.Now()
tmpl := x509.Certificate{ tmpl := x509.Certificate{
SerialNumber: new(big.Int).SetInt64(0), SerialNumber: new(big.Int).SetInt64(0),
@ -87,7 +88,7 @@ func NewSelfSignedCACert(cfg Config, key *rsa.PrivateKey) (*x509.Certificate, er
} }
// NewSignedCert creates a signed certificate using the given CA certificate and key // NewSignedCert creates a signed certificate using the given CA certificate and key
func NewSignedCert(cfg Config, key *rsa.PrivateKey, caCert *x509.Certificate, caKey *rsa.PrivateKey) (*x509.Certificate, error) { func NewSignedCert(cfg Config, key crypto.Signer, caCert *x509.Certificate, caKey crypto.Signer) (*x509.Certificate, error) {
serial, err := rand.Int(rand.Reader, new(big.Int).SetInt64(math.MaxInt64)) serial, err := rand.Int(rand.Reader, new(big.Int).SetInt64(math.MaxInt64))
if err != nil { if err != nil {
return nil, err return nil, err
@ -259,34 +260,6 @@ func GenerateSelfSignedCertKeyWithFixtures(host string, alternateIPs []net.IP, a
return certBuffer.Bytes(), keyBuffer.Bytes(), nil return certBuffer.Bytes(), keyBuffer.Bytes(), nil
} }
// FormatBytesCert receives byte array certificate and formats in human-readable format
func FormatBytesCert(cert []byte) (string, error) {
block, _ := pem.Decode(cert)
c, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return "", fmt.Errorf("failed to parse certificate [%v]", err)
}
return FormatCert(c), nil
}
// FormatCert receives certificate and formats in human-readable format
func FormatCert(c *x509.Certificate) string {
var ips []string
for _, ip := range c.IPAddresses {
ips = append(ips, ip.String())
}
altNames := append(ips, c.DNSNames...)
res := fmt.Sprintf(
"Issuer: CN=%s | Subject: CN=%s | CA: %t\n",
c.Issuer.CommonName, c.Subject.CommonName, c.IsCA,
)
res += fmt.Sprintf("Not before: %s Not After: %s", c.NotBefore, c.NotAfter)
if len(altNames) > 0 {
res += fmt.Sprintf("\nAlternate Names: %v", altNames)
}
return res
}
func ipsToStrings(ips []net.IP) []string { func ipsToStrings(ips []net.IP) []string {
ss := make([]string, 0, len(ips)) ss := make([]string, 0, len(ips))
for _, ip := range ips { for _, ip := range ips {

View File

@ -1,3 +1,10 @@
klog
====
klog is a permanant fork of https://github.com/golang/glog. original README from glog is below
----
glog glog
==== ====
@ -5,7 +12,7 @@ Leveled execution logs for Go.
This is an efficient pure Go implementation of leveled logs in the This is an efficient pure Go implementation of leveled logs in the
manner of the open source C++ package manner of the open source C++ package
http://code.google.com/p/google-glog https://github.com/google/glog
By binding methods to booleans it is possible to use the log package By binding methods to booleans it is possible to use the log package
without paying the expense of evaluating the arguments to the log. without paying the expense of evaluating the arguments to the log.

View File

@ -14,7 +14,7 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
// Package glog implements logging analogous to the Google-internal C++ INFO/ERROR/V setup. // Package klog implements logging analogous to the Google-internal C++ INFO/ERROR/V setup.
// It provides functions Info, Warning, Error, Fatal, plus formatting variants such as // It provides functions Info, Warning, Error, Fatal, plus formatting variants such as
// Infof. It also provides V-style logging controlled by the -v and -vmodule=file=2 flags. // Infof. It also provides V-style logging controlled by the -v and -vmodule=file=2 flags.
// //
@ -68,7 +68,7 @@
// -vmodule=gopher*=3 // -vmodule=gopher*=3
// sets the V level to 3 in all Go files whose names begin "gopher". // sets the V level to 3 in all Go files whose names begin "gopher".
// //
package glog package klog
import ( import (
"bufio" "bufio"
@ -396,13 +396,6 @@ type flushSyncWriter interface {
} }
func init() { func init() {
flag.BoolVar(&logging.toStderr, "logtostderr", false, "log to standard error instead of files")
flag.BoolVar(&logging.alsoToStderr, "alsologtostderr", false, "log to standard error as well as files")
flag.Var(&logging.verbosity, "v", "log level for V logs")
flag.Var(&logging.stderrThreshold, "stderrthreshold", "logs at or above this threshold go to stderr")
flag.Var(&logging.vmodule, "vmodule", "comma-separated list of pattern=N settings for file-filtered logging")
flag.Var(&logging.traceLocation, "log_backtrace_at", "when logging hits line file:N, emit a stack trace")
// Default stderrThreshold is ERROR. // Default stderrThreshold is ERROR.
logging.stderrThreshold = errorLog logging.stderrThreshold = errorLog
@ -410,6 +403,22 @@ func init() {
go logging.flushDaemon() go logging.flushDaemon()
} }
// InitFlags is for explicitly initializing the flags
func InitFlags(flagset *flag.FlagSet) {
if flagset == nil {
flagset = flag.CommandLine
}
flagset.StringVar(&logging.logDir, "log_dir", "", "If non-empty, write log files in this directory")
flagset.StringVar(&logging.logFile, "log_file", "", "If non-empty, use this log file")
flagset.BoolVar(&logging.toStderr, "logtostderr", false, "log to standard error instead of files")
flagset.BoolVar(&logging.alsoToStderr, "alsologtostderr", false, "log to standard error as well as files")
flagset.Var(&logging.verbosity, "v", "log level for V logs")
flagset.BoolVar(&logging.skipHeaders, "skip_headers", false, "If true, avoid header prefixes in the log messages")
flagset.Var(&logging.stderrThreshold, "stderrthreshold", "logs at or above this threshold go to stderr")
flagset.Var(&logging.vmodule, "vmodule", "comma-separated list of pattern=N settings for file-filtered logging")
flagset.Var(&logging.traceLocation, "log_backtrace_at", "when logging hits line file:N, emit a stack trace")
}
// Flush flushes all pending log I/O. // Flush flushes all pending log I/O.
func Flush() { func Flush() {
logging.lockAndFlushAll() logging.lockAndFlushAll()
@ -453,6 +462,17 @@ type loggingT struct {
// safely using atomic.LoadInt32. // safely using atomic.LoadInt32.
vmodule moduleSpec // The state of the -vmodule flag. vmodule moduleSpec // The state of the -vmodule flag.
verbosity Level // V logging level, the value of the -v flag/ verbosity Level // V logging level, the value of the -v flag/
// If non-empty, overrides the choice of directory in which to write logs.
// See createLogDirs for the full list of possible destinations.
logDir string
// If non-empty, specifies the path of the file to write logs. mutually exclusive
// with the log-dir option.
logFile string
// If true, do not add the prefix headers, useful when used with SetOutput
skipHeaders bool
} }
// buffer holds a byte Buffer for reuse. The zero value is ready for use. // buffer holds a byte Buffer for reuse. The zero value is ready for use.
@ -556,6 +576,9 @@ func (l *loggingT) formatHeader(s severity, file string, line int) *buffer {
s = infoLog // for safety. s = infoLog // for safety.
} }
buf := l.getBuffer() buf := l.getBuffer()
if l.skipHeaders {
return buf
}
// Avoid Fprintf, for speed. The format is so simple that we can do it quickly by hand. // Avoid Fprintf, for speed. The format is so simple that we can do it quickly by hand.
// It's worth about 3X. Fprintf is hard. // It's worth about 3X. Fprintf is hard.
@ -667,6 +690,45 @@ func (l *loggingT) printWithFileLine(s severity, file string, line int, alsoToSt
l.output(s, buf, file, line, alsoToStderr) l.output(s, buf, file, line, alsoToStderr)
} }
// redirectBuffer is used to set an alternate destination for the logs
type redirectBuffer struct {
w io.Writer
}
func (rb *redirectBuffer) Sync() error {
return nil
}
func (rb *redirectBuffer) Flush() error {
return nil
}
func (rb *redirectBuffer) Write(bytes []byte) (n int, err error) {
return rb.w.Write(bytes)
}
// SetOutput sets the output destination for all severities
func SetOutput(w io.Writer) {
for s := fatalLog; s >= infoLog; s-- {
rb := &redirectBuffer{
w: w,
}
logging.file[s] = rb
}
}
// SetOutputBySeverity sets the output destination for specific severity
func SetOutputBySeverity(name string, w io.Writer) {
sev, ok := severityByName(name)
if !ok {
panic(fmt.Sprintf("SetOutputBySeverity(%q): unrecognized severity name", name))
}
rb := &redirectBuffer{
w: w,
}
logging.file[sev] = rb
}
// output writes the data to the log files and releases the buffer. // output writes the data to the log files and releases the buffer.
func (l *loggingT) output(s severity, buf *buffer, file string, line int, alsoToStderr bool) { func (l *loggingT) output(s severity, buf *buffer, file string, line int, alsoToStderr bool) {
l.mu.Lock() l.mu.Lock()
@ -876,7 +938,7 @@ const flushInterval = 30 * time.Second
// flushDaemon periodically flushes the log file buffers. // flushDaemon periodically flushes the log file buffers.
func (l *loggingT) flushDaemon() { func (l *loggingT) flushDaemon() {
for _ = range time.NewTicker(flushInterval).C { for range time.NewTicker(flushInterval).C {
l.lockAndFlushAll() l.lockAndFlushAll()
} }
} }

View File

@ -16,11 +16,10 @@
// File I/O for logs. // File I/O for logs.
package glog package klog
import ( import (
"errors" "errors"
"flag"
"fmt" "fmt"
"os" "os"
"os/user" "os/user"
@ -36,13 +35,9 @@ var MaxSize uint64 = 1024 * 1024 * 1800
// logDirs lists the candidate directories for new log files. // logDirs lists the candidate directories for new log files.
var logDirs []string var logDirs []string
// If non-empty, overrides the choice of directory in which to write logs.
// See createLogDirs for the full list of possible destinations.
var logDir = flag.String("log_dir", "", "If non-empty, write log files in this directory")
func createLogDirs() { func createLogDirs() {
if *logDir != "" { if logging.logDir != "" {
logDirs = append(logDirs, *logDir) logDirs = append(logDirs, logging.logDir)
} }
logDirs = append(logDirs, os.TempDir()) logDirs = append(logDirs, os.TempDir())
} }
@ -103,6 +98,13 @@ var onceLogDirs sync.Once
// successfully, create also attempts to update the symlink for that tag, ignoring // successfully, create also attempts to update the symlink for that tag, ignoring
// errors. // errors.
func create(tag string, t time.Time) (f *os.File, filename string, err error) { func create(tag string, t time.Time) (f *os.File, filename string, err error) {
if logging.logFile != "" {
f, err := os.Create(logging.logFile)
if err == nil {
return f, logging.logFile, nil
}
return nil, "", fmt.Errorf("log: unable to create log: %v", err)
}
onceLogDirs.Do(createLogDirs) onceLogDirs.Do(createLogDirs)
if len(logDirs) == 0 { if len(logDirs) == 0 {
return nil, "", errors.New("log: no log dirs") return nil, "", errors.New("log: no log dirs")

View File

@ -82,7 +82,7 @@ docker-machine create \
# Set up local docker to talk to that machine # Set up local docker to talk to that machine
eval $(docker-machine env ${KUBE_BUILD_VM}) eval $(docker-machine env ${KUBE_BUILD_VM})
# Pin down the port that rsync will be exposed on on the remote machine # Pin down the port that rsync will be exposed on the remote machine
export KUBE_RSYNC_PORT=8730 export KUBE_RSYNC_PORT=8730
# forward local 8730 to that machine so that rsync works # forward local 8730 to that machine so that rsync works

View File

@ -82,4 +82,23 @@ const (
// //
// Not all cloud providers support this annotation, though AWS & GCE do. // Not all cloud providers support this annotation, though AWS & GCE do.
AnnotationLoadBalancerSourceRangesKey = "service.beta.kubernetes.io/load-balancer-source-ranges" AnnotationLoadBalancerSourceRangesKey = "service.beta.kubernetes.io/load-balancer-source-ranges"
// EndpointsLastChangeTriggerTime is the annotation key, set for endpoints objects, that
// represents the timestamp (stored as RFC 3339 date-time string, e.g. '2018-10-22T19:32:52.1Z')
// of the last change, of some Pod or Service object, that triggered the endpoints object change.
// In other words, if a Pod / Service changed at time T0, that change was observed by endpoints
// controller at T1, and the Endpoints object was changed at T2, the
// EndpointsLastChangeTriggerTime would be set to T0.
//
// The "endpoints change trigger" here means any Pod or Service change that resulted in the
// Endpoints object change.
//
// Given the definition of the "endpoints change trigger", please note that this annotation will
// be set ONLY for endpoints object changes triggered by either Pod or Service change. If the
// Endpoints object changes due to other reasons, this annotation won't be set (or updated if it's
// already set).
//
// This annotation will be used to compute the in-cluster network programming latency SLI, see
// https://github.com/kubernetes/community/blob/master/sig-scalability/slos/network_programming_latency.md
EndpointsLastChangeTriggerTime = "endpoints.kubernetes.io/last-change-trigger-time"
) )

View File

@ -26,19 +26,19 @@ import (
const ( const (
// NamespaceDefault means the object is in the default namespace which is applied when not specified by clients // NamespaceDefault means the object is in the default namespace which is applied when not specified by clients
NamespaceDefault string = "default" NamespaceDefault = "default"
// NamespaceAll is the default argument to specify on a context when you want to list or filter resources across all namespaces // NamespaceAll is the default argument to specify on a context when you want to list or filter resources across all namespaces
NamespaceAll string = "" NamespaceAll = ""
// NamespaceNone is the argument for a context when there is no namespace. // NamespaceNone is the argument for a context when there is no namespace.
NamespaceNone string = "" NamespaceNone = ""
// NamespaceSystem is the system namespace where we place system components. // NamespaceSystem is the system namespace where we place system components.
NamespaceSystem string = "kube-system" NamespaceSystem = "kube-system"
// NamespacePublic is the namespace where we place public info (ConfigMaps) // NamespacePublic is the namespace where we place public info (ConfigMaps)
NamespacePublic string = "kube-public" NamespacePublic = "kube-public"
// NamespaceNodeLease is the namespace where we place node lease objects (used for node heartbeats) // NamespaceNodeLease is the namespace where we place node lease objects (used for node heartbeats)
NamespaceNodeLease string = "kube-node-lease" NamespaceNodeLease = "kube-node-lease"
// TerminationMessagePathDefault means the default path to capture the application termination message running in a container // TerminationMessagePathDefault means the default path to capture the application termination message running in a container
TerminationMessagePathDefault string = "/dev/termination-log" TerminationMessagePathDefault = "/dev/termination-log"
) )
// Volume represents a named volume in a pod that may be accessed by any containers in the pod. // Volume represents a named volume in a pod that may be accessed by any containers in the pod.
@ -175,7 +175,7 @@ type PersistentVolumeSource struct {
HostPath *HostPathVolumeSource HostPath *HostPathVolumeSource
// Glusterfs represents a Glusterfs volume that is attached to a host and exposed to the pod // Glusterfs represents a Glusterfs volume that is attached to a host and exposed to the pod
// +optional // +optional
Glusterfs *GlusterfsVolumeSource Glusterfs *GlusterfsPersistentVolumeSource
// NFS represents an NFS mount on the host that shares a pod's lifetime // NFS represents an NFS mount on the host that shares a pod's lifetime
// +optional // +optional
NFS *NFSVolumeSource NFS *NFSVolumeSource
@ -229,7 +229,7 @@ type PersistentVolumeSource struct {
// More info: https://releases.k8s.io/HEAD/examples/volumes/storageos/README.md // More info: https://releases.k8s.io/HEAD/examples/volumes/storageos/README.md
// +optional // +optional
StorageOS *StorageOSPersistentVolumeSource StorageOS *StorageOSPersistentVolumeSource
// CSI (Container Storage Interface) represents storage that handled by an external CSI driver (Beta feature). // CSI (Container Storage Interface) represents storage that handled by an external CSI driver.
// +optional // +optional
CSI *CSIPersistentVolumeSource CSI *CSIPersistentVolumeSource
} }
@ -298,7 +298,7 @@ type PersistentVolumeSpec struct {
MountOptions []string MountOptions []string
// volumeMode defines if a volume is intended to be used with a formatted filesystem // volumeMode defines if a volume is intended to be used with a formatted filesystem
// or to remain in raw block state. Value of Filesystem is implied when not included in spec. // or to remain in raw block state. Value of Filesystem is implied when not included in spec.
// This is an alpha feature and may change in the future. // This is a beta feature.
// +optional // +optional
VolumeMode *PersistentVolumeMode VolumeMode *PersistentVolumeMode
// NodeAffinity defines constraints that limit what nodes this volume can be accessed from. // NodeAffinity defines constraints that limit what nodes this volume can be accessed from.
@ -410,7 +410,7 @@ type PersistentVolumeClaimSpec struct {
StorageClassName *string StorageClassName *string
// volumeMode defines what type of volume is required by the claim. // volumeMode defines what type of volume is required by the claim.
// Value of Filesystem is implied when not included in claim spec. // Value of Filesystem is implied when not included in claim spec.
// This is an alpha feature and may change in the future. // This is a beta feature.
// +optional // +optional
VolumeMode *PersistentVolumeMode VolumeMode *PersistentVolumeMode
// This field requires the VolumeSnapshotDataSource alpha feature gate to be // This field requires the VolumeSnapshotDataSource alpha feature gate to be
@ -935,6 +935,30 @@ type GlusterfsVolumeSource struct {
ReadOnly bool ReadOnly bool
} }
// Represents a Glusterfs mount that lasts the lifetime of a pod.
// Glusterfs volumes do not support ownership management or SELinux relabeling.
type GlusterfsPersistentVolumeSource struct {
// EndpointsName is the endpoint name that details Glusterfs topology.
// More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod
EndpointsName string
// Path is the Glusterfs volume path.
// More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod
Path string
// ReadOnly here will force the Glusterfs volume to be mounted with read-only permissions.
// Defaults to false.
// More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod
// +optional
ReadOnly bool
// EndpointsNamespace is the namespace that contains Glusterfs endpoint.
// If this field is empty, the EndpointNamespace defaults to the same namespace as the bound PVC.
// More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod
// +optional
EndpointsNamespace *string
}
// Represents a Rados Block Device mount that lasts the lifetime of a pod. // Represents a Rados Block Device mount that lasts the lifetime of a pod.
// RBD volumes support ownership management and SELinux relabeling. // RBD volumes support ownership management and SELinux relabeling.
type RBDVolumeSource struct { type RBDVolumeSource struct {
@ -1523,7 +1547,7 @@ type LocalVolumeSource struct {
FSType *string FSType *string
} }
// Represents storage that is managed by an external CSI volume driver (Beta feature) // Represents storage that is managed by an external CSI volume driver.
type CSIPersistentVolumeSource struct { type CSIPersistentVolumeSource struct {
// Driver is the name of the driver to use for this volume. // Driver is the name of the driver to use for this volume.
// Required. // Required.
@ -1944,7 +1968,7 @@ type Container struct {
// +optional // +optional
VolumeMounts []VolumeMount VolumeMounts []VolumeMount
// volumeDevices is the list of block devices to be used by the container. // volumeDevices is the list of block devices to be used by the container.
// This is an alpha feature and may change in the future. // This is a beta feature.
// +optional // +optional
VolumeDevices []VolumeDevice VolumeDevices []VolumeDevice
// +optional // +optional
@ -2597,6 +2621,11 @@ type PodSpec struct {
// This is an alpha feature and may change in the future. // This is an alpha feature and may change in the future.
// +optional // +optional
RuntimeClassName *string RuntimeClassName *string
// EnableServiceLinks indicates whether information about services should be injected into pod's
// environment variables, matching the syntax of Docker links.
// If not specified, the default is true.
// +optional
EnableServiceLinks *bool
} }
// HostAlias holds the mapping between IP and hostnames that will be injected as an entry in the // HostAlias holds the mapping between IP and hostnames that will be injected as an entry in the

View File

@ -1498,6 +1498,27 @@ func (in *GitRepoVolumeSource) DeepCopy() *GitRepoVolumeSource {
return out return out
} }
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *GlusterfsPersistentVolumeSource) DeepCopyInto(out *GlusterfsPersistentVolumeSource) {
*out = *in
if in.EndpointsNamespace != nil {
in, out := &in.EndpointsNamespace, &out.EndpointsNamespace
*out = new(string)
**out = **in
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GlusterfsPersistentVolumeSource.
func (in *GlusterfsPersistentVolumeSource) DeepCopy() *GlusterfsPersistentVolumeSource {
if in == nil {
return nil
}
out := new(GlusterfsPersistentVolumeSource)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *GlusterfsVolumeSource) DeepCopyInto(out *GlusterfsVolumeSource) { func (in *GlusterfsVolumeSource) DeepCopyInto(out *GlusterfsVolumeSource) {
*out = *in *out = *in
@ -2808,8 +2829,8 @@ func (in *PersistentVolumeSource) DeepCopyInto(out *PersistentVolumeSource) {
} }
if in.Glusterfs != nil { if in.Glusterfs != nil {
in, out := &in.Glusterfs, &out.Glusterfs in, out := &in.Glusterfs, &out.Glusterfs
*out = new(GlusterfsVolumeSource) *out = new(GlusterfsPersistentVolumeSource)
**out = **in (*in).DeepCopyInto(*out)
} }
if in.NFS != nil { if in.NFS != nil {
in, out := &in.NFS, &out.NFS in, out := &in.NFS, &out.NFS
@ -3556,6 +3577,11 @@ func (in *PodSpec) DeepCopyInto(out *PodSpec) {
*out = new(string) *out = new(string)
**out = **in **out = **in
} }
if in.EnableServiceLinks != nil {
in, out := &in.EnableServiceLinks, &out.EnableServiceLinks
*out = new(bool)
**out = **in
}
return return
} }

File diff suppressed because it is too large Load Diff

View File

@ -30,7 +30,7 @@ import (
utilruntime "k8s.io/apimachinery/pkg/util/runtime" utilruntime "k8s.io/apimachinery/pkg/util/runtime"
api "k8s.io/kubernetes/pkg/apis/core" api "k8s.io/kubernetes/pkg/apis/core"
"github.com/golang/glog" "k8s.io/klog"
) )
func handleHttpStreams(req *http.Request, w http.ResponseWriter, portForwarder PortForwarder, podName string, uid types.UID, supportedPortForwardProtocols []string, idleTimeout, streamCreationTimeout time.Duration) error { func handleHttpStreams(req *http.Request, w http.ResponseWriter, portForwarder PortForwarder, podName string, uid types.UID, supportedPortForwardProtocols []string, idleTimeout, streamCreationTimeout time.Duration) error {
@ -42,7 +42,7 @@ func handleHttpStreams(req *http.Request, w http.ResponseWriter, portForwarder P
} }
streamChan := make(chan httpstream.Stream, 1) streamChan := make(chan httpstream.Stream, 1)
glog.V(5).Infof("Upgrading port forward response") klog.V(5).Infof("Upgrading port forward response")
upgrader := spdy.NewResponseUpgrader() upgrader := spdy.NewResponseUpgrader()
conn := upgrader.UpgradeResponse(w, req, httpStreamReceived(streamChan)) conn := upgrader.UpgradeResponse(w, req, httpStreamReceived(streamChan))
if conn == nil { if conn == nil {
@ -50,7 +50,7 @@ func handleHttpStreams(req *http.Request, w http.ResponseWriter, portForwarder P
} }
defer conn.Close() defer conn.Close()
glog.V(5).Infof("(conn=%p) setting port forwarding streaming connection idle timeout to %v", conn, idleTimeout) klog.V(5).Infof("(conn=%p) setting port forwarding streaming connection idle timeout to %v", conn, idleTimeout)
conn.SetIdleTimeout(idleTimeout) conn.SetIdleTimeout(idleTimeout)
h := &httpStreamHandler{ h := &httpStreamHandler{
@ -121,11 +121,11 @@ func (h *httpStreamHandler) getStreamPair(requestID string) (*httpStreamPair, bo
defer h.streamPairsLock.Unlock() defer h.streamPairsLock.Unlock()
if p, ok := h.streamPairs[requestID]; ok { if p, ok := h.streamPairs[requestID]; ok {
glog.V(5).Infof("(conn=%p, request=%s) found existing stream pair", h.conn, requestID) klog.V(5).Infof("(conn=%p, request=%s) found existing stream pair", h.conn, requestID)
return p, false return p, false
} }
glog.V(5).Infof("(conn=%p, request=%s) creating new stream pair", h.conn, requestID) klog.V(5).Infof("(conn=%p, request=%s) creating new stream pair", h.conn, requestID)
p := newPortForwardPair(requestID) p := newPortForwardPair(requestID)
h.streamPairs[requestID] = p h.streamPairs[requestID] = p
@ -143,7 +143,7 @@ func (h *httpStreamHandler) monitorStreamPair(p *httpStreamPair, timeout <-chan
utilruntime.HandleError(err) utilruntime.HandleError(err)
p.printError(err.Error()) p.printError(err.Error())
case <-p.complete: case <-p.complete:
glog.V(5).Infof("(conn=%v, request=%s) successfully received error and data streams", h.conn, p.requestID) klog.V(5).Infof("(conn=%v, request=%s) successfully received error and data streams", h.conn, p.requestID)
} }
h.removeStreamPair(p.requestID) h.removeStreamPair(p.requestID)
} }
@ -170,7 +170,7 @@ func (h *httpStreamHandler) removeStreamPair(requestID string) {
func (h *httpStreamHandler) requestID(stream httpstream.Stream) string { func (h *httpStreamHandler) requestID(stream httpstream.Stream) string {
requestID := stream.Headers().Get(api.PortForwardRequestIDHeader) requestID := stream.Headers().Get(api.PortForwardRequestIDHeader)
if len(requestID) == 0 { if len(requestID) == 0 {
glog.V(5).Infof("(conn=%p) stream received without %s header", h.conn, api.PortForwardRequestIDHeader) klog.V(5).Infof("(conn=%p) stream received without %s header", h.conn, api.PortForwardRequestIDHeader)
// If we get here, it's because the connection came from an older client // If we get here, it's because the connection came from an older client
// that isn't generating the request id header // that isn't generating the request id header
// (https://github.com/kubernetes/kubernetes/blob/843134885e7e0b360eb5441e85b1410a8b1a7a0c/pkg/client/unversioned/portforward/portforward.go#L258-L287) // (https://github.com/kubernetes/kubernetes/blob/843134885e7e0b360eb5441e85b1410a8b1a7a0c/pkg/client/unversioned/portforward/portforward.go#L258-L287)
@ -197,7 +197,7 @@ func (h *httpStreamHandler) requestID(stream httpstream.Stream) string {
requestID = strconv.Itoa(int(stream.Identifier()) - 2) requestID = strconv.Itoa(int(stream.Identifier()) - 2)
} }
glog.V(5).Infof("(conn=%p) automatically assigning request ID=%q from stream type=%s, stream ID=%d", h.conn, requestID, streamType, stream.Identifier()) klog.V(5).Infof("(conn=%p) automatically assigning request ID=%q from stream type=%s, stream ID=%d", h.conn, requestID, streamType, stream.Identifier())
} }
return requestID return requestID
} }
@ -206,17 +206,17 @@ func (h *httpStreamHandler) requestID(stream httpstream.Stream) string {
// streams, invoking portForward for each complete stream pair. The loop exits // streams, invoking portForward for each complete stream pair. The loop exits
// when the httpstream.Connection is closed. // when the httpstream.Connection is closed.
func (h *httpStreamHandler) run() { func (h *httpStreamHandler) run() {
glog.V(5).Infof("(conn=%p) waiting for port forward streams", h.conn) klog.V(5).Infof("(conn=%p) waiting for port forward streams", h.conn)
Loop: Loop:
for { for {
select { select {
case <-h.conn.CloseChan(): case <-h.conn.CloseChan():
glog.V(5).Infof("(conn=%p) upgraded connection closed", h.conn) klog.V(5).Infof("(conn=%p) upgraded connection closed", h.conn)
break Loop break Loop
case stream := <-h.streamChan: case stream := <-h.streamChan:
requestID := h.requestID(stream) requestID := h.requestID(stream)
streamType := stream.Headers().Get(api.StreamType) streamType := stream.Headers().Get(api.StreamType)
glog.V(5).Infof("(conn=%p, request=%s) received new stream of type %s", h.conn, requestID, streamType) klog.V(5).Infof("(conn=%p, request=%s) received new stream of type %s", h.conn, requestID, streamType)
p, created := h.getStreamPair(requestID) p, created := h.getStreamPair(requestID)
if created { if created {
@ -242,9 +242,9 @@ func (h *httpStreamHandler) portForward(p *httpStreamPair) {
portString := p.dataStream.Headers().Get(api.PortHeader) portString := p.dataStream.Headers().Get(api.PortHeader)
port, _ := strconv.ParseInt(portString, 10, 32) port, _ := strconv.ParseInt(portString, 10, 32)
glog.V(5).Infof("(conn=%p, request=%s) invoking forwarder.PortForward for port %s", h.conn, p.requestID, portString) klog.V(5).Infof("(conn=%p, request=%s) invoking forwarder.PortForward for port %s", h.conn, p.requestID, portString)
err := h.forwarder.PortForward(h.pod, h.uid, int32(port), p.dataStream) err := h.forwarder.PortForward(h.pod, h.uid, int32(port), p.dataStream)
glog.V(5).Infof("(conn=%p, request=%s) done invoking forwarder.PortForward for port %s", h.conn, p.requestID, portString) klog.V(5).Infof("(conn=%p, request=%s) done invoking forwarder.PortForward for port %s", h.conn, p.requestID, portString)
if err != nil { if err != nil {
msg := fmt.Errorf("error forwarding port %d to pod %s, uid %v: %v", port, h.pod, h.uid, err) msg := fmt.Errorf("error forwarding port %d to pod %s, uid %v: %v", port, h.pod, h.uid, err)

View File

@ -26,7 +26,7 @@ import (
"sync" "sync"
"time" "time"
"github.com/golang/glog" "k8s.io/klog"
"k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/util/runtime"
@ -185,9 +185,9 @@ func (h *websocketStreamHandler) portForward(p *websocketStreamPair) {
defer p.dataStream.Close() defer p.dataStream.Close()
defer p.errorStream.Close() defer p.errorStream.Close()
glog.V(5).Infof("(conn=%p) invoking forwarder.PortForward for port %d", h.conn, p.port) klog.V(5).Infof("(conn=%p) invoking forwarder.PortForward for port %d", h.conn, p.port)
err := h.forwarder.PortForward(h.pod, h.uid, p.port, p.dataStream) err := h.forwarder.PortForward(h.pod, h.uid, p.port, p.dataStream)
glog.V(5).Infof("(conn=%p) done invoking forwarder.PortForward for port %d", h.conn, p.port) klog.V(5).Infof("(conn=%p) done invoking forwarder.PortForward for port %d", h.conn, p.port)
if err != nil { if err != nil {
msg := fmt.Errorf("error forwarding port %d to pod %s, uid %v: %v", p.port, h.pod, h.uid, err) msg := fmt.Errorf("error forwarding port %d to pod %s, uid %v: %v", p.port, h.pod, h.uid, err)

View File

@ -34,7 +34,7 @@ import (
"k8s.io/client-go/tools/remotecommand" "k8s.io/client-go/tools/remotecommand"
api "k8s.io/kubernetes/pkg/apis/core" api "k8s.io/kubernetes/pkg/apis/core"
"github.com/golang/glog" "k8s.io/klog"
) )
// Options contains details about which streams are required for // Options contains details about which streams are required for
@ -54,7 +54,7 @@ func NewOptions(req *http.Request) (*Options, error) {
stderr := req.FormValue(api.ExecStderrParam) == "1" stderr := req.FormValue(api.ExecStderrParam) == "1"
if tty && stderr { if tty && stderr {
// TODO: make this an error before we reach this method // TODO: make this an error before we reach this method
glog.V(4).Infof("Access to exec with tty and stderr is not supported, bypassing stderr") klog.V(4).Infof("Access to exec with tty and stderr is not supported, bypassing stderr")
stderr = false stderr = false
} }
@ -125,8 +125,7 @@ func createStreams(req *http.Request, w http.ResponseWriter, opts *Options, supp
func createHttpStreamStreams(req *http.Request, w http.ResponseWriter, opts *Options, supportedStreamProtocols []string, idleTimeout, streamCreationTimeout time.Duration) (*context, bool) { func createHttpStreamStreams(req *http.Request, w http.ResponseWriter, opts *Options, supportedStreamProtocols []string, idleTimeout, streamCreationTimeout time.Duration) (*context, bool) {
protocol, err := httpstream.Handshake(req, w, supportedStreamProtocols) protocol, err := httpstream.Handshake(req, w, supportedStreamProtocols)
if err != nil { if err != nil {
w.WriteHeader(http.StatusBadRequest) http.Error(w, err.Error(), http.StatusBadRequest)
fmt.Fprint(w, err.Error())
return nil, false return nil, false
} }
@ -156,7 +155,7 @@ func createHttpStreamStreams(req *http.Request, w http.ResponseWriter, opts *Opt
case remotecommandconsts.StreamProtocolV2Name: case remotecommandconsts.StreamProtocolV2Name:
handler = &v2ProtocolHandler{} handler = &v2ProtocolHandler{}
case "": case "":
glog.V(4).Infof("Client did not request protocol negotiation. Falling back to %q", remotecommandconsts.StreamProtocolV1Name) klog.V(4).Infof("Client did not request protocol negotiation. Falling back to %q", remotecommandconsts.StreamProtocolV1Name)
fallthrough fallthrough
case remotecommandconsts.StreamProtocolV1Name: case remotecommandconsts.StreamProtocolV1Name:
handler = &v1ProtocolHandler{} handler = &v1ProtocolHandler{}

View File

@ -17,9 +17,6 @@ limitations under the License.
package util package util
import ( import (
"fmt"
"net/url"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
) )
@ -28,20 +25,3 @@ import (
func FromApiserverCache(opts *metav1.GetOptions) { func FromApiserverCache(opts *metav1.GetOptions) {
opts.ResourceVersion = "0" opts.ResourceVersion = "0"
} }
func parseEndpoint(endpoint string) (string, string, error) {
u, err := url.Parse(endpoint)
if err != nil {
return "", "", err
}
if u.Scheme == "tcp" {
return "tcp", u.Host, nil
} else if u.Scheme == "unix" {
return "unix", u.Path, nil
} else if u.Scheme == "" {
return "", "", fmt.Errorf("Using %q as endpoint is deprecated, please consider using full url format", endpoint)
} else {
return u.Scheme, "", fmt.Errorf("protocol %q not supported", u.Scheme)
}
}

View File

@ -21,11 +21,13 @@ package util
import ( import (
"fmt" "fmt"
"net" "net"
"net/url"
"os" "os"
"path/filepath"
"time" "time"
"github.com/golang/glog"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
"k8s.io/klog"
) )
const ( const (
@ -72,8 +74,38 @@ func parseEndpointWithFallbackProtocol(endpoint string, fallbackProtocol string)
fallbackEndpoint := fallbackProtocol + "://" + endpoint fallbackEndpoint := fallbackProtocol + "://" + endpoint
protocol, addr, err = parseEndpoint(fallbackEndpoint) protocol, addr, err = parseEndpoint(fallbackEndpoint)
if err == nil { if err == nil {
glog.Warningf("Using %q as endpoint is deprecated, please consider using full url format %q.", endpoint, fallbackEndpoint) klog.Warningf("Using %q as endpoint is deprecated, please consider using full url format %q.", endpoint, fallbackEndpoint)
} }
} }
return return
} }
func parseEndpoint(endpoint string) (string, string, error) {
u, err := url.Parse(endpoint)
if err != nil {
return "", "", err
}
switch u.Scheme {
case "tcp":
return "tcp", u.Host, nil
case "unix":
return "unix", u.Path, nil
case "":
return "", "", fmt.Errorf("Using %q as endpoint is deprecated, please consider using full url format", endpoint)
default:
return u.Scheme, "", fmt.Errorf("protocol %q not supported", u.Scheme)
}
}
// LocalEndpoint returns the full path to a unix socket at the given endpoint
func LocalEndpoint(path, file string) string {
u := url.URL{
Scheme: unixProtocol,
Path: path,
}
return filepath.Join(u.String(), file+".sock")
}

View File

@ -40,3 +40,8 @@ func LockAndCheckSubPath(volumePath, subPath string) ([]uintptr, error) {
// UnlockPath empty implementation // UnlockPath empty implementation
func UnlockPath(fileHandles []uintptr) { func UnlockPath(fileHandles []uintptr) {
} }
// LocalEndpoint empty implementation
func LocalEndpoint(path, file string) string {
return ""
}

View File

@ -21,11 +21,16 @@ package util
import ( import (
"fmt" "fmt"
"net" "net"
"net/url"
"strings"
"time" "time"
"github.com/Microsoft/go-winio"
) )
const ( const (
tcpProtocol = "tcp" tcpProtocol = "tcp"
npipeProtocol = "npipe"
) )
func CreateListener(endpoint string) (net.Listener, error) { func CreateListener(endpoint string) (net.Listener, error) {
@ -33,11 +38,17 @@ func CreateListener(endpoint string) (net.Listener, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
if protocol != tcpProtocol {
return nil, fmt.Errorf("only support tcp endpoint")
}
return net.Listen(protocol, addr) switch protocol {
case tcpProtocol:
return net.Listen(tcpProtocol, addr)
case npipeProtocol:
return winio.ListenPipe(addr, nil)
default:
return nil, fmt.Errorf("only support tcp and npipe endpoint")
}
} }
func GetAddressAndDialer(endpoint string) (string, func(addr string, timeout time.Duration) (net.Conn, error), error) { func GetAddressAndDialer(endpoint string) (string, func(addr string, timeout time.Duration) (net.Conn, error), error) {
@ -45,13 +56,59 @@ func GetAddressAndDialer(endpoint string) (string, func(addr string, timeout tim
if err != nil { if err != nil {
return "", nil, err return "", nil, err
} }
if protocol != tcpProtocol {
return "", nil, fmt.Errorf("only support tcp endpoint") if protocol == tcpProtocol {
return addr, tcpDial, nil
} }
return addr, dial, nil if protocol == npipeProtocol {
return addr, npipeDial, nil
} }
func dial(addr string, timeout time.Duration) (net.Conn, error) { return "", nil, fmt.Errorf("only support tcp and npipe endpoint")
}
func tcpDial(addr string, timeout time.Duration) (net.Conn, error) {
return net.DialTimeout(tcpProtocol, addr, timeout) return net.DialTimeout(tcpProtocol, addr, timeout)
} }
func npipeDial(addr string, timeout time.Duration) (net.Conn, error) {
return winio.DialPipe(addr, &timeout)
}
func parseEndpoint(endpoint string) (string, string, error) {
// url.Parse doesn't recognize \, so replace with / first.
endpoint = strings.Replace(endpoint, "\\", "/", -1)
u, err := url.Parse(endpoint)
if err != nil {
return "", "", err
}
if u.Scheme == "tcp" {
return "tcp", u.Host, nil
} else if u.Scheme == "npipe" {
if strings.HasPrefix(u.Path, "//./pipe") {
return "npipe", u.Path, nil
}
// fallback host if not provided.
host := u.Host
if host == "" {
host = "."
}
return "npipe", fmt.Sprintf("//%s%s", host, u.Path), nil
} else if u.Scheme == "" {
return "", "", fmt.Errorf("Using %q as endpoint is deprecated, please consider using full url format", endpoint)
} else {
return u.Scheme, "", fmt.Errorf("protocol %q not supported", u.Scheme)
}
}
// LocalEndpoint returns the full path to a windows named pipe
func LocalEndpoint(path, file string) string {
u := url.URL{
Scheme: npipeProtocol,
Path: path,
}
return u.String() + "//./pipe/" + file
}

6
vendor/k8s.io/utils/README.md generated vendored
View File

@ -48,6 +48,12 @@ an existing package to this repository.
- [Pointers](/pointers) provides some functions for pointer-based operations. - [Pointers](/pointers) provides some functions for pointer-based operations.
- [Io](/io) provides interfaces for working with file IO. Currently it provides
functionality for consistently reading a file.
- [NSEnter](/nsenter) provies interfaces for executing and interacting with
processes running within a namespace.
[Build Status]: https://travis-ci.org/kubernetes/utils.svg?branch=master [Build Status]: https://travis-ci.org/kubernetes/utils.svg?branch=master
[Go standard libs]: https://golang.org/pkg/#stdlib [Go standard libs]: https://golang.org/pkg/#stdlib
[api]: https://github.com/kubernetes/api [api]: https://github.com/kubernetes/api

37
vendor/k8s.io/utils/exec/exec.go generated vendored
View File

@ -60,6 +60,17 @@ type Cmd interface {
SetStdin(in io.Reader) SetStdin(in io.Reader)
SetStdout(out io.Writer) SetStdout(out io.Writer)
SetStderr(out io.Writer) SetStderr(out io.Writer)
SetEnv(env []string)
// StdoutPipe and StderrPipe for getting the process' Stdout and Stderr as
// Readers
StdoutPipe() (io.ReadCloser, error)
StderrPipe() (io.ReadCloser, error)
// Start and Wait are for running a process non-blocking
Start() error
Wait() error
// Stops the command by sending SIGTERM. It is not guaranteed the // Stops the command by sending SIGTERM. It is not guaranteed the
// process will stop before this function returns. If the process is not // process will stop before this function returns. If the process is not
// responding, an internal timer function will send a SIGKILL to force // responding, an internal timer function will send a SIGKILL to force
@ -121,6 +132,30 @@ func (cmd *cmdWrapper) SetStderr(out io.Writer) {
cmd.Stderr = out cmd.Stderr = out
} }
func (cmd *cmdWrapper) SetEnv(env []string) {
cmd.Env = env
}
func (cmd *cmdWrapper) StdoutPipe() (io.ReadCloser, error) {
r, err := (*osexec.Cmd)(cmd).StdoutPipe()
return r, handleError(err)
}
func (cmd *cmdWrapper) StderrPipe() (io.ReadCloser, error) {
r, err := (*osexec.Cmd)(cmd).StderrPipe()
return r, handleError(err)
}
func (cmd *cmdWrapper) Start() error {
err := (*osexec.Cmd)(cmd).Start()
return handleError(err)
}
func (cmd *cmdWrapper) Wait() error {
err := (*osexec.Cmd)(cmd).Wait()
return handleError(err)
}
// Run is part of the Cmd interface. // Run is part of the Cmd interface.
func (cmd *cmdWrapper) Run() error { func (cmd *cmdWrapper) Run() error {
err := (*osexec.Cmd)(cmd).Run() err := (*osexec.Cmd)(cmd).Run()
@ -206,10 +241,12 @@ func (e CodeExitError) String() string {
return e.Err.Error() return e.Err.Error()
} }
// Exited is to check if the process has finished
func (e CodeExitError) Exited() bool { func (e CodeExitError) Exited() bool {
return true return true
} }
// ExitStatus is for checking the error code
func (e CodeExitError) ExitStatus() int { func (e CodeExitError) ExitStatus() int {
return e.Code return e.Code
} }

View File

@ -1,6 +1,7 @@
// Copyright 2013 The Go Authors. All rights reserved. // Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style // Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package yaml package yaml
import ( import (

View File

@ -4,13 +4,14 @@ import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io"
"reflect" "reflect"
"strconv" "strconv"
"gopkg.in/yaml.v2" "gopkg.in/yaml.v2"
) )
// Marshals the object into JSON then converts JSON to YAML and returns the // Marshal marshals the object into JSON then converts JSON to YAML and returns the
// YAML. // YAML.
func Marshal(o interface{}) ([]byte, error) { func Marshal(o interface{}) ([]byte, error) {
j, err := json.Marshal(o) j, err := json.Marshal(o)
@ -26,15 +27,35 @@ func Marshal(o interface{}) ([]byte, error) {
return y, nil return y, nil
} }
// Converts YAML to JSON then uses JSON to unmarshal into an object. // JSONOpt is a decoding option for decoding from JSON format.
func Unmarshal(y []byte, o interface{}) error { type JSONOpt func(*json.Decoder) *json.Decoder
// Unmarshal converts YAML to JSON then uses JSON to unmarshal into an object,
// optionally configuring the behavior of the JSON unmarshal.
func Unmarshal(y []byte, o interface{}, opts ...JSONOpt) error {
return yamlUnmarshal(y, o, false, opts...)
}
// UnmarshalStrict strictly converts YAML to JSON then uses JSON to unmarshal
// into an object, optionally configuring the behavior of the JSON unmarshal.
func UnmarshalStrict(y []byte, o interface{}, opts ...JSONOpt) error {
return yamlUnmarshal(y, o, true, append(opts, DisallowUnknownFields)...)
}
// yamlUnmarshal unmarshals the given YAML byte stream into the given interface,
// optionally performing the unmarshalling strictly
func yamlUnmarshal(y []byte, o interface{}, strict bool, opts ...JSONOpt) error {
vo := reflect.ValueOf(o) vo := reflect.ValueOf(o)
j, err := yamlToJSON(y, &vo) unmarshalFn := yaml.Unmarshal
if strict {
unmarshalFn = yaml.UnmarshalStrict
}
j, err := yamlToJSON(y, &vo, unmarshalFn)
if err != nil { if err != nil {
return fmt.Errorf("error converting YAML to JSON: %v", err) return fmt.Errorf("error converting YAML to JSON: %v", err)
} }
err = json.Unmarshal(j, o) err = jsonUnmarshal(bytes.NewReader(j), o, opts...)
if err != nil { if err != nil {
return fmt.Errorf("error unmarshaling JSON: %v", err) return fmt.Errorf("error unmarshaling JSON: %v", err)
} }
@ -42,7 +63,22 @@ func Unmarshal(y []byte, o interface{}) error {
return nil return nil
} }
// Convert JSON to YAML. // jsonUnmarshal unmarshals the JSON byte stream from the given reader into the
// object, optionally applying decoder options prior to decoding. We are not
// using json.Unmarshal directly as we want the chance to pass in non-default
// options.
func jsonUnmarshal(r io.Reader, o interface{}, opts ...JSONOpt) error {
d := json.NewDecoder(r)
for _, opt := range opts {
d = opt(d)
}
if err := d.Decode(&o); err != nil {
return fmt.Errorf("while decoding JSON: %v", err)
}
return nil
}
// JSONToYAML Converts JSON to YAML.
func JSONToYAML(j []byte) ([]byte, error) { func JSONToYAML(j []byte) ([]byte, error) {
// Convert the JSON to an object. // Convert the JSON to an object.
var jsonObj interface{} var jsonObj interface{}
@ -60,8 +96,8 @@ func JSONToYAML(j []byte) ([]byte, error) {
return yaml.Marshal(jsonObj) return yaml.Marshal(jsonObj)
} }
// Convert YAML to JSON. Since JSON is a subset of YAML, passing JSON through // YAMLToJSON converts YAML to JSON. Since JSON is a subset of YAML,
// this method should be a no-op. // passing JSON through this method should be a no-op.
// //
// Things YAML can do that are not supported by JSON: // Things YAML can do that are not supported by JSON:
// * In YAML you can have binary and null keys in your maps. These are invalid // * In YAML you can have binary and null keys in your maps. These are invalid
@ -70,14 +106,22 @@ func JSONToYAML(j []byte) ([]byte, error) {
// use binary data with this library, encode the data as base64 as usual but do // use binary data with this library, encode the data as base64 as usual but do
// not use the !!binary tag in your YAML. This will ensure the original base64 // not use the !!binary tag in your YAML. This will ensure the original base64
// encoded data makes it all the way through to the JSON. // encoded data makes it all the way through to the JSON.
//
// For strict decoding of YAML, use YAMLToJSONStrict.
func YAMLToJSON(y []byte) ([]byte, error) { func YAMLToJSON(y []byte) ([]byte, error) {
return yamlToJSON(y, nil) return yamlToJSON(y, nil, yaml.Unmarshal)
} }
func yamlToJSON(y []byte, jsonTarget *reflect.Value) ([]byte, error) { // YAMLToJSONStrict is like YAMLToJSON but enables strict YAML decoding,
// returning an error on any duplicate field names.
func YAMLToJSONStrict(y []byte) ([]byte, error) {
return yamlToJSON(y, nil, yaml.UnmarshalStrict)
}
func yamlToJSON(y []byte, jsonTarget *reflect.Value, yamlUnmarshal func([]byte, interface{}) error) ([]byte, error) {
// Convert the YAML to an object. // Convert the YAML to an object.
var yamlObj interface{} var yamlObj interface{}
err := yaml.Unmarshal(y, &yamlObj) err := yamlUnmarshal(y, &yamlObj)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -272,6 +316,4 @@ func convertToJSONableObject(yamlObj interface{}, jsonTarget *reflect.Value) (in
} }
return yamlObj, nil return yamlObj, nil
} }
return nil, nil
} }

Some files were not shown because too many files have changed in this diff Show More