kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" '' # Command kubectl get pods --sort-by="{metadata.name}" <ins> kubectl get pods --sort-by="{metadata.creationTimestamp}" </ins> ############################ # Kubectl --all-namespaces #


"sort" "k8s.io/kubernetes/pkg/api/meta" <ins> "k8s.io/kubernetes/pkg/api/unversioned" </ins> "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/runtime" <ins> "k8s.io/kubernetes/pkg/util/integer" </ins> "k8s.io/kubernetes/pkg/util/jsonpath" "github.com/golang/glog"


return i.String() < j.String(), nil case reflect.Ptr: return isLess(i.Elem(), j.Elem()) <ins> case reflect.Struct: // special case handling lessFuncList := []structLessFunc{timeLess} if ok, less := structLess(i, j, lessFuncList); ok { return less, nil } // fallback to the fields comparision for idx := 0; idx < i.NumField(); idx++ { less, err := isLess(i.Field(idx), j.Field(idx)) if err != nil || !less { return less, err } } return true, nil case reflect.Array, reflect.Slice: // note: the length of i and j may be different for idx := 0; idx < integer.IntMin(i.Len(), j.Len()); idx++ { less, err := isLess(i.Index(idx), j.Index(idx)) if err != nil || !less { return less, err } } return true, nil </ins> default: return false, fmt.Errorf("unsortable type: %v", i.Kind()) } } <ins> // structLessFunc checks whether i and j could be compared(the first return value), // and if it could, return whether i is less than j(the second return value) type structLessFunc func(i, j reflect.Value) (bool, bool) // structLess returns whether i and j could be compared with the given function list func structLess(i, j reflect.Value, lessFuncList []structLessFunc) (bool, bool) { for _, lessFunc := range lessFuncList { if ok, less := lessFunc(i, j); ok { return ok, less } } return false, false } // compare two unversioned.Time values. func timeLess(i, j reflect.Value) (bool, bool) { if i.Type() != reflect.TypeOf(unversioned.Unix(0, 0)) { return false, false } return true, i.MethodByName("Before").Call([]reflect.Value{j})[0].Bool() } </ins> func (r *RuntimeSort) Less(i, j int) bool { iObj := r.objs[i] jObj := r.objs[j]


"testing" internal "k8s.io/kubernetes/pkg/api" <ins> "k8s.io/kubernetes/pkg/api/unversioned" </ins> api "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/runtime" )


field: "{.metadata.name}", }, { <ins> name: "random-order-timestamp", obj: &api.PodList{ Items: []api.Pod{ { ObjectMeta: api.ObjectMeta{ CreationTimestamp: unversioned.Unix(300, 0), }, }, { ObjectMeta: api.ObjectMeta{ CreationTimestamp: unversioned.Unix(100, 0), }, }, { ObjectMeta: api.ObjectMeta{ CreationTimestamp: unversioned.Unix(200, 0), }, }, }, }, sort: &api.PodList{ Items: []api.Pod{ { ObjectMeta: api.ObjectMeta{ CreationTimestamp: unversioned.Unix(100, 0), }, }, { ObjectMeta: api.ObjectMeta{ CreationTimestamp: unversioned.Unix(200, 0), }, }, { ObjectMeta: api.ObjectMeta{ CreationTimestamp: unversioned.Unix(300, 0), }, }, }, }, field: "{.metadata.creationTimestamp}", }, { </ins> name: "random-order-numbers", obj: &api.ReplicationControllerList{ Items: []api.ReplicationController{


<ins> /* Copyright 2016 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Code generated by protoc-gen-gogo. // source: k8s.io/kubernetes/pkg/apis/apps/v1alpha1/generated.proto // DO NOT EDIT! /* Package v1alpha1 is a generated protocol buffer package. It is generated from these files: k8s.io/kubernetes/pkg/apis/apps/v1alpha1/generated.proto It has these top-level messages: PetSet PetSetList PetSetSpec PetSetStatus */ package v1alpha1 import proto "github.com/gogo/protobuf/proto" import fmt "fmt" import math "math" import _ "github.com/gogo/protobuf/gogoproto" import _ "k8s.io/kubernetes/pkg/api/resource" import k8s_io_kubernetes_pkg_api_unversioned "k8s.io/kubernetes/pkg/api/unversioned" import k8s_io_kubernetes_pkg_api_v1 "k8s.io/kubernetes/pkg/api/v1" import _ "k8s.io/kubernetes/pkg/util/intstr" import io "io" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf func (m *PetSet) Reset()         { *m = PetSet{} } func (m *PetSet) String() string { return proto.CompactTextString(m) } func (*PetSet) ProtoMessage()    {} func (m *PetSetList) Reset()         { *m = PetSetList{} } func (m *PetSetList) String() string { return proto.CompactTextString(m) } func (*PetSetList) ProtoMessage()    {} func (m *PetSetSpec) Reset()         { *m = PetSetSpec{} } func (m *PetSetSpec) String() string { return proto.CompactTextString(m) } func (*PetSetSpec) ProtoMessage()    {} func (m *PetSetStatus) Reset()         { *m = PetSetStatus{} } func (m *PetSetStatus) String() string { return proto.CompactTextString(m) } func (*PetSetStatus) ProtoMessage()    {} func init() { proto.RegisterType((*PetSet)(nil), "k8s.io.kubernetes.pkg.apis.apps.v1alpha1.PetSet") proto.RegisterType((*PetSetList)(nil), "k8s.io.kubernetes.pkg.apis.apps.v1alpha1.PetSetList") proto.RegisterType((*PetSetSpec)(nil), "k8s.io.kubernetes.pkg.apis.apps.v1alpha1.PetSetSpec") proto.RegisterType((*PetSetStatus)(nil), "k8s.io.kubernetes.pkg.apis.apps.v1alpha1.PetSetStatus") } func (m *PetSet) Marshal() (data []byte, err error) { size := m.Size() data = make([]byte, size) n, err := m.MarshalTo(data) if err != nil { return nil, err } return data[:n], nil } func (m *PetSet) MarshalTo(data []byte) (int, error) { var i int _ = i var l int _ = l data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ObjectMeta.Size())) n1, err := m.ObjectMeta.MarshalTo(data[i:]) if err != nil { return 0, err } i += n1 data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64(m.Spec.Size())) n2, err := m.Spec.MarshalTo(data[i:]) if err != nil { return 0, err } i += n2 data[i] = 0x1a i++ i = encodeVarintGenerated(data, i, uint64(m.Status.Size())) n3, err := m.Status.MarshalTo(data[i:]) if err != nil { return 0, err } i += n3 return i, nil } func (m *PetSetList) Marshal() (data []byte, err error) { size := m.Size() data = make([]byte, size) n, err := m.MarshalTo(data) if err != nil { return nil, err } return data[:n], nil } func (m *PetSetList) MarshalTo(data []byte) (int, error) { var i int _ = i var l int _ = l data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ListMeta.Size())) n4, err := m.ListMeta.MarshalTo(data[i:]) if err != nil { return 0, err } i += n4 if len(m.Items) > 0 { for _, msg := range m.Items { data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64(msg.Size())) n, err := msg.MarshalTo(data[i:]) if err != nil { return 0, err } i += n } } return i, nil } func (m *PetSetSpec) Marshal() (data []byte, err error) { size := m.Size() data = make([]byte, size) n, err := m.MarshalTo(data) if err != nil { return nil, err } return data[:n], nil } func (m *PetSetSpec) MarshalTo(data []byte) (int, error) { var i int _ = i var l int _ = l if m.Replicas != nil { data[i] = 0x8 i++ i = encodeVarintGenerated(data, i, uint64(*m.Replicas)) } if m.Selector != nil { data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64(m.Selector.Size())) n5, err := m.Selector.MarshalTo(data[i:]) if err != nil { return 0, err } i += n5 } data[i] = 0x1a i++ i = encodeVarintGenerated(data, i, uint64(m.Template.Size())) n6, err := m.Template.MarshalTo(data[i:]) if err != nil { return 0, err } i += n6 if len(m.VolumeClaimTemplates) > 0 { for _, msg := range m.VolumeClaimTemplates { data[i] = 0x22 i++ i = encodeVarintGenerated(data, i, uint64(msg.Size())) n, err := msg.MarshalTo(data[i:]) if err != nil { return 0, err } i += n } } data[i] = 0x2a i++ i = encodeVarintGenerated(data, i, uint64(len(m.ServiceName))) i += copy(data[i:], m.ServiceName) return i, nil } func (m *PetSetStatus) Marshal() (data []byte, err error) { size := m.Size() data = make([]byte, size) n, err := m.MarshalTo(data) if err != nil { return nil, err } return data[:n], nil } func (m *PetSetStatus) MarshalTo(data []byte) (int, error) { var i int _ = i var l int _ = l if m.ObservedGeneration != nil { data[i] = 0x8 i++ i = encodeVarintGenerated(data, i, uint64(*m.ObservedGeneration)) } data[i] = 0x10 i++ i = encodeVarintGenerated(data, i, uint64(m.Replicas)) 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 { for v >= 1<<7 { data[offset] = uint8(v&0x7f | 0x80) v >>= 7 offset++ } data[offset] = uint8(v) return offset + 1 } func (m *PetSet) Size() (n int) { var l int _ = l l = m.ObjectMeta.Size() n += 1 + l + sovGenerated(uint64(l)) l = m.Spec.Size() n += 1 + l + sovGenerated(uint64(l)) l = m.Status.Size() n += 1 + l + sovGenerated(uint64(l)) return n } func (m *PetSetList) Size() (n int) { var l int _ = l l = m.ListMeta.Size() n += 1 + l + sovGenerated(uint64(l)) if len(m.Items) > 0 { for _, e := range m.Items { l = e.Size() n += 1 + l + sovGenerated(uint64(l)) } } return n } func (m *PetSetSpec) Size() (n int) { var l int _ = l if m.Replicas != nil { n += 1 + sovGenerated(uint64(*m.Replicas)) } if m.Selector != nil { l = m.Selector.Size() n += 1 + l + sovGenerated(uint64(l)) } l = m.Template.Size() n += 1 + l + sovGenerated(uint64(l)) if len(m.VolumeClaimTemplates) > 0 { for _, e := range m.VolumeClaimTemplates { l = e.Size() n += 1 + l + sovGenerated(uint64(l)) } } l = len(m.ServiceName) n += 1 + l + sovGenerated(uint64(l)) return n } func (m *PetSetStatus) Size() (n int) { var l int _ = l if m.ObservedGeneration != nil { n += 1 + sovGenerated(uint64(*m.ObservedGeneration)) } n += 1 + sovGenerated(uint64(m.Replicas)) return n } func sovGenerated(x uint64) (n int) { for { n++ x >>= 7 if x == 0 { break } } return n } func sozGenerated(x uint64) (n int) { return sovGenerated(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } func (m *PetSet) Unmarshal(data []byte) error { l := len(data) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := data[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: PetSet: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: PetSet: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := data[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } if err := m.ObjectMeta.Unmarshal(data[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := data[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } if err := m.Spec.Unmarshal(data[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := data[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } if err := m.Status.Unmarshal(data[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(data[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthGenerated } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *PetSetList) Unmarshal(data []byte) error { l := len(data) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := data[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: PetSetList: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: PetSetList: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ListMeta", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := data[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } if err := m.ListMeta.Unmarshal(data[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := data[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } m.Items = append(m.Items, PetSet{}) if err := m.Items[len(m.Items)-1].Unmarshal(data[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(data[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthGenerated } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *PetSetSpec) Unmarshal(data []byte) error { l := len(data) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := data[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: PetSetSpec: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: PetSetSpec: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Replicas", wireType) } var v int32 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := data[iNdEx] iNdEx++ v |= (int32(b) & 0x7F) << shift if b < 0x80 { break } } m.Replicas = &v case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Selector", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := data[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } if m.Selector == nil { m.Selector = &k8s_io_kubernetes_pkg_api_unversioned.LabelSelector{} } if err := m.Selector.Unmarshal(data[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Template", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := data[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } if err := m.Template.Unmarshal(data[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 4: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field VolumeClaimTemplates", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := data[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } m.VolumeClaimTemplates = append(m.VolumeClaimTemplates, k8s_io_kubernetes_pkg_api_v1.PersistentVolumeClaim{}) if err := m.VolumeClaimTemplates[len(m.VolumeClaimTemplates)-1].Unmarshal(data[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 5: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ServiceName", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := data[iNdEx] iNdEx++ stringLen |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + intStringLen if postIndex > l { return io.ErrUnexpectedEOF } m.ServiceName = string(data[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(data[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthGenerated } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *PetSetStatus) Unmarshal(data []byte) error { l := len(data) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := data[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: PetSetStatus: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: PetSetStatus: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field ObservedGeneration", wireType) } var v int64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := data[iNdEx] iNdEx++ v |= (int64(b) & 0x7F) << shift if b < 0x80 { break } } m.ObservedGeneration = &v case 2: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Replicas", wireType) } m.Replicas = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := data[iNdEx] iNdEx++ m.Replicas |= (int32(b) & 0x7F) << shift if b < 0x80 { break } } default: iNdEx = preIndex skippy, err := skipGenerated(data[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthGenerated } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func skipGenerated(data []byte) (n int, err error) { l := len(data) iNdEx := 0 for iNdEx < l { var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowGenerated } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := data[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } wireType := int(wire & 0x7) switch wireType { case 0: for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowGenerated } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } iNdEx++ if data[iNdEx-1] < 0x80 { break } } return iNdEx, nil case 1: iNdEx += 8 return iNdEx, nil case 2: var length int for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowGenerated } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := data[iNdEx] iNdEx++ length |= (int(b) & 0x7F) << shift if b < 0x80 { break } } iNdEx += length if length < 0 { return 0, ErrInvalidLengthGenerated } return iNdEx, nil case 3: for { var innerWire uint64 var start int = iNdEx for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowGenerated } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := data[iNdEx] iNdEx++ innerWire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } innerWireType := int(innerWire & 0x7) if innerWireType == 4 { break } next, err := skipGenerated(data[start:]) if err != nil { return 0, err } iNdEx = start + next } return iNdEx, nil case 4: return iNdEx, nil case 5: iNdEx += 4 return iNdEx, nil default: return 0, fmt.Errorf("proto: illegal wireType %d", wireType) } } panic("unreachable") } var ( ErrInvalidLengthGenerated = fmt.Errorf("proto: negative length found during unmarshaling") ErrIntOverflowGenerated   = fmt.Errorf("proto: integer overflow") ) </ins>


<ins> /* Copyright 2016 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // This file was autogenerated by go-to-protobuf. Do not edit it manually! syntax = 'proto2'; package k8s.io.kubernetes.pkg.apis.apps.v1alpha1; import "k8s.io/kubernetes/pkg/api/resource/generated.proto"; import "k8s.io/kubernetes/pkg/api/unversioned/generated.proto"; import "k8s.io/kubernetes/pkg/api/v1/generated.proto"; import "k8s.io/kubernetes/pkg/util/intstr/generated.proto"; // Package-wide variables from generator "generated". option go_package = "v1alpha1"; // PetSet represents a set of pods with consistent identities. // Identities are defined as: //  - Network: A single stable DNS and hostname. //  - Storage: As many VolumeClaims as requested. // The PetSet guarantees that a given network identity will always // map to the same storage identity. PetSet is currently in alpha // and subject to change without notice. message PetSet { optional k8s.io.kubernetes.pkg.api.v1.ObjectMeta metadata = 1; // Spec defines the desired identities of pets in this set. optional PetSetSpec spec = 2; // Status is the current status of Pets in this PetSet. This data // may be out of date by some window of time. optional PetSetStatus status = 3; } // PetSetList is a collection of PetSets. message PetSetList { optional k8s.io.kubernetes.pkg.api.unversioned.ListMeta metadata = 1; repeated PetSet items = 2; } // A PetSetSpec is the specification of a PetSet. message PetSetSpec { // Replicas is the desired number of replicas of the given Template. // These are replicas in the sense that they are instantiations of the // same Template, but individual replicas also have a consistent identity. // If unspecified, defaults to 1. // TODO: Consider a rename of this field. optional int32 replicas = 1; // Selector is a label query over pods that should match the replica count. // If empty, defaulted to labels on the pod template. // More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors optional k8s.io.kubernetes.pkg.api.unversioned.LabelSelector selector = 2; // Template is the object that describes the pod that will be created if // insufficient replicas are detected. Each pod stamped out by the PetSet // will fulfill this Template, but have a unique identity from the rest // of the PetSet. optional k8s.io.kubernetes.pkg.api.v1.PodTemplateSpec template = 3; // VolumeClaimTemplates is a list of claims that pets are allowed to reference. // The PetSet controller is responsible for mapping network identities to // claims in a way that maintains the identity of a pet. Every claim in // this list must have at least one matching (by name) volumeMount in one // container in the template. A claim in this list takes precedence over // any volumes in the template, with the same name. // TODO: Define the behavior if a claim already exists with the same name. repeated k8s.io.kubernetes.pkg.api.v1.PersistentVolumeClaim volumeClaimTemplates = 4; // ServiceName is the name of the service that governs this PetSet. // This service must exist before the PetSet, and is responsible for // the network identity of the set. Pets get DNS/hostnames that follow the // pattern: pet-specific-string.serviceName.default.svc.cluster.local // where "pet-specific-string" is managed by the PetSet controller. optional string serviceName = 5; } // PetSetStatus represents the current state of a PetSet. message PetSetStatus { // most recent generation observed by this autoscaler. optional int64 observedGeneration = 1; // Replicas is the number of actual replicas. optional int32 replicas = 2; } </ins>


if !options.Local { helper := resource.NewHelper(client, mapping) <del> patchedObject, err := helper.Patch(namespace, name, patchType, patchBytes) </del> <ins> _, err := helper.Patch(namespace, name, patchType, patchBytes) </ins> if err != nil { return err } if cmdutil.ShouldRecord(cmd, info) { <del> if err := cmdutil.RecordChangeCause(patchedObject, f.Command()); err == nil { // don't return an error on failure.  The patch itself succeeded, its only the hint for that change that failed // don't bother checking for failures of this replace, because a failure to indicate the hint doesn't fail the command // also, don't force the replacement.  If the replacement fails on a resourceVersion conflict, then it means this // record hint is likely to be invalid anyway, so avoid the bad hint resource.NewHelper(client, mapping).Replace(namespace, name, false, patchedObject) </del> <ins> // don't return an error on failure.  The patch itself succeeded, its only the hint for that change that failed // don't bother checking for failures of this replace, because a failure to indicate the hint doesn't fail the command // also, don't force the replacement.  If the replacement fails on a resourceVersion conflict, then it means this // record hint is likely to be invalid anyway, so avoid the bad hint patch, err := cmdutil.ChangeResourcePatch(info, f.Command()) if err == nil { helper.Patch(info.Namespace, info.Name, api.StrategicMergePatchType, patch) </ins> } } count++


} // TODO: if we ever want to go generic, this allows a clean -o yaml without trying to print columns or anything // rawExtension := &runtime.Unknown{ <del> // 	Raw: originalPatchedObjJS, </del> <ins> //	Raw: originalPatchedObjJS, </ins> // } printer, err := f.PrinterForMapping(cmd, mapping, false)


} func TestDelNode(t *testing.T) { <ins> defer func() { now = time.Now }() var tick int64 now = func() time.Time { t := time.Unix(tick, 0) tick++ return t } </ins> evictor := NewRateLimitedTimedQueue(flowcontrol.NewFakeAlwaysRateLimiter()) evictor.Add("first") evictor.Add("second")


tar xf elasticsearch-1.5.2.tar.gz &&  rm elasticsearch-1.5.2.tar.gz <ins> RUN mkdir -p /elasticsearch-1.5.2/config/templates </ins> COPY elasticsearch.yml /elasticsearch-1.5.2/config/elasticsearch.yml <ins> COPY template-k8s-logstash.json /elasticsearch-1.5.2/config/templates/template-k8s-logstash.json </ins> COPY run.sh / COPY elasticsearch_logging_discovery /


<ins> { "template_k8s_logstash" : { "template" : "logstash-*", "settings" : { "index.refresh_interval" : "5s" }, "mappings" : { "_default_" : { "dynamic_templates" : [ { "kubernetes_field" : { "path_match" : "kubernetes.*", "mapping" : { "type" : "string", "index" : "not_analyzed" } } } ] } } } } </ins>


kube::etcd::install() { ( cd "${KUBE_ROOT}/third_party" <del> curl -fsSL --retry 3 https://github.com/coreos/etcd/releases/download/v${ETCD_VERSION}/etcd-v${ETCD_VERSION}-linux-amd64.tar.gz | tar xzf - ln -fns "etcd-v${ETCD_VERSION}-linux-amd64" etcd </del> <ins> if [[ $(uname) == "Darwin" ]]; then download_file="etcd-v${ETCD_VERSION}-darwin-amd64.zip" curl -fsSLO --retry 3 https://github.com/coreos/etcd/releases/download/v${ETCD_VERSION}/"${download_file}" unzip -o "${download_file}" ln -fns "etcd-v${ETCD_VERSION}-darwin-amd64" etcd rm "${download_file}" else curl -fsSL --retry 3 https://github.com/coreos/etcd/releases/download/v${ETCD_VERSION}/etcd-v${ETCD_VERSION}-linux-amd64.tar.gz | tar xzf - ln -fns "etcd-v${ETCD_VERSION}-linux-amd64" etcd fi </ins> kube::log::info "etcd v${ETCD_VERSION} installed. To use:" kube::log::info "export PATH=${PATH}:$(pwd)/etcd" )


<ins> /* Copyright 2016 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package core import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/runtime" ) func addDefaultingFuncs(scheme *runtime.Scheme) { scheme.AddDefaultingFuncs( func(obj *api.ListOptions) { if obj.LabelSelector == nil { obj.LabelSelector = labels.Everything() } if obj.FieldSelector == nil { obj.FieldSelector = fields.Everything() } }, ) } func addConversionFuncs(scheme *runtime.Scheme) { scheme.AddConversionFuncs( api.Convert_unversioned_TypeMeta_To_unversioned_TypeMeta, api.Convert_unversioned_ListMeta_To_unversioned_ListMeta, api.Convert_intstr_IntOrString_To_intstr_IntOrString, api.Convert_unversioned_Time_To_unversioned_Time, api.Convert_Slice_string_To_unversioned_Time, api.Convert_string_To_labels_Selector, api.Convert_string_To_fields_Selector, api.Convert_Pointer_bool_To_bool, api.Convert_bool_To_Pointer_bool, api.Convert_Pointer_string_To_string, api.Convert_string_To_Pointer_string, api.Convert_labels_Selector_To_string, api.Convert_fields_Selector_To_string, api.Convert_resource_Quantity_To_resource_Quantity, ) } </ins>


<ins> /* Copyright 2016 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package core import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/runtime" ) func addDeepCopyFuncs(scheme *runtime.Scheme) { if err := scheme.AddGeneratedDeepCopyFuncs( api.DeepCopy_api_DeleteOptions, api.DeepCopy_api_ExportOptions, api.DeepCopy_api_List, api.DeepCopy_api_ListOptions, api.DeepCopy_api_ObjectMeta, api.DeepCopy_api_ObjectReference, api.DeepCopy_api_OwnerReference, api.DeepCopy_api_Service, api.DeepCopy_api_ServiceList, api.DeepCopy_api_ServicePort, api.DeepCopy_api_ServiceSpec, api.DeepCopy_api_ServiceStatus, ); err != nil { // if one of the deep copy functions is malformed, detect it immediately. panic(err) } } </ins>


&unversioned.APIGroup{}, &unversioned.APIResourceList{}, ) <ins> addDeepCopyFuncs(scheme) addDefaultingFuncs(scheme) addConversionFuncs(scheme) </ins> }


import ( "fmt" <del> "k8s.io/kubernetes/pkg/api" </del> "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/runtime" )


func addConversionFuncs(scheme *runtime.Scheme) { // Add non-generated conversion functions err := scheme.AddConversionFuncs( <del> v1.Convert_api_ServiceSpec_To_v1_ServiceSpec, </del> <ins> v1.Convert_v1_DeleteOptions_To_api_DeleteOptions, v1.Convert_api_DeleteOptions_To_v1_DeleteOptions, v1.Convert_v1_ExportOptions_To_api_ExportOptions, v1.Convert_api_ExportOptions_To_v1_ExportOptions, v1.Convert_v1_List_To_api_List, v1.Convert_api_List_To_v1_List, v1.Convert_v1_ListOptions_To_api_ListOptions, v1.Convert_api_ListOptions_To_v1_ListOptions, v1.Convert_v1_ObjectFieldSelector_To_api_ObjectFieldSelector, v1.Convert_api_ObjectFieldSelector_To_v1_ObjectFieldSelector, v1.Convert_v1_ObjectMeta_To_api_ObjectMeta, v1.Convert_api_ObjectMeta_To_v1_ObjectMeta, v1.Convert_v1_ObjectReference_To_api_ObjectReference, v1.Convert_api_ObjectReference_To_v1_ObjectReference, v1.Convert_v1_OwnerReference_To_api_OwnerReference, v1.Convert_api_OwnerReference_To_v1_OwnerReference, v1.Convert_v1_Service_To_api_Service, v1.Convert_api_Service_To_v1_Service, v1.Convert_v1_ServiceList_To_api_ServiceList, v1.Convert_api_ServiceList_To_v1_ServiceList, v1.Convert_v1_ServicePort_To_api_ServicePort, v1.Convert_api_ServicePort_To_v1_ServicePort, v1.Convert_v1_ServiceProxyOptions_To_api_ServiceProxyOptions, v1.Convert_api_ServiceProxyOptions_To_v1_ServiceProxyOptions, </ins> v1.Convert_v1_ServiceSpec_To_api_ServiceSpec, <ins> v1.Convert_api_ServiceSpec_To_v1_ServiceSpec, v1.Convert_v1_ServiceStatus_To_api_ServiceStatus, v1.Convert_api_ServiceStatus_To_v1_ServiceStatus, </ins> ) if err != nil { // If one of the conversion functions is malformed, detect it immediately.


for _, kind := range []string{ "Service", } { <del> err = api.Scheme.AddFieldLabelConversionFunc("v1", kind, </del> <ins> err = scheme.AddFieldLabelConversionFunc("v1", kind, </ins> func(label, value string) (string, string, error) { switch label { case "metadata.namespace",


<ins> /* Copyright 2016 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package v1 import ( "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/runtime" ) func addDeepCopyFuncs(scheme *runtime.Scheme) { if err := scheme.AddGeneratedDeepCopyFuncs( v1.DeepCopy_v1_DeleteOptions, v1.DeepCopy_v1_ExportOptions, v1.DeepCopy_v1_List, v1.DeepCopy_v1_ListOptions, v1.DeepCopy_v1_ObjectMeta, v1.DeepCopy_v1_ObjectReference, v1.DeepCopy_v1_OwnerReference, v1.DeepCopy_v1_Service, v1.DeepCopy_v1_ServiceList, v1.DeepCopy_v1_ServicePort, v1.DeepCopy_v1_ServiceSpec, v1.DeepCopy_v1_ServiceStatus, ); err != nil { // if one of the deep copy functions is malformed, detect it immediately. panic(err) } } </ins>


addKnownTypes(scheme) addConversionFuncs(scheme) addDefaultingFuncs(scheme) <ins> addDeepCopyFuncs(scheme) </ins> } // Adds the list of known types to api.Scheme.


func assertManagedStatus( config *KubeletManagedHostConfig, podName string, expectedIsManaged bool, name string) { <del> // See https://github.com/kubernetes/kubernetes/issues/27023 </del> <ins> // TODO: workaround for https://github.com/kubernetes/kubernetes/issues/34256 </ins> // <del> // Retry until timeout for the right contents of /etc/hosts to show // up. There may be a low probability race here. We still fail the // test if retry was necessary, but at least we will know whether or // not it resolves or seems to be a permanent condition. // // If /etc/hosts is properly mounted, then this will succeed // immediately. </del> <ins> // Retry until timeout for the contents of /etc/hosts to show // up. Note: if /etc/hosts is properly mounted, then this will // succeed immediately. </ins> const retryTimeout = 30 * time.Second retryCount := 0 etcHostsContent := "" <del> matched := false </del> for startTime := time.Now(); time.Since(startTime) < retryTimeout; { etcHostsContent = config.getEtcHostsContent(podName, name) isManaged := strings.Contains(etcHostsContent, etcHostsPartialContent) if expectedIsManaged == isManaged { <del> matched = true break </del> <ins> return </ins> } <del> glog.Errorf( </del> <ins> glog.Warningf( </ins> "For pod: %s, name: %s, expected %t, actual %t (/etc/hosts was %q), retryCount: %d", podName, name, expectedIsManaged, isManaged, etcHostsContent, retryCount)


time.Sleep(100 * time.Millisecond) } <del> if retryCount > 0 { if matched { conditionText := "should" if !expectedIsManaged { conditionText = "should not" } framework.Failf( "/etc/hosts file %s be kubelet managed (name: %s, retries: %d). /etc/hosts contains %q", conditionText, name, retryCount, etcHostsContent) } else { framework.Failf( "had to retry %d times to get matching content in /etc/hosts (name: %s)", retryCount, name) } </del> <ins> if expectedIsManaged { framework.Failf( "/etc/hosts file should be kubelet managed (name: %s, retries: %d). /etc/hosts contains %q", name, retryCount, etcHostsContent) } else { framework.Failf( "/etc/hosts file should no be kubelet managed (name: %s, retries: %d). /etc/hosts contains %q", name, retryCount, etcHostsContent) </ins> } }


var endpointColumns = []string{"NAME", "ENDPOINTS", "AGE"} var nodeColumns = []string{"NAME", "STATUS", "AGE"} var daemonSetColumns = []string{"NAME", "DESIRED", "CURRENT", "NODE-SELECTOR", "AGE"} <del> var eventColumns = []string{"FIRSTSEEN", "LASTSEEN", "COUNT", "NAME", "KIND", "SUBOBJECT", "TYPE", "REASON", "SOURCE", "MESSAGE"} </del> <ins> var eventColumns = []string{"LASTSEEN", "FIRSTSEEN", "COUNT", "NAME", "KIND", "SUBOBJECT", "TYPE", "REASON", "SOURCE", "MESSAGE"} </ins> var limitRangeColumns = []string{"NAME", "AGE"} var resourceQuotaColumns = []string{"NAME", "AGE"} var namespaceColumns = []string{"NAME", "STATUS", "AGE"}


if _, err := fmt.Fprintf( w, "%st%st%dt%st%st%st%st%st%st%s", <del> FirstTimestamp, </del> LastTimestamp, <ins> FirstTimestamp, </ins> event.Count, event.InvolvedObject.Name, event.InvolvedObject.Kind,


var k8sBinDir = flag.String("k8s-bin-dir", "", "Directory containing k8s kubelet and kube-apiserver binaries.") <del> var buildTargets = []string{ "cmd/kubelet", "cmd/kube-apiserver", "test/e2e_node/e2e_node.test", } </del> func buildGo() { glog.Infof("Building k8s binaries...") k8sRoot, err := getK8sRootDir() if err != nil { glog.Fatalf("Failed to locate kubernetes root directory %v.", err) } <del> cmd := exec.Command(filepath.Join(k8sRoot, "hack/build-go.sh"), buildTargets...) </del> <ins> cmd := exec.Command(filepath.Join(k8sRoot, "hack/build-go.sh")) </ins> cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr err = cmd.Run()


return "", err } if _, err := os.Stat(filepath.Join(*k8sBinDir, bin)); err != nil { <del> return "", fmt.Errorf("Could not find %s under directory %s.", bin, absPath) </del> <ins> return "", fmt.Errorf("Could not find kube-apiserver under directory %s.", absPath) </ins> } return filepath.Join(absPath, bin), nil }


kubectl replace "${kube_flags[@]}" --force -f /tmp/tmp-valid-pod.json # Post-condition: spec.container.name = "replaced-k8s-serve-hostname" kube::test::get_object_assert 'pod valid-pod' "{{(index .spec.containers 0).name}}" 'replaced-k8s-serve-hostname' <ins> ## check replace --grace-period requires --force output_message=$(! kubectl replace "${kube_flags[@]}" --grace-period=1 -f /tmp/tmp-valid-pod.json 2>&1) kube::test::if_has_string "${output_message}" '--grace-period must have --force specified' ## check replace --timeout requires --force output_message=$(! kubectl replace "${kube_flags[@]}" --timeout=1s -f /tmp/tmp-valid-pod.json 2>&1) kube::test::if_has_string "${output_message}" '--timeout must have --force specified' </ins> #cleaning rm /tmp/tmp-valid-pod.json


"github.com/spf13/cobra" "github.com/golang/glog" <ins> "k8s.io/kubernetes/pkg/api/errors" </ins> "k8s.io/kubernetes/pkg/kubectl" cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" "k8s.io/kubernetes/pkg/kubectl/resource" "k8s.io/kubernetes/pkg/runtime" <ins> "k8s.io/kubernetes/pkg/util/wait" </ins> ) // ReplaceOptions is the start of the data required to perform the operation.  As new fields are added, add them here instead of


return forceReplace(f, out, cmd, args, shortOutput, options) } <ins> if cmdutil.GetFlagInt(cmd, "grace-period") >= 0 { return fmt.Errorf("--grace-period must have --force specified") } if cmdutil.GetFlagDuration(cmd, "timeout") != 0 { return fmt.Errorf("--timeout must have --force specified") } </ins> mapper, typer := f.Object(cmdutil.GetIncludeThirdPartyAPIs(cmd)) r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). Schema(schema).


} //Replace will create a resource if it doesn't exist already, so ignore not found error ignoreNotFound := true <ins> timeout := cmdutil.GetFlagDuration(cmd, "timeout") </ins> // By default use a reaper to delete all related resources. if cmdutil.GetFlagBool(cmd, "cascade") { glog.Warningf(""cascade" is set, kubectl will delete and re-create all resources managed by this resource (e.g. Pods created by a ReplicationController). Consider using "kubectl rolling-update" if you want to update a ReplicationController together with its Pods.") <del> err = ReapResult(r, f, out, cmdutil.GetFlagBool(cmd, "cascade"), ignoreNotFound, cmdutil.GetFlagDuration(cmd, "timeout"), cmdutil.GetFlagInt(cmd, "grace-period"), shortOutput, mapper, false) </del> <ins> err = ReapResult(r, f, out, cmdutil.GetFlagBool(cmd, "cascade"), ignoreNotFound, timeout, cmdutil.GetFlagInt(cmd, "grace-period"), shortOutput, mapper, false) </ins> } else { err = DeleteResult(r, out, ignoreNotFound, shortOutput, mapper) }


return err } <ins> if timeout == 0 { timeout = kubectl.Timeout } r.Visit(func(info *resource.Info, err error) error { if err != nil { return err } return wait.PollImmediate(kubectl.Interval, timeout, func() (bool, error) { if err := info.Get(); !errors.IsNotFound(err) { return false, err } return true, nil }) }) </ins> r = resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.UnstructuredClientForMapping), runtime.UnstructuredJSONScheme). Schema(schema). ContinueOnError().


f, tf, codec, _ := NewAPIFactory() ns := dynamic.ContentConfig().NegotiatedSerializer tf.Printer = &testPrinter{} <ins> deleted := false </ins> tf.Client = &fake.RESTClient{ NegotiatedSerializer: ns, Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { switch p, m := req.URL.Path, req.Method; { <del> case p == "/namespaces/test/replicationcontrollers/redis-master" && (m == http.MethodGet || m == http.MethodPut || m == http.MethodDelete): </del> <ins> case p == "/namespaces/test/replicationcontrollers/redis-master" && m == http.MethodDelete: deleted = true fallthrough case p == "/namespaces/test/replicationcontrollers/redis-master" && m == http.MethodPut: </ins> return &http.Response{StatusCode: http.StatusOK, Header: defaultHeader(), Body: objBody(codec, &rc.Items[0])}, nil <ins> case p == "/namespaces/test/replicationcontrollers/redis-master" && m == http.MethodGet: statusCode := http.StatusOK if deleted { statusCode = http.StatusNotFound } return &http.Response{StatusCode: statusCode, Header: defaultHeader(), Body: objBody(codec, &rc.Items[0])}, nil </ins> case p == "/namespaces/test/replicationcontrollers" && m == http.MethodPost: return &http.Response{StatusCode: http.StatusCreated, Header: defaultHeader(), Body: objBody(codec, &rc.Items[0])}, nil default:


f, tf, codec, _ := NewAPIFactory() ns := dynamic.ContentConfig().NegotiatedSerializer tf.Printer = &testPrinter{} <ins> redisMasterDeleted := false frontendDeleted := false </ins> tf.Client = &fake.RESTClient{ NegotiatedSerializer: ns, Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { switch p, m := req.URL.Path, req.Method; { <del> case p == "/namespaces/test/replicationcontrollers/redis-master" && (m == http.MethodGet || m == http.MethodPut || m == http.MethodDelete): </del> <ins> case p == "/namespaces/test/replicationcontrollers/redis-master" && m == http.MethodDelete: redisMasterDeleted = true fallthrough case p == "/namespaces/test/replicationcontrollers/redis-master" && m == http.MethodPut: </ins> return &http.Response{StatusCode: http.StatusOK, Header: defaultHeader(), Body: objBody(codec, &rc.Items[0])}, nil <ins> case p == "/namespaces/test/replicationcontrollers/redis-master" && m == http.MethodGet: statusCode := http.StatusOK if redisMasterDeleted { statusCode = http.StatusNotFound } return &http.Response{StatusCode: statusCode, Header: defaultHeader(), Body: objBody(codec, &rc.Items[0])}, nil </ins> case p == "/namespaces/test/replicationcontrollers" && m == http.MethodPost: return &http.Response{StatusCode: http.StatusCreated, Header: defaultHeader(), Body: objBody(codec, &rc.Items[0])}, nil <del> case p == "/namespaces/test/services/frontend" && (m == http.MethodGet || m == http.MethodPut || m == http.MethodDelete): </del> <ins> case p == "/namespaces/test/services/frontend" && m == http.MethodDelete: frontendDeleted = true fallthrough case p == "/namespaces/test/services/frontend" && m == http.MethodPut: </ins> return &http.Response{StatusCode: http.StatusOK, Header: defaultHeader(), Body: objBody(codec, &svc.Items[0])}, nil <ins> case p == "/namespaces/test/services/frontend" && m == http.MethodGet: statusCode := http.StatusOK if frontendDeleted { statusCode = http.StatusNotFound } return &http.Response{StatusCode: statusCode, Header: defaultHeader(), Body: objBody(codec, &svc.Items[0])}, nil </ins> case p == "/namespaces/test/services" && m == http.MethodPost: return &http.Response{StatusCode: http.StatusCreated, Header: defaultHeader(), Body: objBody(codec, &svc.Items[0])}, nil default:


f, tf, codec, _ := NewAPIFactory() ns := dynamic.ContentConfig().NegotiatedSerializer tf.Printer = &testPrinter{} <ins> created := map[string]bool{} </ins> tf.Client = &fake.RESTClient{ NegotiatedSerializer: ns, Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { switch p, m := req.URL.Path, req.Method; { <del> case strings.HasPrefix(p, "/namespaces/test/replicationcontrollers/") && (m == http.MethodGet || m == http.MethodPut || m == http.MethodDelete): </del> <ins> case strings.HasPrefix(p, "/namespaces/test/replicationcontrollers/") && m == http.MethodPut: created[p] = true return &http.Response{StatusCode: http.StatusOK, Header: defaultHeader(), Body: objBody(codec, &rc.Items[0])}, nil case strings.HasPrefix(p, "/namespaces/test/replicationcontrollers/") && m == http.MethodGet: statusCode := http.StatusNotFound if created[p] { statusCode = http.StatusOK } return &http.Response{StatusCode: statusCode, Header: defaultHeader(), Body: objBody(codec, &rc.Items[0])}, nil case strings.HasPrefix(p, "/namespaces/test/replicationcontrollers/") && m == http.MethodDelete: delete(created, p) </ins> return &http.Response{StatusCode: http.StatusOK, Header: defaultHeader(), Body: objBody(codec, &rc.Items[0])}, nil case strings.HasPrefix(p, "/namespaces/test/replicationcontrollers") && m == http.MethodPost: return &http.Response{StatusCode: http.StatusCreated, Header: defaultHeader(), Body: objBody(codec, &rc.Items[0])}, nil


NegotiatedSerializer: ns, Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { switch p, m := req.URL.Path, req.Method; { <del> case p == "/namespaces/test/replicationcontrollers/redis-master" && m == http.MethodDelete: </del> <ins> case p == "/namespaces/test/replicationcontrollers/redis-master" && (m == http.MethodGet || m == http.MethodDelete): </ins> return &http.Response{StatusCode: http.StatusNotFound, Header: defaultHeader(), Body: stringBody("")}, nil case p == "/namespaces/test/replicationcontrollers" && m == http.MethodPost: return &http.Response{StatusCode: http.StatusCreated, Header: defaultHeader(), Body: objBody(codec, &rc.Items[0])}, nil


$host_kubectl create secret generic ${name} --from-file="${dir}/kubeconfig" --namespace="${FEDERATION_NAMESPACE}" done <del> $template "${manifests_root}/federation-apiserver-"{deployment,secrets}".yaml" | $host_kubectl create -f - $template "${manifests_root}/federation-controller-manager-deployment.yaml" | $host_kubectl create -f - </del> <ins> for file in federation-etcd-pvc.yaml federation-apiserver-{deployment,secrets}.yaml federation-controller-manager-deployment.yaml; do $template "${manifests_root}/${file}" | $host_kubectl create -f - done </ins> # Update the users kubeconfig to include federation-apiserver credentials. CONTEXT=federation-cluster


readOnly: true - name: etcd image: quay.io/coreos/etcd:v2.3.3 <ins> command: - /etcd - --data-dir - /var/etcd/data volumeMounts: - mountPath: /var/etcd name: varetcd </ins> volumes: - name: federation-apiserver-secrets secret: secretName: federation-apiserver-secrets <ins> - name: varetcd persistentVolumeClaim: claimName: {{.FEDERATION_APISERVER_DEPLOYMENT_NAME}}-etcd-claim </ins>


<ins> apiVersion: v1 kind: PersistentVolumeClaim metadata: name: {{.FEDERATION_APISERVER_DEPLOYMENT_NAME}}-etcd-claim annotations: volume.alpha.kubernetes.io/storage-class: "yes" namespace: {{.FEDERATION_NAMESPACE}} labels: app: federated-cluster spec: accessModes: - ReadWriteOnce resources: requests: storage: 10Gi </ins>


Expect(container.Create()).To(Succeed()) defer container.Delete() <del> By("check the pod phase") Eventually(container.GetPhase, retryTimeout, pollInterval).Should(Equal(testCase.phase)) Consistently(container.GetPhase, consistentCheckTimeout, pollInterval).Should(Equal(testCase.phase)) </del> <ins> // We need to check container state first. The default pod status is pending, If we check // pod phase first, and the expected pod phase is Pending, the container status may not // even show up when we check it. </ins> By("check the container state") <del> status, err := container.GetStatus() Expect(err).NotTo(HaveOccurred()) Expect(GetContainerState(status.State)).To(Equal(testCase.state)) </del> <ins> getState := func() (ContainerState, error) { status, err := container.GetStatus() if err != nil { return ContainerStateUnknown, err } return GetContainerState(status.State), nil } Eventually(getState, retryTimeout, pollInterval).Should(Equal(testCase.state)) Consistently(getState, consistentCheckTimeout, pollInterval).Should(Equal(testCase.state)) By("check the pod phase") Expect(container.GetPhase()).To(Equal(testCase.phase)) </ins> By("it should be possible to delete") Expect(container.Delete()).To(Succeed())


kube::release::package_kube_manifests_tarball & kube::util::wait-for-jobs || { kube::log::error "previous tarball phase failed"; return 1; } <del> kube::release::package_full_tarball & # _full depends on all the previous phases </del> <ins> kube::release::package_final_tarball & # _final depends on some of the previous phases </ins> kube::release::package_test_tarball & # _test doesn't depend on anything kube::util::wait-for-jobs || { kube::log::error "previous tarball phase failed"; return 1; } }


kube::release::create_tarball "${package_name}" "${release_stage}/.." } <del> # This is all the stuff you need to run/install kubernetes.  This includes: #   - precompiled binaries for client </del> <ins> # This is all the platform-independent stuff you need to run/install kubernetes. # Arch-specific binaries will need to be downloaded separately (possibly by # using the bundled cluster/get-kube-binaries.sh script). # Included in this tarball: </ins> #   - Cluster spin up/down scripts and configs for various cloud providers <del> #   - tarballs for server binary and salt configs that are ready to be uploaded </del> <ins> #   - Tarballs for salt configs that are ready to be uploaded </ins> #     to master by whatever means appropriate. <del> function kube::release::package_full_tarball() { kube::log::status "Building tarball: full" </del> <ins> #   - Examples (which may or may not still work) #   - The remnants of the docs/ directory function kube::release::package_final_tarball() { kube::log::status "Building tarball: final" # This isn't a "full" tarball anymore, but the release lib still expects # artifacts under "full/kubernetes/" </ins> local release_stage="${RELEASE_STAGE}/full/kubernetes" rm -rf "${release_stage}" mkdir -p "${release_stage}" <del> # Copy all of the client binaries in here, but not test or server binaries. # The server binaries are included with the server binary tarball. local platform for platform in "${KUBE_CLIENT_PLATFORMS[@]}"; do local client_bins=("${KUBE_CLIENT_BINARIES[@]}") if [[ "${platform%/*}" == "windows" ]]; then client_bins=("${KUBE_CLIENT_BINARIES_WIN[@]}") fi mkdir -p "${release_stage}/platforms/${platform}" cp "${client_bins[@]/#/${LOCAL_OUTPUT_BINPATH}/${platform}/}"  "${release_stage}/platforms/${platform}" done </del> <ins> mkdir -p "${release_stage}/client" cat <<EOF > "${release_stage}/client/README" Client binaries are no longer included in the Kubernetes final tarball. Run cluster/get-kube-binaries.sh to download client and server binaries. EOF </ins> # We want everything in /cluster except saltbase.  That is only needed on the # server.


mkdir -p "${release_stage}/server" cp "${RELEASE_DIR}/kubernetes-salt.tar.gz" "${release_stage}/server/" <del> cp "${RELEASE_DIR}"/kubernetes-server-*.tar.gz "${release_stage}/server/" </del> cp "${RELEASE_DIR}/kubernetes-manifests.tar.gz" "${release_stage}/server/" <ins> cat <<EOF > "${release_stage}/server/README" Server binary tarballs are no longer included in the Kubernetes final tarball. Run cluster/get-kube-binaries.sh to download client and server binaries. EOF </ins> mkdir -p "${release_stage}/third_party" cp -R "${KUBE_ROOT}/third_party/htpasswd" "${release_stage}/third_party/htpasswd"


"os/exec" "path" "path/filepath" <del> "reflect" </del> "strconv" "strings" "syscall"


cmd.Cmd.Stdout = outfile cmd.Cmd.Stderr = outfile <del> // Killing the sudo command should kill the server as well. attrs := &syscall.SysProcAttr{} // Hack to set linux-only field without build tags. deathSigField := reflect.ValueOf(attrs).Elem().FieldByName("Pdeathsig") if deathSigField.IsValid() { deathSigField.Set(reflect.ValueOf(syscall.SIGKILL)) } else { cmdErrorChan <- fmt.Errorf("Failed to set Pdeathsig field (non-linux build)") return } cmd.Cmd.SysProcAttr = attrs </del> // Run the command err = cmd.Run() if err != nil {


const timeout = 10 * time.Second for _, signal := range []string{"-TERM", "-KILL"} { glog.V(2).Infof("Killing process %d (%s) with %s", pid, name, signal) <del> _, err := exec.Command("sudo", "kill", signal, strconv.Itoa(pid)).Output() </del> <ins> cmd := exec.Command("sudo", "kill", signal, strconv.Itoa(pid)) // Run the 'kill' command in a separate process group so sudo doesn't ignore it cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} _, err := cmd.Output() </ins> if err != nil { glog.Errorf("Error signaling process %d (%s) with %s: %v", pid, name, signal, err) continue


cmd.Cmd.Stdout = outfile cmd.Cmd.Stderr = outfile <del> // Killing the sudo command should kill the server as well. </del> <ins> // Death of this test process should kill the server as well. </ins> attrs := &syscall.SysProcAttr{} // Hack to set linux-only field without build tags. deathSigField := reflect.ValueOf(attrs).Elem().FieldByName("Pdeathsig") if deathSigField.IsValid() { <del> deathSigField.Set(reflect.ValueOf(syscall.SIGKILL)) </del> <ins> deathSigField.Set(reflect.ValueOf(syscall.SIGTERM)) </ins> } else { cmdErrorChan <- fmt.Errorf("Failed to set Pdeathsig field (non-linux build)") return


const timeout = 10 * time.Second for _, signal := range []string{"-TERM", "-KILL"} { glog.V(2).Infof("Killing process %d (%s) with %s", pid, name, signal) <del> _, err := exec.Command("sudo", "kill", signal, strconv.Itoa(pid)).Output() </del> <ins> cmd := exec.Command("sudo", "kill", signal, strconv.Itoa(pid)) // Run the 'kill' command in a separate process group so sudo doesn't ignore it attrs := &syscall.SysProcAttr{} // Hack to set unix-only field without build tags. setpgidField := reflect.ValueOf(attrs).Elem().FieldByName("Setpgid") if setpgidField.IsValid() { setpgidField.Set(reflect.ValueOf(true)) } else { return fmt.Errorf("Failed to set Setpgid field (non-unix build)") } cmd.SysProcAttr = attrs _, err := cmd.Output() </ins> if err != nil { glog.Errorf("Error signaling process %d (%s) with %s: %v", pid, name, signal, err) continue


workerControllerJson := mkpath("storm-worker-controller.json") nsFlag := fmt.Sprintf("--namespace=%v", ns) zookeeperPod := "zookeeper" <ins> nimbusPod := "nimbus" </ins> By("starting Zookeeper") framework.RunKubectlOrDie("create", "-f", zookeeperPodJson, nsFlag) framework.RunKubectlOrDie("create", "-f", zookeeperServiceJson, nsFlag) <del> err := framework.WaitForPodNameRunningInNamespace(c, zookeeperPod, ns) </del> <ins> err := f.WaitForPodRunningSlow(zookeeperPod) </ins> Expect(err).NotTo(HaveOccurred()) By("checking if zookeeper is up and running")


By("starting Nimbus") framework.RunKubectlOrDie("create", "-f", nimbusPodJson, nsFlag) framework.RunKubectlOrDie("create", "-f", nimbusServiceJson, nsFlag) <del> err = framework.WaitForPodNameRunningInNamespace(c, "nimbus", ns) </del> <ins> err = f.WaitForPodRunningSlow(nimbusPod) </ins> Expect(err).NotTo(HaveOccurred()) err = framework.WaitForEndpoint(c, ns, "nimbus")


# OS options for minions KUBE_OS_DISTRIBUTION="${KUBE_OS_DISTRIBUTION:-jessie}" <del> KUBE_MASTER_OS_DISTRIBUTION="${KUBE_OS_DISTRIBUTION}" KUBE_NODE_OS_DISTRIBUTION="${KUBE_OS_DISTRIBUTION}" </del> <ins> MASTER_OS_DISTRIBUTION="${KUBE_OS_DISTRIBUTION}" NODE_OS_DISTRIBUTION="${KUBE_OS_DISTRIBUTION}" </ins> KUBE_NODE_IMAGE="${KUBE_NODE_IMAGE:-}" COREOS_CHANNEL="${COREOS_CHANNEL:-alpha}" CONTAINER_RUNTIME="${KUBE_CONTAINER_RUNTIME:-docker}"


if err := p.SyncPVCs(pet); err != nil { return err } <del> if exists { </del> <ins> // if pet failed - we need to remove old one because of consistent naming if exists && realPet.pod.Status.Phase == api.PodFailed { glog.V(4).Infof("Delete evicted pod %v", realPet.pod.Name) if err := p.petClient.Delete(realPet); err != nil { return err } } else if exists { </ins> if !p.isHealthy(realPet.pod) { glog.Infof("PetSet %v waiting on unhealthy pet %v", pet.parent.Name, realPet.pod.Name) }


"k8s.io/kubernetes/pkg/controller/petset" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/runtime" <ins> "k8s.io/kubernetes/pkg/types" </ins> "k8s.io/kubernetes/pkg/util/sets" "k8s.io/kubernetes/pkg/util/wait" utilyaml "k8s.io/kubernetes/pkg/util/yaml" <ins> "k8s.io/kubernetes/pkg/watch" </ins> "k8s.io/kubernetes/test/e2e/framework" ) const ( petsetPoll = 10 * time.Second // Some pets install base packages via wget <del> petsetTimeout           = 10 * time.Minute </del> <ins> petsetTimeout = 10 * time.Minute // Timeout for pet pods to change state petPodTimeout           = 5 * time.Minute </ins> zookeeperManifestPath   = "test/e2e/testing-manifests/petset/zookeeper" mysqlGaleraManifestPath = "test/e2e/testing-manifests/petset/mysql-galera" redisManifestPath       = "test/e2e/testing-manifests/petset/redis"


}) }) <ins> var _ = framework.KubeDescribe("Pet set recreate [Slow] [Feature:PetSet]", func() { f := framework.NewDefaultFramework("pet-set-recreate") var c *client.Client var ns string labels := map[string]string{ "foo": "bar", "baz": "blah", } headlessSvcName := "test" podName := "test-pod" petSetName := "web" petPodName := "web-0" BeforeEach(func() { framework.SkipUnlessProviderIs("gce", "vagrant") By("creating service " + headlessSvcName + " in namespace " + f.Namespace.Name) headlessService := createServiceSpec(headlessSvcName, "", true, labels) _, err := f.Client.Services(f.Namespace.Name).Create(headlessService) framework.ExpectNoError(err) c = f.Client ns = f.Namespace.Name }) AfterEach(func() { if CurrentGinkgoTestDescription().Failed { dumpDebugInfo(c, ns) } By("Deleting all petset in ns " + ns) deleteAllPetSets(c, ns) }) It("should recreate evicted petset", func() { By("looking for a node to schedule pet set and pod") nodes := framework.GetReadySchedulableNodesOrDie(f.Client) node := nodes.Items[0] By("creating pod with conflicting port in namespace " + f.Namespace.Name) conflictingPort := api.ContainerPort{HostPort: 21017, ContainerPort: 21017, Name: "conflict"} pod := &api.Pod{ ObjectMeta: api.ObjectMeta{ Name: podName, }, Spec: api.PodSpec{ Containers: []api.Container{ { Name:  "nginx", Image: "gcr.io/google_containers/nginx-slim:0.7", Ports: []api.ContainerPort{conflictingPort}, }, }, NodeName: node.Name, }, } pod, err := f.Client.Pods(f.Namespace.Name).Create(pod) framework.ExpectNoError(err) By("creating petset with conflicting port in namespace " + f.Namespace.Name) ps := newPetSet(petSetName, f.Namespace.Name, headlessSvcName, 1, nil, nil, labels) petContainer := &ps.Spec.Template.Spec.Containers[0] petContainer.Ports = append(petContainer.Ports, conflictingPort) ps.Spec.Template.Spec.NodeName = node.Name _, err = f.Client.Apps().PetSets(f.Namespace.Name).Create(ps) framework.ExpectNoError(err) By("waiting until pod " + podName + " will start running in namespace " + f.Namespace.Name) if err := f.WaitForPodRunning(podName); err != nil { framework.Failf("Pod %v did not start running: %v", podName, err) } var initialPetPodUID types.UID By("waiting until pet pod " + petPodName + " will be recreated and deleted at least once in namespace " + f.Namespace.Name) w, err := f.Client.Pods(f.Namespace.Name).Watch(api.SingleObject(api.ObjectMeta{Name: petPodName})) framework.ExpectNoError(err) // we need to get UID from pod in any state and wait until pet set controller will remove pod atleast once _, err = watch.Until(petPodTimeout, w, func(event watch.Event) (bool, error) { pod := event.Object.(*api.Pod) switch event.Type { case watch.Deleted: framework.Logf("Observed delete event for pet pod %v in namespace %v", pod.Name, pod.Namespace) if initialPetPodUID == "" { return false, nil } return true, nil } framework.Logf("Observed pet pod in namespace: %v, name: %v, uid: %v, status phase: %v. Waiting for petset controller to delete.", pod.Namespace, pod.Name, pod.UID, pod.Status.Phase) initialPetPodUID = pod.UID return false, nil }) if err != nil { framework.Failf("Pod %v expected to be re-created atleast once", petPodName) } By("removing pod with conflicting port in namespace " + f.Namespace.Name) err = f.Client.Pods(f.Namespace.Name).Delete(pod.Name, api.NewDeleteOptions(0)) framework.ExpectNoError(err) By("waiting when pet pod " + petPodName + " will be recreated in namespace " + f.Namespace.Name + " and will be in running state") // we may catch delete event, thats why we are waiting for running phase like this, and not with watch.Until Eventually(func() error { petPod, err := f.Client.Pods(f.Namespace.Name).Get(petPodName) if err != nil { return err } if petPod.Status.Phase != api.PodRunning { return fmt.Errorf("Pod %v is not in running phase: %v", petPod.Name, petPod.Status.Phase) } else if petPod.UID == initialPetPodUID { return fmt.Errorf("Pod %v wasn't recreated: %v == %v", petPod.Name, petPod.UID, initialPetPodUID) } return nil }, petPodTimeout, 2*time.Second).Should(BeNil()) }) }) </ins> func dumpDebugInfo(c *client.Client, ns string) { pl, _ := c.Pods(ns).List(api.ListOptions{LabelSelector: labels.Everything()}) for _, p := range pl.Items {


return err } if waitForReplicas != nil { <del> watchOptions := api.ListOptions{FieldSelector: fields.OneTermEqualSelector("metadata.name", name), ResourceVersion: updatedResourceVersion} watcher, err := scaler.c.ReplicationControllers(namespace).Watch(watchOptions) </del> <ins> checkRC := func(rc *api.ReplicationController) bool { if uint(rc.Spec.Replicas) != newSize { // the size is changed by other party. Don't need to wait for the new change to complete. return true } return rc.Status.ObservedGeneration >= rc.Generation && rc.Status.Replicas == rc.Spec.Replicas } // If number of replicas doesn't change, then the update may not event // be sent to underlying databse (we don't send no-op changes). // In such case, <updatedResourceVersion> will have value of the most // recent update (which may be far in the past) so we may get "too old // RV" error from watch or potentially no ReplicationController events // will be deliver, since it may already be in the expected state. // To protect from these two, we first issue Get() to ensure that we // are not already in the expected state. currentRC, err := scaler.c.ReplicationControllers(namespace).Get(name) </ins> if err != nil { return err } <del> _, err = watch.Until(waitForReplicas.Timeout, watcher, func(event watch.Event) (bool, error) { if event.Type != watch.Added && event.Type != watch.Modified { return false, nil </del> <ins> if !checkRC(currentRC) { watchOptions := api.ListOptions{ FieldSelector:   fields.OneTermEqualSelector("metadata.name", name), ResourceVersion: updatedResourceVersion, </ins> } <del> rc := event.Object.(*api.ReplicationController) if uint(rc.Spec.Replicas) != newSize { // the size is changed by other party. Don't need to wait for the new change to complete. return true, nil </del> <ins> watcher, err := scaler.c.ReplicationControllers(namespace).Watch(watchOptions) if err != nil { return err </ins> } <del> return rc.Status.ObservedGeneration >= rc.Generation && rc.Status.Replicas == rc.Spec.Replicas, nil }) if err == wait.ErrWaitTimeout { return fmt.Errorf("timed out waiting for %q to be synced", name) </del> <ins> _, err = watch.Until(waitForReplicas.Timeout, watcher, func(event watch.Event) (bool, error) { if event.Type != watch.Added && event.Type != watch.Modified { return false, nil } return checkRC(event.Object.(*api.ReplicationController)), nil }) if err == wait.ErrWaitTimeout { return fmt.Errorf("timed out waiting for %q to be synced", name) } return err </ins> } <del> return err </del> } return nil }


}, }, StopError:       nil, <del> ExpectedActions: []string{"get", "list", "get", "update", "watch", "delete"}, </del> <ins> ExpectedActions: []string{"get", "list", "get", "update", "get", "delete"}, </ins> }, { Name: "NoOverlapping",


}, }, StopError:       nil, <del> ExpectedActions: []string{"get", "list", "get", "update", "watch", "delete"}, </del> <ins> ExpectedActions: []string{"get", "list", "get", "update", "get", "delete"}, </ins> }, { Name: "OverlappingError",


healthchecker.mutationRequestChannel <- req } <del> func updateServiceListener(serviceName types.NamespacedName, listenPort int, addOrDelete bool) bool { </del> <ins> func updateServiceListener(serviceName types.NamespacedName, listenPort int, add bool) bool { </ins> responseChannel := make(chan bool) req := &proxyListenerRequest{ serviceName:     serviceName, listenPort:      uint16(listenPort), <del> add:             addOrDelete, </del> <ins> add:             add, </ins> responseChannel: responseChannel, } healthchecker.listenerRequestChannel <- req


return updateServiceListener(serviceName, listenPort, true) } <del> // DeleteServiceListener Request addition of a listener for a service's health check </del> <ins> // DeleteServiceListener Request deletion of a listener for a service's health check </ins> func DeleteServiceListener(serviceName types.NamespacedName, listenPort int) bool { return updateServiceListener(serviceName, listenPort, false) }


s, ok := h.serviceEndpointsMap.Get(serviceName) if !ok { glog.V(4).Infof("Service %s not found or has no local endpoints", serviceName) <del> sendHealthCheckResponse(rw, http.StatusServiceUnavailable, "No Service Endpoints Not Found") </del> <ins> sendHealthCheckResponse(rw, http.StatusServiceUnavailable, "No Service Endpoints Found") </ins> return } numEndpoints := len(*s.(*serviceEndpointsList).endpoints)


func run(s *options.KubeletServer, kubeDeps *kubelet.KubeletDeps) (err error) { // TODO: this should be replaced by a --standalone flag <del> standaloneMode := (len(s.APIServerList) == 0) </del> <ins> standaloneMode := (len(s.APIServerList) == 0 && !s.RequireKubeConfig) </ins> if s.ExitOnLockContention && s.LockFilePath == "" { return errors.New("cannot exit on lock file contention: no lock file specified")


go nc.podController.Run(wait.NeverStop) go nc.daemonSetController.Run(wait.NeverStop) if nc.internalPodInformer != nil { <del> nc.internalPodInformer.Run(wait.NeverStop) </del> <ins> go nc.internalPodInformer.Run(wait.NeverStop) </ins> } // Incorporate the results of node status pushed from kubelet to master.


Items []Foo `json:"items"` } <del> var _ = Describe("ThirdParty resources", func() { </del> <ins> // This test is marked flaky pending namespace controller observing dynamic creation of new third party types. var _ = Describe("ThirdParty resources [Flaky] [Disruptive]", func() { </ins> f := framework.NewDefaultFramework("thirdparty")


return result, len(result) > 0 } <ins> // TODO: Most probably splitting this method to a separate thread will visibily // improve throughput of our watch machinery. So what we should do is to: // - OnEvent handler simply put an element to channel // - processEvent be another goroutine processing events from that channel // Additionally, if we make this channel buffered, cacher will be more resistant // to single watchers being slow - see cacheWatcher::add method. </ins> func (c *Cacher) processEvent(event watchCacheEvent) { triggerValues, supported := c.triggerValues(&event)


// OK, block sending, but only for up to 5 seconds. // cacheWatcher.add is called very often, so arrange // to reuse timers instead of constantly allocating. <ins> startTime := time.Now() </ins> const timeout = 5 * time.Second t, ok := timerPool.Get().(*time.Timer) if ok {


c.forget(false) c.stop() } <ins> glog.V(2).Infof("cacheWatcher add function blocked processing for %v", time.Since(startTime)) </ins> } func (c *cacheWatcher) sendWatchCacheEvent(event watchCacheEvent) {


import ( "fmt" "net/http" <ins> "reflect" </ins> "sync" "sync/atomic" "time"


// Injectable for testing. Send the event down the outgoing channel. emit func(watch.Event) <ins> // HighWaterMarks for performance debugging. incomingHWM HighWaterMark outgoingHWM HighWaterMark </ins> cache etcdCache }


cancel:   nil, } w.emit = func(e watch.Event) { <ins> if curLen := int64(len(w.outgoing)); w.outgoingHWM.Update(curLen) { // Monitor if this gets backed up, and how much. glog.V(1).Infof("watch (%v): %v objects queued in outgoing channel.", reflect.TypeOf(e.Object).String(), curLen) } </ins> // Give up on user stop, without this we leak a lot of goroutines in tests. select { case w.outgoing <- e:


incoming <- &copied } <del> var ( watchChannelHWM HighWaterMark ) </del> // translate pulls stuff from etcd, converts, and pushes out the outgoing channel. Meant to be // called as a goroutine. func (w *etcdWatcher) translate() {


return case res, ok := <-w.etcdIncoming: if ok { <del> if curLen := int64(len(w.etcdIncoming)); watchChannelHWM.Update(curLen) { </del> <ins> if curLen := int64(len(w.etcdIncoming)); w.incomingHWM.Update(curLen) { </ins> // Monitor if this gets backed up, and how much. <del> glog.V(2).Infof("watch: %v objects queued in channel.", curLen) </del> <ins> glog.V(1).Infof("watch: %v objects queued in incoming channel.", curLen) </ins> } w.sendResult(res) }


if res == nil { continue } <ins> if len(wc.resultChan) == outgoingBufSize { glog.Warningf("Fast watcher, slow processing. Number of buffered events: %d."+ "Probably caused by slow dispatching events to watchers", outgoingBufSize) } </ins> // If user couldn't receive results fast enough, we also block incoming events from watcher. // Because storing events in local will cause more memory usage. // The worst case would be closing the fast watcher.


func (wc *watchChan) sendEvent(e *event) { if len(wc.incomingEventChan) == incomingBufSize { <del> glog.V(2).Infof("Fast watcher, slow processing. Number of buffered events: %d."+ </del> <ins> glog.Warningf("Fast watcher, slow processing. Number of buffered events: %d."+ </ins> "Probably caused by slow decoding, user not receiving fast, or other processing logic", incomingBufSize) }


} framework.ExpectNoError(framework.RunRC(controllerRcConfig)) <del> // Make sure endpoints are propagated. // TODO(piosz): replace sleep with endpoints watch. time.Sleep(10 * time.Second) </del> <ins> // Wait for endpoints to propagate for the controller service. framework.ExpectNoError(framework.WaitForServiceEndpointsNum( c, ns, controllerName, 1, startServiceInterval, startServiceTimeout)) </ins> }


} // errorBadPodsStates create error message of basic info of bad pods for debugging. <del> func errorBadPodsStates(badPods []api.Pod, desiredPods int, ns string, timeout time.Duration) string { errStr := fmt.Sprintf("%d / %d pods in namespace %q are NOT in the desired state in %vn", len(badPods), desiredPods, ns, timeout) </del> <ins> func errorBadPodsStates(badPods []api.Pod, desiredPods int, ns, desiredState string, timeout time.Duration) string { errStr := fmt.Sprintf("%d / %d pods in namespace %q are NOT in %s state in %vn", len(badPods), desiredPods, ns, desiredState, timeout) </ins> // Pirnt bad pods info only if there are fewer than 10 bad pods if len(badPods) > 10 { return errStr + "There are too many bad pods. Please check log for details."


// pods have been created. func WaitForPodsSuccess(c *client.Client, ns string, successPodLabels map[string]string, timeout time.Duration) error { successPodSelector := labels.SelectorFromSet(successPodLabels) <del> start, badPods := time.Now(), []api.Pod{} </del> <ins> start, badPods, desiredPods := time.Now(), []api.Pod{}, 0 </ins> if wait.PollImmediate(30*time.Second, timeout, func() (bool, error) { podList, err := c.Pods(ns).List(api.ListOptions{LabelSelector: successPodSelector})


return true, nil } badPods = []api.Pod{} <ins> desiredPods = len(podList.Items) </ins> for _, pod := range podList.Items { if pod.Status.Phase != api.PodSucceeded { badPods = append(badPods, pod)


}) != nil { logPodStates(badPods) LogPodsWithLabels(c, ns, successPodLabels) <del> return fmt.Errorf("Not all pods in namespace %q are successful within %v", ns, timeout) </del> <ins> return errors.New(errorBadPodsStates(badPods, desiredPods, ns, "SUCCESS", timeout)) </ins> } return nil }


logPodStates(badPods) return false, nil }) != nil { <del> return errors.New(errorBadPodsStates(badPods, desiredPods, ns, timeout)) </del> <ins> return errors.New(errorBadPodsStates(badPods, desiredPods, ns, "RUNNING and READY", timeout)) </ins> } wg.Wait() if waitForSuccessError != nil {


} // Create the container. <del> fClock.SetTime(time.Now()) </del> <ins> fClock.SetTime(time.Now().Add(-1 * time.Hour)) </ins> *expected.CreatedAt = fClock.Now().Unix() id, err := ds.CreateContainer("sandboxid", config, sConfig) // Set the id manually since we don't know the id until it's created.


assert.Equal(t, expected, status) // Advance the clock and stop the container. <del> fClock.SetTime(time.Now()) </del> <ins> fClock.SetTime(time.Now().Add(1 * time.Hour)) </ins> *expected.FinishedAt = fClock.Now().Unix() *expected.State = runtimeApi.ContainerState_EXITED *expected.Reason = "Completed"


) func newTestDockerSevice() (*dockerService, *dockertools.FakeDockerClient, *clock.FakeClock) { <del> c := dockertools.NewFakeDockerClient() </del> fakeClock := clock.NewFakeClock(time.Time{}) <ins> c := dockertools.NewFakeDockerClientWithClock(fakeClock) </ins> return &dockerService{client: c}, c, fakeClock }


// `HostIP: s.API.AdvertiseAddrs[0]`, if there is only one address` {Name: "http", ContainerPort: 9898, HostPort: 9898}, }, <ins> SecurityContext: &api.SecurityContext{ SELinuxOptions: &api.SELinuxOptions{ // TODO: This implies our discovery container is not being restricted by // SELinux. This is not optimal and would be nice to adjust in future // so it can read /tmp/secret, but for now this avoids recommending // setenforce 0 system-wide. Type: "unconfined_t", }, }, </ins> }}, Volumes: []api.Volume{{ Name: kubeDiscoverySecretName,


} const yamlSeparator = "n---" <del> const separator = "---n" </del> <ins> const separator = "---" </ins> // splitYAMLDocument is a bufio.SplitFunc for splitting YAML streams into individual documents. func splitYAMLDocument(data []byte, atEOF bool) (advance int, token []byte, err error) {


return nil, err } <del> if string(line) == separator || err == io.EOF { </del> <ins> sep := len([]byte(separator)) if i := bytes.Index(line, []byte(separator)); i == 0 { // We have a potential document terminator i += sep after := line[i:] if len(strings.TrimRightFunc(string(after), unicode.IsSpace)) == 0 { if buffer.Len() != 0 { return buffer.Bytes(), nil } if err == io.EOF { return nil, err } } } if err == io.EOF { </ins> if buffer.Len() != 0 { <ins> // If we're at EOF, we have a final, non-terminated line. Return it. </ins> return buffer.Bytes(), nil } <del> if err == io.EOF { return nil, err } } else { buffer.Write(line) </del> <ins> return nil, err </ins> } <ins> buffer.Write(line) </ins> } }


s := NewYAMLToJSONDecoder(bytes.NewReader([]byte(`--- stuff: 1 <del> --- </del> <ins> --- </ins> `))) obj := generic{} if err := s.Decode(&obj); err != nil {


obj := generic{} err := s.Decode(&obj) if err == nil { <del> t.Fatal("expected error with yaml: prefix, got no error") </del> <ins> t.Fatal("expected error with yaml: violate, got no error") </ins> } fmt.Printf("err: %sn", err.Error()) <del> if !strings.HasPrefix(err.Error(), "yaml: line 1:") { t.Fatalf("expected %q to have 'yaml: line 1:' prefix", err.Error()) </del> <ins> if !strings.HasPrefix(err.Error(), "yaml: line 2:") { t.Fatalf("expected %q to have 'yaml: line 2:' found a tab character", err.Error()) </ins> } }


docker build -t $(PREFIX)/logs-generator:$(TAG) . push: <del> gcloud docker push $(PREFIX)/logs-generator:$(TAG) </del> <ins> gcloud docker -- push $(PREFIX)/logs-generator:$(TAG) </ins> clean: rm -f logs-generator  No newline at end of file


RUN mkdir -p ${K8S_PATCHED_GOROOT}  && curl -sSL https://github.com/golang/go/archive/go${K8S_PATCHED_GOLANG_VERSION}.tar.gz | tar -xz -C ${K8S_PATCHED_GOROOT} --strip-components=1 <ins> # We need a patched go1.7.1 for linux/arm (https://github.com/kubernetes/kubernetes/issues/29904) # We need go1.7.1 for all darwin builds (https://github.com/kubernetes/kubernetes/issues/32999) </ins> COPY golang-patches/CL28857-go1.7.1-luxas.patch ${K8S_PATCHED_GOROOT}/ RUN cd ${K8S_PATCHED_GOROOT}  && patch -p1 < CL28857-go1.7.1-luxas.patch  && cd src  && GOROOT_FINAL=${K8S_PATCHED_GOROOT} GOROOT_BOOTSTRAP=/usr/local/go ./make.bash  <del> && for platform in linux/arm; do GOOS=${platform%/*} GOARCH=${platform##*/} GOROOT=${K8S_PATCHED_GOROOT} go install std; done </del> <ins> && for platform in linux/arm darwin/386 darwin/amd64; do GOOS=${platform%/*} GOARCH=${platform##*/} GOROOT=${K8S_PATCHED_GOROOT} go install std; done </ins>


<del> v1.6.3-7 </del> <ins> v1.6.3-8 </ins>


if [[ ${platform} == "linux/arm" ]]; then export CGO_ENABLED=1 export CC=arm-linux-gnueabi-gcc <ins> # See https://github.com/kubernetes/kubernetes/issues/29904 </ins> export GOROOT=${K8S_PATCHED_GOROOT} elif [[ ${platform} == "linux/arm64" ]]; then export CGO_ENABLED=1


elif [[ ${platform} == "linux/ppc64le" ]]; then export CGO_ENABLED=1 export CC=powerpc64le-linux-gnu-gcc <ins> elif [[ ${platform} == "darwin/"* ]]; then # See https://github.com/kubernetes/kubernetes/issues/32999 export GOROOT=${K8S_PATCHED_GOROOT} </ins> fi fi }


r.setLastSyncResourceVersion(resourceVersion) resyncerrc := make(chan error, 1) <ins> cancelCh := make(chan struct{}) defer close(cancelCh) </ins> go func() { for { select { case <-resyncCh: case <-stopCh: return <ins> case <-cancelCh: return </ins> } glog.V(4).Infof("%s: forcing resync", r.name) if err := r.store.Resync(); err != nil {


if lbaas.opts.ManageSecurityGroups { err := lbaas.ensureSecurityGroup(clusterName, apiService, nodes, loadbalancer) if err != nil { <del> // cleanup what was created so far _ = lbaas.EnsureLoadBalancerDeleted(ctx, clusterName, apiService) return status, err </del> <ins> return status, fmt.Errorf("Error reconciling security groups for LB service %v/%v: %v", apiService.Namespace, apiService.Name, err) </ins> } }


// It doesn't update, probe or get the pod. type defaultPetHealthChecker struct{} <del> // isHealthy returns true if the pod is running and has the // "pod.alpha.kubernetes.io/initialized" set to "true". </del> <ins> // isHealthy returns true if the pod is ready & running. If the pod has the // "pod.alpha.kubernetes.io/initialized" annotation set to "false", pod state is ignored. </ins> func (d *defaultPetHealthChecker) isHealthy(pod *api.Pod) bool { if pod == nil || pod.Status.Phase != api.PodRunning { return false } <ins> podReady := api.IsPodReady(pod) // User may have specified a pod readiness override through a debug annotation. </ins> initialized, ok := pod.Annotations[StatefulSetInitAnnotation] <del> if !ok { glog.Infof("StatefulSet pod %v in %v, waiting on annotation %v", api.PodRunning, pod.Name, StatefulSetInitAnnotation) return false } b, err := strconv.ParseBool(initialized) if err != nil { return false </del> <ins> if ok { if initAnnotation, err := strconv.ParseBool(initialized); err != nil { glog.Infof("Failed to parse %v annotation on pod %v: %v", StatefulSetInitAnnotation, pod.Name, err) } else if !initAnnotation { glog.Infof("StatefulSet pod %v waiting on annotation %v", pod.Name, StatefulSetInitAnnotation) podReady = initAnnotation } </ins> } <del> return b && api.IsPodReady(pod) </del> <ins> return podReady </ins> } // isDying returns true if the pod has a non-nil deletion timestamp. Since the


ObjectMeta: api.ObjectMeta{ Name:      name, Namespace: ns, <ins> Annotations: map[string]string{ "pod.alpha.kubernetes.io/initialized": "false", }, </ins> }, Spec: apps.StatefulSetSpec{ Selector: &unversioned.LabelSelector{


create-static-ip "${MASTER_NAME}-ip" "${REGION}" MASTER_RESERVED_IP=$(gcloud compute addresses describe "${MASTER_NAME}-ip"  --project "${PROJECT}" --region "${REGION}" -q --format='value(address)') <del> KUBELET_APISERVER="${MASTER_RESERVED_IP}" </del> <ins> if [[ "${REGISTER_MASTER_KUBELET:-}" == "true" ]]; then KUBELET_APISERVER="${MASTER_RESERVED_IP}" fi </ins> KUBERNETES_MASTER_NAME="${MASTER_RESERVED_IP}" create-certs "${MASTER_RESERVED_IP}"


} // TODO(freehan): allow user to update loadbalancerSourceRanges <del> allErrs = append(allErrs, ValidateImmutableField(service.Spec.LoadBalancerSourceRanges, oldService.Spec.LoadBalancerSourceRanges, field.NewPath("spec", "loadBalancerSourceRanges"))...) </del> <ins> // Only allow removing LoadBalancerSourceRanges when change service type from LoadBalancer // to non-LoadBalancer or adding LoadBalancerSourceRanges when change service type from // non-LoadBalancer to LoadBalancer. if service.Spec.Type != api.ServiceTypeLoadBalancer && oldService.Spec.Type != api.ServiceTypeLoadBalancer || service.Spec.Type == api.ServiceTypeLoadBalancer && oldService.Spec.Type == api.ServiceTypeLoadBalancer { allErrs = append(allErrs, ValidateImmutableField(service.Spec.LoadBalancerSourceRanges, oldService.Spec.LoadBalancerSourceRanges, field.NewPath("spec", "loadBalancerSourceRanges"))...) } </ins> allErrs = append(allErrs, validateServiceFields(service)...) allErrs = append(allErrs, validateServiceAnnotations(service, oldService)...)


return errStr + buf.String() } <del> // check if a Pod is controlled by a Replication Controller in the List func hasReplicationControllersForPod(rcs *api.ReplicationControllerList, pod api.Pod) bool { for _, rc := range rcs.Items { selector := labels.SelectorFromSet(rc.Spec.Selector) if selector.Matches(labels.Set(pod.ObjectMeta.Labels)) { return true } } return false } </del> // WaitForPodsSuccess waits till all labels matching the given selector enter // the Success state. The caller is expected to only invoke this method once the // pods have been created.


// WaitForPodsRunningReady waits up to timeout to ensure that all pods in // namespace ns are either running and ready, or failed but controlled by a <del> // replication controller. Also, it ensures that at least minPods are running // and ready. It has separate behavior from other 'wait for' pods functions in // that it requires the list of pods on every iteration. This is useful, for </del> <ins> // controller. Also, it ensures that at least minPods are running and // ready. It has separate behavior from other 'wait for' pods functions in // that it requests the list of pods on every iteration. This is useful, for </ins> // example, in cluster startup, because the number of pods increases while // waiting. // If ignoreLabels is not empty, pods matching this selector are ignored and


}() if wait.PollImmediate(Poll, timeout, func() (bool, error) { <del> // We get the new list of pods and replication controllers in every // iteration because more pods come online during startup and we want to // ensure they are also checked. </del> <ins> // We get the new list of pods, replication controllers, and // replica sets in every iteration because more pods come // online during startup and we want to ensure they are also // checked. replicas, replicaOk := int32(0), int32(0) </ins> rcList, err := c.Core().ReplicationControllers(ns).List(api.ListOptions{}) if err != nil { Logf("Error getting replication controllers in namespace '%s': %v", ns, err) return false, nil } <del> replicas := int32(0) </del> for _, rc := range rcList.Items { replicas += rc.Spec.Replicas <ins> replicaOk += rc.Status.ReadyReplicas } rsList, err := c.Extensions().ReplicaSets(ns).List(api.ListOptions{}) if err != nil { Logf("Error getting replication sets in namespace %q: %v", ns, err) return false, nil } for _, rs := range rsList.Items { replicas += rs.Spec.Replicas replicaOk += rs.Status.ReadyReplicas </ins> } podList, err := c.Core().Pods(ns).List(api.ListOptions{})


Logf("Error getting pods in namespace '%s': %v", ns, err) return false, nil } <del> nOk, replicaOk := int32(0), int32(0) </del> <ins> nOk := int32(0) </ins> badPods = []api.Pod{} desiredPods = len(podList.Items) for _, pod := range podList.Items {


} if res, err := testutils.PodRunningReady(&pod); res && err == nil { nOk++ <del> if hasReplicationControllersForPod(rcList, pod) { replicaOk++ } </del> } else { if pod.Status.Phase != api.PodFailed { Logf("The status of Pod %s is %s (Ready = false), waiting for it to be either Running (with Ready = true) or Failed", pod.ObjectMeta.Name, pod.Status.Phase) badPods = append(badPods, pod) <del> } else if !hasReplicationControllersForPod(rcList, pod) { Logf("Pod %s is Failed, but it's not controlled by a ReplicationController", pod.ObjectMeta.Name) </del> <ins> } else if _, ok := pod.Annotations[api.CreatedByAnnotation]; !ok { Logf("Pod %s is Failed, but it's not controlled by a controller", pod.ObjectMeta.Name) </ins> badPods = append(badPods, pod) } <del> //ignore failed pods that are controlled by a replication controller </del> <ins> //ignore failed pods that are controlled by some controller </ins> } }


--env "KUBE_FASTBUILD=${KUBE_FASTBUILD:-false}" --env "KUBE_BUILDER_OS=${OSTYPE:-notdetected}" --env "KUBE_BUILD_PPC64LE=${KUBE_BUILD_PPC64LE}"  # TODO(IBM): remove <ins> --env "KUBE_VERBOSE=${KUBE_VERBOSE}" </ins> ) # If we have stdin we can run interactive.  This allows things like 'shell.sh'


[[ -n ${1-} ]] || { kube::log::error_exit "!!! Internal error. No platform set in kube::golang::set_platform_envs" } <ins> # make sure we have a clean slate first kube::golang::unset_platform_envs </ins> export GOOS=${platform%/*} export GOARCH=${platform##*/}


local -a nonstatics=() local -a tests=() <ins> V=2 kube::log::info "Env for ${platform}: GOOS=${GOOS-} GOARCH=${GOARCH-} GOROOT=${GOROOT-} CGO_ENABLED=${CGO_ENABLED-} CC=${CC-}" </ins> for binary in "${binaries[@]}"; do if [[ "${binary}" =~ ".test"$ ]]; then


else for platform in "${platforms[@]}"; do kube::log::status "Building go targets for ${platform}:" "${targets[@]}" <del> kube::golang::set_platform_envs "${platform}" kube::golang::build_binaries_for_platform ${platform} ${use_go_build:-} </del> <ins> ( kube::golang::set_platform_envs "${platform}" kube::golang::build_binaries_for_platform ${platform} ${use_go_build:-} ) </ins> done fi )


[[ -n ${1-} ]] || { kube::log::error_exit "!!! Internal error. No platform set in kube::golang::set_platform_envs" } <del> # make sure we have a clean slate first kube::golang::unset_platform_envs </del> export GOOS=${platform%/*} export GOARCH=${platform##*/}


for _, mountPoint := range mountPoints { const sysfsDevice = "sysfs" <del> if mountPoint.Device != sysfsDevice { </del> <ins> if mountPoint.Type != sysfsDevice { </ins> continue } // Check whether sysfs is 'rw'


"//vendor:k8s.io/apimachinery/pkg/runtime/schema", "//vendor:k8s.io/apimachinery/pkg/types", "//vendor:k8s.io/apimachinery/pkg/util/intstr", <ins> "//vendor:k8s.io/apimachinery/pkg/util/sets", </ins> "//vendor:k8s.io/apimachinery/pkg/util/uuid", "//vendor:k8s.io/apimachinery/pkg/watch", "//vendor:k8s.io/client-go/pkg/api",


"k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" <ins> "k8s.io/apimachinery/pkg/util/sets" </ins> "k8s.io/apimachinery/pkg/util/uuid" "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/test/e2e/framework"


}) Context("", func() { It("pod infra containers oom-score-adj should be -998 and best effort container's should be 1000", func() { <del> var err error </del> <ins> // Take a snapshot of existing pause processes. These were // created before this test, and may not be infra // containers. They should be excluded from the test. existingPausePIDs, err := getPidsForProcess("pause", "") Expect(err).To(BeNil(), "failed to list all pause processes on the node") existingPausePIDSet := sets.NewInt(existingPausePIDs...) </ins> podClient := f.PodClient() podName := "besteffort" + string(uuid.NewUUID()) podClient.Create(&v1.Pod{


return fmt.Errorf("failed to get list of pause pids: %v", err) } for _, pid := range pausePids { <ins> if existingPausePIDSet.Has(pid) { // Not created by this test. Ignore it. continue } </ins> if err := validateOOMScoreAdjSetting(pid, -998); err != nil { return err }


"fmt" "os" "path" <ins> "strings" </ins> "github.com/golang/glog" "k8s.io/kubernetes/pkg/api/resource"


if err != nil { return nil, err } <ins> volumePath = strings.Replace(volumePath, "040", " ", -1) </ins> glog.V(5).Infof("vSphere volume path is %q", volumePath) vsphereVolume := &v1.Volume{ Name: volumeName,


"//pkg/registry/rbac/rolebinding/etcd:go_default_library", "//pkg/registry/rbac/rolebinding/policybased:go_default_library", "//pkg/util/runtime:go_default_library", <ins> "//pkg/util/wait:go_default_library", </ins> "//plugin/pkg/auth/authorizer/rbac/bootstrappolicy:go_default_library", "//vendor:github.com/golang/glog", ],


import ( "fmt" "sync" <ins> "time" </ins> "github.com/golang/glog"


rolebindingetcd "k8s.io/kubernetes/pkg/registry/rbac/rolebinding/etcd" rolebindingpolicybased "k8s.io/kubernetes/pkg/registry/rbac/rolebinding/policybased" utilruntime "k8s.io/kubernetes/pkg/util/runtime" <ins> "k8s.io/kubernetes/pkg/util/wait" </ins> "k8s.io/kubernetes/plugin/pkg/auth/authorizer/rbac/bootstrappolicy" )


} func PostStartHook(hookContext genericapiserver.PostStartHookContext) error { <del> clientset, err := rbacclient.NewForConfig(hookContext.LoopbackClientConfig) if err != nil { utilruntime.HandleError(fmt.Errorf("unable to initialize clusterroles: %v", err)) return nil } existingClusterRoles, err := clientset.ClusterRoles().List(api.ListOptions{}) if err != nil { utilruntime.HandleError(fmt.Errorf("unable to initialize clusterroles: %v", err)) return nil } // if clusterroles already exist, then assume we don't have work to do because we've already // initialized or another API server has started this task if len(existingClusterRoles.Items) > 0 { return nil } for _, clusterRole := range append(bootstrappolicy.ClusterRoles(), bootstrappolicy.ControllerRoles()...) { if _, err := clientset.ClusterRoles().Create(&clusterRole); err != nil { // don't fail on failures, try to create as many as you can </del> <ins> // intializing roles is really important.  On some e2e runs, we've seen cases where etcd is down when the server // starts, the roles don't initialize, and nothing works. err := wait.Poll(1*time.Second, 30*time.Second, func() (done bool, err error) { clientset, err := rbacclient.NewForConfig(hookContext.LoopbackClientConfig) if err != nil { </ins> utilruntime.HandleError(fmt.Errorf("unable to initialize clusterroles: %v", err)) <del> continue </del> <ins> return false, nil </ins> } <del> glog.Infof("Created clusterrole.%s/%s", rbac.GroupName, clusterRole.Name) } existingClusterRoleBindings, err := clientset.ClusterRoleBindings().List(api.ListOptions{}) if err != nil { utilruntime.HandleError(fmt.Errorf("unable to initialize clusterrolebindings: %v", err)) return nil } // if clusterrolebindings already exist, then assume we don't have work to do because we've already // initialized or another API server has started this task if len(existingClusterRoleBindings.Items) > 0 { return nil } </del> <ins> existingClusterRoles, err := clientset.ClusterRoles().List(api.ListOptions{}) if err != nil { utilruntime.HandleError(fmt.Errorf("unable to initialize clusterroles: %v", err)) return false, nil } // only initialized on empty etcd if len(existingClusterRoles.Items) == 0 { for _, clusterRole := range append(bootstrappolicy.ClusterRoles(), bootstrappolicy.ControllerRoles()...) { if _, err := clientset.ClusterRoles().Create(&clusterRole); err != nil { // don't fail on failures, try to create as many as you can utilruntime.HandleError(fmt.Errorf("unable to initialize clusterroles: %v", err)) continue } glog.Infof("Created clusterrole.%s/%s", rbac.GroupName, clusterRole.Name) } } </ins> <del> for _, clusterRoleBinding := range append(bootstrappolicy.ClusterRoleBindings(), bootstrappolicy.ControllerRoleBindings()...) { if _, err := clientset.ClusterRoleBindings().Create(&clusterRoleBinding); err != nil { // don't fail on failures, try to create as many as you can </del> <ins> existingClusterRoleBindings, err := clientset.ClusterRoleBindings().List(api.ListOptions{}) if err != nil { </ins> utilruntime.HandleError(fmt.Errorf("unable to initialize clusterrolebindings: %v", err)) <del> continue </del> <ins> return false, nil } // only initialized on empty etcd if len(existingClusterRoleBindings.Items) == 0 { for _, clusterRoleBinding := range append(bootstrappolicy.ClusterRoleBindings(), bootstrappolicy.ControllerRoleBindings()...) { if _, err := clientset.ClusterRoleBindings().Create(&clusterRoleBinding); err != nil { // don't fail on failures, try to create as many as you can utilruntime.HandleError(fmt.Errorf("unable to initialize clusterrolebindings: %v", err)) continue } glog.Infof("Created clusterrolebinding.%s/%s", rbac.GroupName, clusterRoleBinding.Name) } </ins> } <del> glog.Infof("Created clusterrolebinding.%s/%s", rbac.GroupName, clusterRoleBinding.Name) </del> <ins> return true, nil }) // if we're never able to make it through intialization, kill the API server if err != nil { return fmt.Errorf("unable to initialize roles: %v", err) </ins> } return nil


package controller import ( <del> "hash/adler32" </del> <ins> "hash/fnv" </ins> "sync" "github.com/golang/groupcache/lru"


// Since we match objects by namespace and Labels/Selector, so if two objects have the same namespace and labels, // they will have the same key. func keyFunc(obj objectWithMeta) uint64 { <del> hash := adler32.New() </del> <ins> hash := fnv.New32a() </ins> hashutil.DeepHashObject(hash, &equivalenceLabelObj{ namespace: obj.GetNamespace(), labels:    obj.GetLabels(),


import ( "bufio" "fmt" <del> "hash/adler32" </del> <ins> "hash/fnv" </ins> "io" "os" "os/exec"


} func readProcMountsFrom(file io.Reader, out *[]MountPoint) (uint32, error) { <del> hash := adler32.New() </del> <ins> hash := fnv.New32a() </ins> scanner := bufio.NewReader(file) for { line, err := scanner.ReadString('n')


/dev/1    /path/to/1   type1	flags 1 1 /dev/2 /path/to/2 type2 flags,1,2=3 2 2 ` <ins> // NOTE: readProcMountsFrom has been updated to using fnv.New32a() </ins> hash, err := readProcMountsFrom(strings.NewReader(successCase), nil) if err != nil { t.Errorf("expected success") } <del> if hash != 0xa3522051 { t.Errorf("expected 0xa3522051, got %#x", hash) </del> <ins> if hash != 0xa290ff0b { t.Errorf("expected 0xa290ff0b, got %#x", hash) </ins> } mounts := []MountPoint{} hash, err = readProcMountsFrom(strings.NewReader(successCase), &mounts) if err != nil { t.Errorf("expected success") } <del> if hash != 0xa3522051 { t.Errorf("expected 0xa3522051, got %#x", hash) </del> <ins> if hash != 0xa290ff0b { t.Errorf("expected 0xa290ff0b, got %#x", hash) </ins> } if len(mounts) != 3 { t.Fatalf("expected 3 mounts, got %d", len(mounts))


package core import ( <del> "hash/adler32" </del> <ins> "hash/fnv" </ins> "github.com/golang/groupcache/lru"


// hashEquivalencePod returns the hash of equivalence pod. func (ec *EquivalenceCache) hashEquivalencePod(pod *v1.Pod) uint64 { equivalencePod := ec.getEquivalencePod(pod) <del> hash := adler32.New() </del> <ins> hash := fnv.New32a() </ins> hashutil.DeepHashObject(hash, equivalencePod) return uint64(hash.Sum32()) }


type cacheWatcher struct { sync.Mutex copier  runtime.ObjectCopier <del> input   chan *watchCacheEvent </del> <ins> input   chan watchCacheEvent </ins> result  chan watch.Event done    chan struct{} filter  watchFilterFunc


func newCacheWatcher(copier runtime.ObjectCopier, resourceVersion uint64, chanSize int, initEvents []*watchCacheEvent, filter watchFilterFunc, forget func(bool)) *cacheWatcher { watcher := &cacheWatcher{ copier:  copier, <del> input:   make(chan *watchCacheEvent, chanSize), </del> <ins> input:   make(chan watchCacheEvent, chanSize), </ins> result:  make(chan watch.Event, chanSize), done:    make(chan struct{}), filter:  filter,