<commit_before>/*
Copyright 2017 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package server

import (
	"fmt"
	"io"
	"net"

	"github.com/spf13/cobra"

	"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
	"k8s.io/apiextensions-apiserver/pkg/apiserver"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	utilerrors "k8s.io/apimachinery/pkg/util/errors"
	genericregistry "k8s.io/apiserver/pkg/registry/generic"
	genericapiserver "k8s.io/apiserver/pkg/server"
	genericoptions "k8s.io/apiserver/pkg/server/options"
)

const defaultEtcdPathPrefix = "/registry/apiextensions.kubernetes.io"

type CustomResourceDefinitionsServerOptions struct {
	RecommendedOptions *genericoptions.RecommendedOptions
	APIEnablement      *genericoptions.APIEnablementOptions

	StdOut io.Writer
	StdErr io.Writer
}

func NewCustomResourceDefinitionsServerOptions(out, errOut io.Writer) *CustomResourceDefinitionsServerOptions {
	o := &CustomResourceDefinitionsServerOptions{
		RecommendedOptions: genericoptions.NewRecommendedOptions(defaultEtcdPathPrefix, apiserver.Codecs.LegacyCodec(v1beta1.SchemeGroupVersion)),
		APIEnablement:      genericoptions.NewAPIEnablementOptions(),

		StdOut: out,
		StdErr: errOut,
	}

	// the shared informer is not needed for kube-aggregator. Disable the kubeconfig flag and the client creation.
	o.RecommendedOptions.CoreAPI = nil

	return o
}

func NewCommandStartCustomResourceDefinitionsServer(out, errOut io.Writer, stopCh <-chan struct{}) *cobra.Command {
	o := NewCustomResourceDefinitionsServerOptions(out, errOut)

	cmd := &cobra.Command{
		Short: "Launch an API extensions API server",
		Long:  "Launch an API extensions API server",
		RunE: func(c *cobra.Command, args []string) error {
			if err := o.Complete(); err != nil {
				return err
			}
			if err := o.Validate(args); err != nil {
				return err
			}
			if err := o.RunCustomResourceDefinitionsServer(stopCh); err != nil {
				return err
			}
			return nil
		},
	}

	flags := cmd.Flags()
	o.RecommendedOptions.AddFlags(flags)
	o.APIEnablement.AddFlags(flags)
	return cmd
}

func (o CustomResourceDefinitionsServerOptions) Validate(args []string) error {
	errors := []error{}
	errors = append(errors, o.RecommendedOptions.Validate()...)
	errors = append(errors, o.APIEnablement.Validate(apiserver.Scheme)...)
	return utilerrors.NewAggregate(errors)
}

func (o *CustomResourceDefinitionsServerOptions) Complete() error {
	return nil
}

func (o CustomResourceDefinitionsServerOptions) Config() (*apiserver.Config, error) {
	// TODO have a "real" external address
	if err := o.RecommendedOptions.SecureServing.MaybeDefaultWithSelfSignedCerts("localhost", nil, []net.IP{net.ParseIP("127.0.0.1")}); err != nil {
		return nil, fmt.Errorf("error creating self-signed certificates: %v", err)
	}

	serverConfig := genericapiserver.NewRecommendedConfig(apiserver.Codecs)
	if err := o.RecommendedOptions.ApplyTo(serverConfig, apiserver.Scheme); err != nil {
		return nil, err
	}
	if err := o.APIEnablement.ApplyTo(&serverConfig.Config, apiserver.DefaultAPIResourceConfigSource(), apiserver.Scheme); err != nil {
		return nil, err
	}

	config := &apiserver.Config{
		GenericConfig: serverConfig,
		ExtraConfig: apiserver.ExtraConfig{
			CRDRESTOptionsGetter: NewCRDRESTOptionsGetter(*o.RecommendedOptions.Etcd),
		},
	}
	return config, nil
}

func NewCRDRESTOptionsGetter(etcdOptions genericoptions.EtcdOptions) genericregistry.RESTOptionsGetter {
	ret := apiserver.CRDRESTOptionsGetter{
		StorageConfig:           etcdOptions.StorageConfig,
		StoragePrefix:           etcdOptions.StorageConfig.Prefix,
		EnableWatchCache:        etcdOptions.EnableWatchCache,
		DefaultWatchCacheSize:   etcdOptions.DefaultWatchCacheSize,
		EnableGarbageCollection: etcdOptions.EnableGarbageCollection,
		DeleteCollectionWorkers: etcdOptions.DeleteCollectionWorkers,
	}
	ret.StorageConfig.Codec = unstructured.UnstructuredJSONScheme

	return ret
}

func (o CustomResourceDefinitionsServerOptions) RunCustomResourceDefinitionsServer(stopCh <-chan struct{}) error {
	config, err := o.Config()
	if err != nil {
		return err
	}

	server, err := config.Complete().New(genericapiserver.NewEmptyDelegate())
	if err != nil {
		return err
	}
	return server.GenericAPIServer.PrepareRun().Run(stopCh)
}
<commit_msg>fix typo<commit_after>/*
Copyright 2017 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package server

import (
	"fmt"
	"io"
	"net"

	"github.com/spf13/cobra"

	"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
	"k8s.io/apiextensions-apiserver/pkg/apiserver"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	utilerrors "k8s.io/apimachinery/pkg/util/errors"
	genericregistry "k8s.io/apiserver/pkg/registry/generic"
	genericapiserver "k8s.io/apiserver/pkg/server"
	genericoptions "k8s.io/apiserver/pkg/server/options"
)

const defaultEtcdPathPrefix = "/registry/apiextensions.kubernetes.io"

type CustomResourceDefinitionsServerOptions struct {
	RecommendedOptions *genericoptions.RecommendedOptions
	APIEnablement      *genericoptions.APIEnablementOptions

	StdOut io.Writer
	StdErr io.Writer
}

func NewCustomResourceDefinitionsServerOptions(out, errOut io.Writer) *CustomResourceDefinitionsServerOptions {
	o := &CustomResourceDefinitionsServerOptions{
		RecommendedOptions: genericoptions.NewRecommendedOptions(defaultEtcdPathPrefix, apiserver.Codecs.LegacyCodec(v1beta1.SchemeGroupVersion)),
		APIEnablement:      genericoptions.NewAPIEnablementOptions(),

		StdOut: out,
		StdErr: errOut,
	}

	// the shared informer is not needed for apiextentions apiserver. Disable the kubeconfig flag and the client creation.
	o.RecommendedOptions.CoreAPI = nil

	return o
}

func NewCommandStartCustomResourceDefinitionsServer(out, errOut io.Writer, stopCh <-chan struct{}) *cobra.Command {
	o := NewCustomResourceDefinitionsServerOptions(out, errOut)

	cmd := &cobra.Command{
		Short: "Launch an API extensions API server",
		Long:  "Launch an API extensions API server",
		RunE: func(c *cobra.Command, args []string) error {
			if err := o.Complete(); err != nil {
				return err
			}
			if err := o.Validate(args); err != nil {
				return err
			}
			if err := o.RunCustomResourceDefinitionsServer(stopCh); err != nil {
				return err
			}
			return nil
		},
	}

	flags := cmd.Flags()
	o.RecommendedOptions.AddFlags(flags)
	o.APIEnablement.AddFlags(flags)
	return cmd
}

func (o CustomResourceDefinitionsServerOptions) Validate(args []string) error {
	errors := []error{}
	errors = append(errors, o.RecommendedOptions.Validate()...)
	errors = append(errors, o.APIEnablement.Validate(apiserver.Scheme)...)
	return utilerrors.NewAggregate(errors)
}

func (o *CustomResourceDefinitionsServerOptions) Complete() error {
	return nil
}

func (o CustomResourceDefinitionsServerOptions) Config() (*apiserver.Config, error) {
	// TODO have a "real" external address
	if err := o.RecommendedOptions.SecureServing.MaybeDefaultWithSelfSignedCerts("localhost", nil, []net.IP{net.ParseIP("127.0.0.1")}); err != nil {
		return nil, fmt.Errorf("error creating self-signed certificates: %v", err)
	}

	serverConfig := genericapiserver.NewRecommendedConfig(apiserver.Codecs)
	if err := o.RecommendedOptions.ApplyTo(serverConfig, apiserver.Scheme); err != nil {
		return nil, err
	}
	if err := o.APIEnablement.ApplyTo(&serverConfig.Config, apiserver.DefaultAPIResourceConfigSource(), apiserver.Scheme); err != nil {
		return nil, err
	}

	config := &apiserver.Config{
		GenericConfig: serverConfig,
		ExtraConfig: apiserver.ExtraConfig{
			CRDRESTOptionsGetter: NewCRDRESTOptionsGetter(*o.RecommendedOptions.Etcd),
		},
	}
	return config, nil
}

func NewCRDRESTOptionsGetter(etcdOptions genericoptions.EtcdOptions) genericregistry.RESTOptionsGetter {
	ret := apiserver.CRDRESTOptionsGetter{
		StorageConfig:           etcdOptions.StorageConfig,
		StoragePrefix:           etcdOptions.StorageConfig.Prefix,
		EnableWatchCache:        etcdOptions.EnableWatchCache,
		DefaultWatchCacheSize:   etcdOptions.DefaultWatchCacheSize,
		EnableGarbageCollection: etcdOptions.EnableGarbageCollection,
		DeleteCollectionWorkers: etcdOptions.DeleteCollectionWorkers,
	}
	ret.StorageConfig.Codec = unstructured.UnstructuredJSONScheme

	return ret
}

func (o CustomResourceDefinitionsServerOptions) RunCustomResourceDefinitionsServer(stopCh <-chan struct{}) error {
	config, err := o.Config()
	if err != nil {
		return err
	}

	server, err := config.Complete().New(genericapiserver.NewEmptyDelegate())
	if err != nil {
		return err
	}
	return server.GenericAPIServer.PrepareRun().Run(stopCh)
}
<|endoftext|>


<commit_before>/*
Copyright 2015 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package resource

import (
	"fmt"
	"io"
	"math/bits"

	"github.com/gogo/protobuf/proto"
)

var _ proto.Sizer = &Quantity{}

func (m *Quantity) Marshal() (data []byte, err error) {
	size := m.Size()
	data = make([]byte, size)
	n, err := m.MarshalToSizedBuffer(data[:size])
	if err != nil {
		return nil, err
	}
	return data[:n], nil
}

// MarshalTo is a customized version of the generated Protobuf unmarshaler for a struct
// with a single string field.
func (m *Quantity) MarshalTo(data []byte) (int, error) {
	size := m.Size()
	return m.MarshalToSizedBuffer(data[:size])
}

// MarshalToSizedBuffer is a customized version of the generated
// Protobuf unmarshaler for a struct with a single string field.
func (m *Quantity) MarshalToSizedBuffer(data []byte) (int, error) {
	i := len(data)
	_ = i
	var l int
	_ = l

	// BEGIN CUSTOM MARSHAL
	out := m.String()
	i -= len(out)
	copy(data[i:], out)
	i = encodeVarintGenerated(data, i, uint64(len(out)))
	// END CUSTOM MARSHAL
	i--
	data[i] = 0xa

	return len(data) - i, nil
}

func encodeVarintGenerated(data []byte, offset int, v uint64) int {
	offset -= sovGenerated(v)
	base := offset
	for v >= 1<<7 {
		data[offset] = uint8(v&0x7f | 0x80)
		v >>= 7
		offset++
	}
	data[offset] = uint8(v)
	return base
}

func (m *Quantity) Size() (n int) {
	var l int
	_ = l

	// BEGIN CUSTOM SIZE
	l = len(m.String())
	// END CUSTOM SIZE

	n += 1 + l + sovGenerated(uint64(l))
	return n
}

func sovGenerated(x uint64) (n int) {
	return (bits.Len64(x|1) + 6) / 7
}

// Unmarshal is a customized version of the generated Protobuf unmarshaler for a struct
// with a single string field.
func (m *Quantity) 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: Quantity: wiretype end group for non-group")
		}
		if fieldNum <= 0 {
			return fmt.Errorf("proto: Quantity: illegal tag %d (wire type %d)", fieldNum, wire)
		}
		switch fieldNum {
		case 1:
			if wireType != 2 {
				return fmt.Errorf("proto: wrong wireType = %d for field String_", 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
			}
			s := string(data[iNdEx:postIndex])

			// BEGIN CUSTOM DECODE
			p, err := ParseQuantity(s)
			if err != nil {
				return err
			}
			*m = p
			// END CUSTOM DECODE

			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 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")
)
<commit_msg>Additional CVE-2021-3121 fix<commit_after>/*
Copyright 2015 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package resource

import (
	"fmt"
	"io"
	"math/bits"

	"github.com/gogo/protobuf/proto"
)

var _ proto.Sizer = &Quantity{}

func (m *Quantity) Marshal() (data []byte, err error) {
	size := m.Size()
	data = make([]byte, size)
	n, err := m.MarshalToSizedBuffer(data[:size])
	if err != nil {
		return nil, err
	}
	return data[:n], nil
}

// MarshalTo is a customized version of the generated Protobuf unmarshaler for a struct
// with a single string field.
func (m *Quantity) MarshalTo(data []byte) (int, error) {
	size := m.Size()
	return m.MarshalToSizedBuffer(data[:size])
}

// MarshalToSizedBuffer is a customized version of the generated
// Protobuf unmarshaler for a struct with a single string field.
func (m *Quantity) MarshalToSizedBuffer(data []byte) (int, error) {
	i := len(data)
	_ = i
	var l int
	_ = l

	// BEGIN CUSTOM MARSHAL
	out := m.String()
	i -= len(out)
	copy(data[i:], out)
	i = encodeVarintGenerated(data, i, uint64(len(out)))
	// END CUSTOM MARSHAL
	i--
	data[i] = 0xa

	return len(data) - i, nil
}

func encodeVarintGenerated(data []byte, offset int, v uint64) int {
	offset -= sovGenerated(v)
	base := offset
	for v >= 1<<7 {
		data[offset] = uint8(v&0x7f | 0x80)
		v >>= 7
		offset++
	}
	data[offset] = uint8(v)
	return base
}

func (m *Quantity) Size() (n int) {
	var l int
	_ = l

	// BEGIN CUSTOM SIZE
	l = len(m.String())
	// END CUSTOM SIZE

	n += 1 + l + sovGenerated(uint64(l))
	return n
}

func sovGenerated(x uint64) (n int) {
	return (bits.Len64(x|1) + 6) / 7
}

// Unmarshal is a customized version of the generated Protobuf unmarshaler for a struct
// with a single string field.
func (m *Quantity) 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: Quantity: wiretype end group for non-group")
		}
		if fieldNum <= 0 {
			return fmt.Errorf("proto: Quantity: illegal tag %d (wire type %d)", fieldNum, wire)
		}
		switch fieldNum {
		case 1:
			if wireType != 2 {
				return fmt.Errorf("proto: wrong wireType = %d for field String_", 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
			}
			s := string(data[iNdEx:postIndex])

			// BEGIN CUSTOM DECODE
			p, err := ParseQuantity(s)
			if err != nil {
				return err
			}
			*m = p
			// END CUSTOM DECODE

			iNdEx = postIndex
		default:
			iNdEx = preIndex
			skippy, err := skipGenerated(data[iNdEx:])
			if err != nil {
				return err
			}
			if (skippy < 0) || (iNdEx+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")
)
<|endoftext|>


<commit_before>package lua

/*
#cgo pkg-config: --static luajit

#include <lua.h>
#include <lualib.h>
#include <stdlib.h>
*/
import "C"

import (
	"reflect"
	"unsafe"
)

// Type of allocation functions to use with NewStateAlloc
type Alloc func(ptr unsafe.Pointer, osize uint, nsize uint) unsafe.Pointer

// This is the type of go function that can be registered as lua functions
type LuaGoFunction func(L *State) int

// Wrapper to keep cgo from complaining about incomplete ptr type
//export State
type State struct {
	// Wrapped lua_State object
	s *C.lua_State

	// Registry of go object that have been pushed to Lua VM
	registry []interface{}

	// Freelist for funcs indices, to allow for freeing
	freeIndices []uint
}

//export golua_callgofunction
func golua_callgofunction(L interface{}, fid uint) int {
	L1 := L.(*State)
	if fid < 0 {
		panic(&LuaError{0, "Requested execution of an unknown function", L1.StackTrace()})
	}
	f := L1.registry[fid].(LuaGoFunction)
	return f(L1)
}

//export golua_interface_newindex_callback
func golua_interface_newindex_callback(Li interface{}, iid uint, field_name_cstr *C.char) int {
	L := Li.(*State)
	iface := L.registry[iid]
	ifacevalue := reflect.ValueOf(iface).Elem()

	field_name := C.GoString(field_name_cstr)

	fval := ifacevalue.FieldByName(field_name)

	if fval.Kind() == reflect.Ptr {
		fval = fval.Elem()
	}

	luatype := LuaValType(C.lua_type(L.s, 3))

	switch fval.Kind() {
	case reflect.Bool:
		if luatype == LUA_TBOOLEAN {
			fval.SetBool(int(C.lua_toboolean(L.s, 3)) != 0)
			return 1
		} else {
			L.PushString("Wrong assignment to field "+field_name)
			return -1
		}

	case reflect.Int:
		fallthrough
	case reflect.Int8:
		fallthrough
	case reflect.Int16:
		fallthrough
	case reflect.Int32:
		fallthrough
	case reflect.Int64:
		if luatype == LUA_TNUMBER {
			fval.SetInt(int64(C.lua_tointeger(L.s, 3)))
			return 1
		} else {
			L.PushString("Wrong assignment to field "+field_name)
			return -1
		}

	case reflect.Uint:
		fallthrough
	case reflect.Uint8:
		fallthrough
	case reflect.Uint16:
		fallthrough
	case reflect.Uint32:
		fallthrough
	case reflect.Uint64:
		if luatype == LUA_TNUMBER {
			fval.SetUint(uint64(C.lua_tointeger(L.s, 3)))
			return 1
		} else {
			L.PushString("Wrong assignment to field "+field_name)
			return -1
		}

	case reflect.String:
		if luatype == LUA_TSTRING {
			fval.SetString(C.GoString(C.lua_tolstring(L.s, 3, nil)))
			return 1
		} else {
			L.PushString("Wrong assignment to field "+field_name)
			return -1
		}

	case reflect.Float32:
		fallthrough
	case reflect.Float64:
		if luatype == LUA_TNUMBER {
			fval.SetFloat(float64(C.lua_tonumber(L.s, 3)))
			return 1
		} else {
			L.PushString("Wrong assignment to field "+field_name)
			return -1
		}
	}

	L.PushString("Unsupported type of field "+field_name+": "+fval.Type().String())
	return -1
}

//export golua_interface_index_callback
func golua_interface_index_callback(Li interface{}, iid uint, field_name *C.char) int {
	L := Li.(*State)
	iface := L.registry[iid]
	ifacevalue := reflect.ValueOf(iface).Elem()

	fval := ifacevalue.FieldByName(C.GoString(field_name))

	if fval.Kind() == reflect.Ptr {
		fval = fval.Elem()
	}

	switch fval.Kind() {
	case reflect.Bool:
		L.PushBoolean(fval.Bool())
		return 1

	case reflect.Int:
		fallthrough
	case reflect.Int8:
		fallthrough
	case reflect.Int16:
		fallthrough
	case reflect.Int32:
		fallthrough
	case reflect.Int64:
		L.PushInteger(fval.Int())
		return 1

	case reflect.Uint:
		fallthrough
	case reflect.Uint8:
		fallthrough
	case reflect.Uint16:
		fallthrough
	case reflect.Uint32:
		fallthrough
	case reflect.Uint64:
		L.PushInteger(int64(fval.Uint()))
		return 1

	case reflect.String:
		L.PushString(fval.String())
		return 1

	case reflect.Float32:
		fallthrough
	case reflect.Float64:
		L.PushNumber(fval.Float())
		return 1
	}

	L.PushString("Unsupported type of field: "+fval.Type().String())
	return -1
}

//export golua_gchook
func golua_gchook(L interface{}, id uint) int {
	L1 := L.(*State)
	L1.unregister(id)
	return 0
}

//export golua_callpanicfunction
func golua_callpanicfunction(L interface{}, id uint) int {
	L1 := L.(*State)
	f := L1.registry[id].(LuaGoFunction)
	return f(L1)
}

//export golua_idtointerface
func golua_idtointerface(id uint) interface{} {
	return id
}

//export golua_cfunctiontointerface
func golua_cfunctiontointerface(f *uintptr) interface{} {
	return f
}

//export golua_callallocf
func golua_callallocf(fp uintptr, ptr uintptr, osize uint, nsize uint) uintptr {
	return uintptr((*((*Alloc)(unsafe.Pointer(fp))))(unsafe.Pointer(ptr), osize, nsize))
}

//export go_panic_msghandler
func go_panic_msghandler(Li interface{}, z *C.char) {
	L := Li.(*State)
	s := C.GoString(z)

	panic(&LuaError{LUA_ERRERR, s, L.StackTrace()})
}
<commit_msg>Update golua.go<commit_after>package lua

/*
#cgo pkg-config: luajit

#include <lua.h>
#include <lualib.h>
#include <stdlib.h>
*/
import "C"

import (
	"reflect"
	"unsafe"
)

// Type of allocation functions to use with NewStateAlloc
type Alloc func(ptr unsafe.Pointer, osize uint, nsize uint) unsafe.Pointer

// This is the type of go function that can be registered as lua functions
type LuaGoFunction func(L *State) int

// Wrapper to keep cgo from complaining about incomplete ptr type
//export State
type State struct {
	// Wrapped lua_State object
	s *C.lua_State

	// Registry of go object that have been pushed to Lua VM
	registry []interface{}

	// Freelist for funcs indices, to allow for freeing
	freeIndices []uint
}

//export golua_callgofunction
func golua_callgofunction(L interface{}, fid uint) int {
	L1 := L.(*State)
	if fid < 0 {
		panic(&LuaError{0, "Requested execution of an unknown function", L1.StackTrace()})
	}
	f := L1.registry[fid].(LuaGoFunction)
	return f(L1)
}

//export golua_interface_newindex_callback
func golua_interface_newindex_callback(Li interface{}, iid uint, field_name_cstr *C.char) int {
	L := Li.(*State)
	iface := L.registry[iid]
	ifacevalue := reflect.ValueOf(iface).Elem()

	field_name := C.GoString(field_name_cstr)

	fval := ifacevalue.FieldByName(field_name)

	if fval.Kind() == reflect.Ptr {
		fval = fval.Elem()
	}

	luatype := LuaValType(C.lua_type(L.s, 3))

	switch fval.Kind() {
	case reflect.Bool:
		if luatype == LUA_TBOOLEAN {
			fval.SetBool(int(C.lua_toboolean(L.s, 3)) != 0)
			return 1
		} else {
			L.PushString("Wrong assignment to field "+field_name)
			return -1
		}

	case reflect.Int:
		fallthrough
	case reflect.Int8:
		fallthrough
	case reflect.Int16:
		fallthrough
	case reflect.Int32:
		fallthrough
	case reflect.Int64:
		if luatype == LUA_TNUMBER {
			fval.SetInt(int64(C.lua_tointeger(L.s, 3)))
			return 1
		} else {
			L.PushString("Wrong assignment to field "+field_name)
			return -1
		}

	case reflect.Uint:
		fallthrough
	case reflect.Uint8:
		fallthrough
	case reflect.Uint16:
		fallthrough
	case reflect.Uint32:
		fallthrough
	case reflect.Uint64:
		if luatype == LUA_TNUMBER {
			fval.SetUint(uint64(C.lua_tointeger(L.s, 3)))
			return 1
		} else {
			L.PushString("Wrong assignment to field "+field_name)
			return -1
		}

	case reflect.String:
		if luatype == LUA_TSTRING {
			fval.SetString(C.GoString(C.lua_tolstring(L.s, 3, nil)))
			return 1
		} else {
			L.PushString("Wrong assignment to field "+field_name)
			return -1
		}

	case reflect.Float32:
		fallthrough
	case reflect.Float64:
		if luatype == LUA_TNUMBER {
			fval.SetFloat(float64(C.lua_tonumber(L.s, 3)))
			return 1
		} else {
			L.PushString("Wrong assignment to field "+field_name)
			return -1
		}
	}

	L.PushString("Unsupported type of field "+field_name+": "+fval.Type().String())
	return -1
}

//export golua_interface_index_callback
func golua_interface_index_callback(Li interface{}, iid uint, field_name *C.char) int {
	L := Li.(*State)
	iface := L.registry[iid]
	ifacevalue := reflect.ValueOf(iface).Elem()

	fval := ifacevalue.FieldByName(C.GoString(field_name))

	if fval.Kind() == reflect.Ptr {
		fval = fval.Elem()
	}

	switch fval.Kind() {
	case reflect.Bool:
		L.PushBoolean(fval.Bool())
		return 1

	case reflect.Int:
		fallthrough
	case reflect.Int8:
		fallthrough
	case reflect.Int16:
		fallthrough
	case reflect.Int32:
		fallthrough
	case reflect.Int64:
		L.PushInteger(fval.Int())
		return 1

	case reflect.Uint:
		fallthrough
	case reflect.Uint8:
		fallthrough
	case reflect.Uint16:
		fallthrough
	case reflect.Uint32:
		fallthrough
	case reflect.Uint64:
		L.PushInteger(int64(fval.Uint()))
		return 1

	case reflect.String:
		L.PushString(fval.String())
		return 1

	case reflect.Float32:
		fallthrough
	case reflect.Float64:
		L.PushNumber(fval.Float())
		return 1
	}

	L.PushString("Unsupported type of field: "+fval.Type().String())
	return -1
}

//export golua_gchook
func golua_gchook(L interface{}, id uint) int {
	L1 := L.(*State)
	L1.unregister(id)
	return 0
}

//export golua_callpanicfunction
func golua_callpanicfunction(L interface{}, id uint) int {
	L1 := L.(*State)
	f := L1.registry[id].(LuaGoFunction)
	return f(L1)
}

//export golua_idtointerface
func golua_idtointerface(id uint) interface{} {
	return id
}

//export golua_cfunctiontointerface
func golua_cfunctiontointerface(f *uintptr) interface{} {
	return f
}

//export golua_callallocf
func golua_callallocf(fp uintptr, ptr uintptr, osize uint, nsize uint) uintptr {
	return uintptr((*((*Alloc)(unsafe.Pointer(fp))))(unsafe.Pointer(ptr), osize, nsize))
}

//export go_panic_msghandler
func go_panic_msghandler(Li interface{}, z *C.char) {
	L := Li.(*State)
	s := C.GoString(z)

	panic(&LuaError{LUA_ERRERR, s, L.StackTrace()})
}
<|endoftext|>


<commit_before>package shutdown

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os/exec"
	"strconv"

	"github.com/vblazhnov/RemoteControl/interfaces"
)

// Shutdown shutdown the local machine
type Shutdown struct {
}

// GetHandlers implemintation of interfaces.EndPointInfo
func (sh Shutdown) GetHandlers() []interfaces.EndPointInfo {
	handlers := []interfaces.EndPointInfo{
		interfaces.BaseEndPointInfo{
			"/api/v1/shutdown",
			apiServeRequest,
			interfaces.EndPointAPI},
		interfaces.BaseEndPointInfo{
			"/shutdown",
			contentServeRequest,
			interfaces.EndPointContent},
	}

	return handlers
}

func contentServeRequest(
	w http.ResponseWriter,
	r *http.Request) {
	f, e := ioutil.ReadFile(".\\plugins\\shutdown\\static\\index.html")
	if e != nil {
		fmt.Fprint(w, e)
	}
	w.Write(f)
}

func apiServeRequest(
	w http.ResponseWriter,
	r *http.Request) {
	secStr := r.FormValue("sec")

	sec, err := strconv.Atoi(secStr)
	if err != nil {
		sec = 0
	}
	abort()
	if sec != 0 {
		start(sec)
	}
	fmt.Fprint(w, sec)
}

func abort() {
	run("/a")
}

func start(sec int) {
	run("/s", "/t", strconv.Itoa(sec))
}

func run(args ...string) {
	cmd := exec.Command("shutdown", args...)
	err := cmd.Run()
	if err != nil {
		log.Println("error: " + err.Error())
	}
}
<commit_msg>Fix error when incorrect parameter aborting shutdown<commit_after>package shutdown

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os/exec"
	"strconv"

	"github.com/vblazhnov/RemoteControl/interfaces"
)

// Shutdown shutdown the local machine
type Shutdown struct {
}

// GetHandlers implemintation of interfaces.EndPointInfo
func (sh Shutdown) GetHandlers() []interfaces.EndPointInfo {
	handlers := []interfaces.EndPointInfo{
		interfaces.BaseEndPointInfo{
			"/api/v1/shutdown",
			apiServeRequest,
			interfaces.EndPointAPI},
		interfaces.BaseEndPointInfo{
			"/shutdown",
			contentServeRequest,
			interfaces.EndPointContent},
	}

	return handlers
}

func contentServeRequest(
	w http.ResponseWriter,
	r *http.Request) {
	f, e := ioutil.ReadFile(".\\plugins\\shutdown\\static\\index.html")
	if e != nil {
		fmt.Fprint(w, e)
	}
	w.Write(f)
}

func apiServeRequest(
	w http.ResponseWriter,
	r *http.Request) {
	secStr := r.FormValue("sec")

	sec, err := strconv.Atoi(secStr)
	if err != nil {
		sec = 0
	}
	if sec != 0 {
		abort()
		start(sec)
		fmt.Fprint(w, sec)
	} else {
		http.Error(w, http.StatusText(500), 500)
	}
}

func abort() {
	run("/a")
}

func start(sec int) {
	run("/s", "/t", strconv.Itoa(sec))
}

func run(args ...string) {
	cmd := exec.Command("shutdown", args...)
	err := cmd.Run()
	if err != nil {
		log.Println("error: " + err.Error())
	}
}
<|endoftext|>


<commit_before>package mockery

import (
	"go/ast"
	"go/importer"
	"go/types"
	"io/ioutil"
	"path/filepath"

	"golang.org/x/tools/go/loader"
)

type Parser struct {
	file           *ast.File
	path           string
	nameToASTFiles map[string][]*ast.File
	parserPackages []*types.Package
}

func NewParser() *Parser {
	return &Parser{
		parserPackages: make([]*types.Package, 0),
		nameToASTFiles: make(map[string][]*ast.File),
	}
}

func (p *Parser) Parse(path string) error {
	dir := filepath.Dir(path)

	files, err := ioutil.ReadDir(dir)
	if err != nil {
		return err
	}

	var conf loader.Config

	conf.TypeCheckFuncBodies = func(_ string) bool { return false }
	conf.TypeChecker.DisableUnusedImportCheck = true
	conf.TypeChecker.Importer = importer.Default()

	for _, fi := range files {
		if filepath.Ext(fi.Name()) != ".go" {
			continue
		}

		fpath := filepath.Join(dir, fi.Name())
		f, err := conf.ParseFile(fpath, nil)
		if err != nil {
			return err
		}

		if fi.Name() == filepath.Base(path) {
			p.file = f
		}
		p.nameToASTFiles[f.Name.String()] = append(p.nameToASTFiles[f.Name.String()], f)
	}

	abs, err := filepath.Abs(path)
	if err != nil {
		return err
	}
	p.path = abs

	// Type-check a package consisting of this file.
	// Type information for the imported packages
	// comes from $GOROOT/pkg/$GOOS_$GOOARCH/fmt.a.
	for _, files := range p.nameToASTFiles {
		conf.CreateFromFiles(abs, files...)
	}

	prog, err := conf.Load()
	if err != nil {
		return err
	}

	for _, pkgInfo := range prog.Created {
		p.parserPackages = append(p.parserPackages, pkgInfo.Pkg)
	}

	return nil
}

func (p *Parser) Find(name string) (*Interface, error) {
	for _, pkg := range p.parserPackages {
		if iface := p.FindInPackage(name, pkg); iface != nil {
			return iface, nil
		}
	}
	return nil, ErrNotInterface
}

func (p *Parser) FindInPackage(name string, pkg *types.Package) *Interface {
	obj := pkg.Scope().Lookup(name)
	if obj == nil {
		return nil
	}

	typ := obj.Type().(*types.Named)

	name = typ.Obj().Name()

	iface := typ.Underlying().(*types.Interface).Complete()

	return &Interface{name, p.path, p.file, pkg, iface, typ}
}

/*
func (p *Parser) FindOld(name string) (*Interface, error) {
	for _, decl := range p.file.Decls {
		if gen, ok := decl.(*ast.GenDecl); ok {
			for _, spec := range gen.Specs {
				if typespec, ok := spec.(*ast.TypeSpec); ok {
					if typespec.Name.Name == name {
						if iface, ok := typespec.Type.(*ast.InterfaceType); ok {
							return &Interface{name, p.path, p.file, iface}, nil
						} else {
							return nil, ErrNotInterface
						}
					}
				}
			}
		}
	}
	return nil, nil
}
*/

type Interface struct {
	Name      string
	Path      string
	File      *ast.File
	Pkg       *types.Package
	Type      *types.Interface
	NamedType *types.Named
}

func (p *Parser) getFileForInterfaceName(name string) *ast.File {
	for _, astFiles := range p.nameToASTFiles {
		for _, file := range astFiles {
			if file.Scope.Lookup(name) != nil {
				return file
			}
		}
	}
	return p.file
}

func (p *Parser) Interfaces() (ifaces []*Interface) {
	for _, pkg := range p.parserPackages {
		ifaces = p.packageInterfaces(pkg, ifaces)
	}
	return
}

func (p *Parser) packageInterfaces(pkg *types.Package, ifaces []*Interface) []*Interface {

	scope := pkg.Scope()

	for _, name := range scope.Names() {
		obj := scope.Lookup(name)
		if obj == nil {
			continue
		}

		typ, ok := obj.Type().(*types.Named)
		if !ok {
			continue
		}

		name = typ.Obj().Name()

		iface, ok := typ.Underlying().(*types.Interface)
		if !ok {
			continue
		}

		ifaces = append(
			ifaces,
			&Interface{
				name, p.path, p.getFileForInterfaceName(name), pkg,
				iface.Complete(), typ,
			},
		)
	}

	return ifaces
}
<commit_msg>add check for _test.go to parser<commit_after>package mockery

import (
	"go/ast"
	"go/importer"
	"go/types"
	"io/ioutil"
	"path/filepath"
	"strings"

	"golang.org/x/tools/go/loader"
)

type Parser struct {
	file           *ast.File
	path           string
	nameToASTFiles map[string][]*ast.File
	parserPackages []*types.Package
}

func NewParser() *Parser {
	return &Parser{
		parserPackages: make([]*types.Package, 0),
		nameToASTFiles: make(map[string][]*ast.File),
	}
}

func (p *Parser) Parse(path string) error {
	dir := filepath.Dir(path)

	files, err := ioutil.ReadDir(dir)
	if err != nil {
		return err
	}

	var conf loader.Config

	conf.TypeCheckFuncBodies = func(_ string) bool { return false }
	conf.TypeChecker.DisableUnusedImportCheck = true
	conf.TypeChecker.Importer = importer.Default()

	for _, fi := range files {
		if filepath.Ext(fi.Name()) != ".go" || strings.HasSuffix(fi.Name(), "_test.go") {
			continue
		}

		fpath := filepath.Join(dir, fi.Name())
		f, err := conf.ParseFile(fpath, nil)
		if err != nil {
			return err
		}

		if fi.Name() == filepath.Base(path) {
			p.file = f
		}
		p.nameToASTFiles[f.Name.String()] = append(p.nameToASTFiles[f.Name.String()], f)
	}

	abs, err := filepath.Abs(path)
	if err != nil {
		return err
	}
	p.path = abs

	// Type-check a package consisting of this file.
	// Type information for the imported packages
	// comes from $GOROOT/pkg/$GOOS_$GOOARCH/fmt.a.
	for _, files := range p.nameToASTFiles {
		conf.CreateFromFiles(abs, files...)
	}

	prog, err := conf.Load()
	if err != nil {
		return err
	}

	for _, pkgInfo := range prog.Created {
		p.parserPackages = append(p.parserPackages, pkgInfo.Pkg)
	}

	return nil
}

func (p *Parser) Find(name string) (*Interface, error) {
	for _, pkg := range p.parserPackages {
		if iface := p.FindInPackage(name, pkg); iface != nil {
			return iface, nil
		}
	}
	return nil, ErrNotInterface
}

func (p *Parser) FindInPackage(name string, pkg *types.Package) *Interface {
	obj := pkg.Scope().Lookup(name)
	if obj == nil {
		return nil
	}

	typ := obj.Type().(*types.Named)

	name = typ.Obj().Name()

	iface := typ.Underlying().(*types.Interface).Complete()

	return &Interface{name, p.path, p.file, pkg, iface, typ}
}

/*
func (p *Parser) FindOld(name string) (*Interface, error) {
	for _, decl := range p.file.Decls {
		if gen, ok := decl.(*ast.GenDecl); ok {
			for _, spec := range gen.Specs {
				if typespec, ok := spec.(*ast.TypeSpec); ok {
					if typespec.Name.Name == name {
						if iface, ok := typespec.Type.(*ast.InterfaceType); ok {
							return &Interface{name, p.path, p.file, iface}, nil
						} else {
							return nil, ErrNotInterface
						}
					}
				}
			}
		}
	}
	return nil, nil
}
*/

type Interface struct {
	Name      string
	Path      string
	File      *ast.File
	Pkg       *types.Package
	Type      *types.Interface
	NamedType *types.Named
}

func (p *Parser) getFileForInterfaceName(name string) *ast.File {
	for _, astFiles := range p.nameToASTFiles {
		for _, file := range astFiles {
			if file.Scope.Lookup(name) != nil {
				return file
			}
		}
	}
	return p.file
}

func (p *Parser) Interfaces() (ifaces []*Interface) {
	for _, pkg := range p.parserPackages {
		ifaces = p.packageInterfaces(pkg, ifaces)
	}
	return
}

func (p *Parser) packageInterfaces(pkg *types.Package, ifaces []*Interface) []*Interface {

	scope := pkg.Scope()

	for _, name := range scope.Names() {
		obj := scope.Lookup(name)
		if obj == nil {
			continue
		}

		typ, ok := obj.Type().(*types.Named)
		if !ok {
			continue
		}

		name = typ.Obj().Name()

		iface, ok := typ.Underlying().(*types.Interface)
		if !ok {
			continue
		}

		ifaces = append(
			ifaces,
			&Interface{
				name, p.path, p.getFileForInterfaceName(name), pkg,
				iface.Complete(), typ,
			},
		)
	}

	return ifaces
}
<|endoftext|>


<commit_before>package mocks

import "github.com/stretchr/testify/mock"

import "github.com/aws/aws-sdk-go/aws"
import "github.com/aws/aws-sdk-go/aws/service"
import "github.com/aws/aws-sdk-go/service/kinesis"

type Kinesis struct {
	mock.Mock
}

func (m *Kinesis) AddTagsToStreamRequest(_a0 *kinesis.AddTagsToStreamInput) (*service.Request, *kinesis.AddTagsToStreamOutput) {
	ret := m.Called(_a0)

	var r0 *service.Request
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*service.Request)
	}
	var r1 *kinesis.AddTagsToStreamOutput
	if ret.Get(1) != nil {
		r1 = ret.Get(1).(*kinesis.AddTagsToStreamOutput)
	}

	return r0, r1
}
func (m *Kinesis) AddTagsToStream(_a0 *kinesis.AddTagsToStreamInput) (*kinesis.AddTagsToStreamOutput, error) {
	ret := m.Called(_a0)

	var r0 *kinesis.AddTagsToStreamOutput
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*kinesis.AddTagsToStreamOutput)
	}
	r1 := ret.Error(1)

	return r0, r1
}
func (m *Kinesis) CreateStreamRequest(_a0 *kinesis.CreateStreamInput) (*service.Request, *kinesis.CreateStreamOutput) {
	ret := m.Called(_a0)

	var r0 *service.Request
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*service.Request)
	}
	var r1 *kinesis.CreateStreamOutput
	if ret.Get(1) != nil {
		r1 = ret.Get(1).(*kinesis.CreateStreamOutput)
	}

	return r0, r1
}
func (m *Kinesis) CreateStream(_a0 *kinesis.CreateStreamInput) (*kinesis.CreateStreamOutput, error) {
	ret := m.Called(_a0)

	var r0 *kinesis.CreateStreamOutput
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*kinesis.CreateStreamOutput)
	}
	r1 := ret.Error(1)

	return r0, r1
}
func (m *Kinesis) DeleteStreamRequest(_a0 *kinesis.DeleteStreamInput) (*service.Request, *kinesis.DeleteStreamOutput) {
	ret := m.Called(_a0)

	var r0 *service.Request
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*service.Request)
	}
	var r1 *kinesis.DeleteStreamOutput
	if ret.Get(1) != nil {
		r1 = ret.Get(1).(*kinesis.DeleteStreamOutput)
	}

	return r0, r1
}
func (m *Kinesis) DeleteStream(_a0 *kinesis.DeleteStreamInput) (*kinesis.DeleteStreamOutput, error) {
	ret := m.Called(_a0)

	var r0 *kinesis.DeleteStreamOutput
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*kinesis.DeleteStreamOutput)
	}
	r1 := ret.Error(1)

	return r0, r1
}
func (m *Kinesis) DescribeStreamRequest(_a0 *kinesis.DescribeStreamInput) (*service.Request, *kinesis.DescribeStreamOutput) {
	ret := m.Called(_a0)

	var r0 *service.Request
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*service.Request)
	}
	var r1 *kinesis.DescribeStreamOutput
	if ret.Get(1) != nil {
		r1 = ret.Get(1).(*kinesis.DescribeStreamOutput)
	}

	return r0, r1
}
func (m *Kinesis) DescribeStream(_a0 *kinesis.DescribeStreamInput) (*kinesis.DescribeStreamOutput, error) {
	ret := m.Called(_a0)

	var r0 *kinesis.DescribeStreamOutput
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*kinesis.DescribeStreamOutput)
	}
	r1 := ret.Error(1)

	return r0, r1
}
func (m *Kinesis) DescribeStreamPages(_a0 *kinesis.DescribeStreamInput, _a1 func(*kinesis.DescribeStreamOutput, bool) bool) error {
	ret := m.Called(_a0, _a1)

	a := kinesis.Shard{
		AdjacentParentShardID: nil,
		HashKeyRange: &kinesis.HashKeyRange{
			StartingHashKey: aws.String("0"),
			EndingHashKey:   aws.String("7f"),
		},
		ParentShardID: nil,
		SequenceNumberRange: &kinesis.SequenceNumberRange{
			StartingSequenceNumber: aws.String("0"),
			EndingSequenceNumber:   aws.String("100"),
		},
		ShardID: aws.String("shard0"),
	}
	b := kinesis.Shard{
		AdjacentParentShardID: nil,
		HashKeyRange: &kinesis.HashKeyRange{
			StartingHashKey: aws.String("80"),
			EndingHashKey:   aws.String("ff"),
		},
		ParentShardID: nil,
		SequenceNumberRange: &kinesis.SequenceNumberRange{
			StartingSequenceNumber: aws.String("101"),
			EndingSequenceNumber:   aws.String("200"),
		},
		ShardID: aws.String("shard1"),
	}
	cont := _a1(
		&kinesis.DescribeStreamOutput{
			StreamDescription: &kinesis.StreamDescription{
				HasMoreShards: aws.Bool(true),
				Shards:        []*kinesis.Shard{&a},
				StreamName:    aws.String("TestStream"),
				StreamStatus:  aws.String("ACTIVE"),
			},
		}, true)
	if cont {
		_a1(
			&kinesis.DescribeStreamOutput{
				StreamDescription: &kinesis.StreamDescription{
					HasMoreShards: aws.Bool(true),
					Shards:        []*kinesis.Shard{&b},
					StreamName:    aws.String("TestStream"),
					StreamStatus:  aws.String("ACTIVE"),
				},
			}, false)
	}
	r0 := ret.Error(0)

	return r0
}
func (m *Kinesis) GetRecordsRequest(_a0 *kinesis.GetRecordsInput) (*service.Request, *kinesis.GetRecordsOutput) {
	ret := m.Called(_a0)

	var r0 *service.Request
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*service.Request)
	}
	var r1 *kinesis.GetRecordsOutput
	if ret.Get(1) != nil {
		r1 = ret.Get(1).(*kinesis.GetRecordsOutput)
	}

	return r0, r1
}
func (m *Kinesis) GetRecords(_a0 *kinesis.GetRecordsInput) (*kinesis.GetRecordsOutput, error) {
	ret := m.Called(_a0)

	var r0 *kinesis.GetRecordsOutput
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*kinesis.GetRecordsOutput)
	}
	r1 := ret.Error(1)

	return r0, r1
}
func (m *Kinesis) GetShardIteratorRequest(_a0 *kinesis.GetShardIteratorInput) (*service.Request, *kinesis.GetShardIteratorOutput) {
	ret := m.Called(_a0)

	var r0 *service.Request
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*service.Request)
	}
	var r1 *kinesis.GetShardIteratorOutput
	if ret.Get(1) != nil {
		r1 = ret.Get(1).(*kinesis.GetShardIteratorOutput)
	}

	return r0, r1
}
func (m *Kinesis) GetShardIterator(_a0 *kinesis.GetShardIteratorInput) (*kinesis.GetShardIteratorOutput, error) {
	ret := m.Called(_a0)

	var r0 *kinesis.GetShardIteratorOutput
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*kinesis.GetShardIteratorOutput)
	}
	r1 := ret.Error(1)

	return r0, r1
}
func (m *Kinesis) ListStreamsRequest(_a0 *kinesis.ListStreamsInput) (*service.Request, *kinesis.ListStreamsOutput) {
	ret := m.Called(_a0)

	var r0 *service.Request
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*service.Request)
	}
	var r1 *kinesis.ListStreamsOutput
	if ret.Get(1) != nil {
		r1 = ret.Get(1).(*kinesis.ListStreamsOutput)
	}

	return r0, r1
}
func (m *Kinesis) ListStreams(_a0 *kinesis.ListStreamsInput) (*kinesis.ListStreamsOutput, error) {
	ret := m.Called(_a0)

	var r0 *kinesis.ListStreamsOutput
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*kinesis.ListStreamsOutput)
	}
	r1 := ret.Error(1)

	return r0, r1
}
func (m *Kinesis) ListStreamsPages(_a0 *kinesis.ListStreamsInput, _a1 func(*kinesis.ListStreamsOutput, bool) bool) error {
	ret := m.Called(_a0, _a1)

	cont := _a1(&kinesis.ListStreamsOutput{
		HasMoreStreams: aws.Bool(true),
		StreamNames:    []*string{aws.String("a"), aws.String("b")},
	}, true)
	if cont {
		_a1(&kinesis.ListStreamsOutput{
			HasMoreStreams: aws.Bool(false),
			StreamNames:    []*string{aws.String("c")},
		}, false)
	}
	r0 := ret.Error(0)

	return r0
}
func (m *Kinesis) ListTagsForStreamRequest(_a0 *kinesis.ListTagsForStreamInput) (*service.Request, *kinesis.ListTagsForStreamOutput) {
	ret := m.Called(_a0)

	var r0 *service.Request
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*service.Request)
	}
	var r1 *kinesis.ListTagsForStreamOutput
	if ret.Get(1) != nil {
		r1 = ret.Get(1).(*kinesis.ListTagsForStreamOutput)
	}

	return r0, r1
}
func (m *Kinesis) ListTagsForStream(_a0 *kinesis.ListTagsForStreamInput) (*kinesis.ListTagsForStreamOutput, error) {
	ret := m.Called(_a0)

	var r0 *kinesis.ListTagsForStreamOutput
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*kinesis.ListTagsForStreamOutput)
	}
	r1 := ret.Error(1)

	return r0, r1
}
func (m *Kinesis) MergeShardsRequest(_a0 *kinesis.MergeShardsInput) (*service.Request, *kinesis.MergeShardsOutput) {
	ret := m.Called(_a0)

	var r0 *service.Request
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*service.Request)
	}
	var r1 *kinesis.MergeShardsOutput
	if ret.Get(1) != nil {
		r1 = ret.Get(1).(*kinesis.MergeShardsOutput)
	}

	return r0, r1
}
func (m *Kinesis) MergeShards(_a0 *kinesis.MergeShardsInput) (*kinesis.MergeShardsOutput, error) {
	ret := m.Called(_a0)

	var r0 *kinesis.MergeShardsOutput
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*kinesis.MergeShardsOutput)
	}
	r1 := ret.Error(1)

	return r0, r1
}
func (m *Kinesis) PutRecordRequest(_a0 *kinesis.PutRecordInput) (*service.Request, *kinesis.PutRecordOutput) {
	ret := m.Called(_a0)

	var r0 *service.Request
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*service.Request)
	}
	var r1 *kinesis.PutRecordOutput
	if ret.Get(1) != nil {
		r1 = ret.Get(1).(*kinesis.PutRecordOutput)
	}

	return r0, r1
}
func (m *Kinesis) PutRecord(_a0 *kinesis.PutRecordInput) (*kinesis.PutRecordOutput, error) {
	ret := m.Called(_a0)

	var r0 *kinesis.PutRecordOutput
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*kinesis.PutRecordOutput)
	}
	r1 := ret.Error(1)

	return r0, r1
}
func (m *Kinesis) PutRecordsRequest(_a0 *kinesis.PutRecordsInput) (*service.Request, *kinesis.PutRecordsOutput) {
	ret := m.Called(_a0)

	var r0 *service.Request
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*service.Request)
	}
	var r1 *kinesis.PutRecordsOutput
	if ret.Get(1) != nil {
		r1 = ret.Get(1).(*kinesis.PutRecordsOutput)
	}

	return r0, r1
}
func (m *Kinesis) PutRecords(_a0 *kinesis.PutRecordsInput) (*kinesis.PutRecordsOutput, error) {
	ret := m.Called(_a0)

	var r0 *kinesis.PutRecordsOutput
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*kinesis.PutRecordsOutput)
	}
	r1 := ret.Error(1)

	return r0, r1
}
func (m *Kinesis) RemoveTagsFromStreamRequest(_a0 *kinesis.RemoveTagsFromStreamInput) (*service.Request, *kinesis.RemoveTagsFromStreamOutput) {
	ret := m.Called(_a0)

	var r0 *service.Request
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*service.Request)
	}
	var r1 *kinesis.RemoveTagsFromStreamOutput
	if ret.Get(1) != nil {
		r1 = ret.Get(1).(*kinesis.RemoveTagsFromStreamOutput)
	}

	return r0, r1
}
func (m *Kinesis) RemoveTagsFromStream(_a0 *kinesis.RemoveTagsFromStreamInput) (*kinesis.RemoveTagsFromStreamOutput, error) {
	ret := m.Called(_a0)

	var r0 *kinesis.RemoveTagsFromStreamOutput
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*kinesis.RemoveTagsFromStreamOutput)
	}
	r1 := ret.Error(1)

	return r0, r1
}
func (m *Kinesis) SplitShardRequest(_a0 *kinesis.SplitShardInput) (*service.Request, *kinesis.SplitShardOutput) {
	ret := m.Called(_a0)

	var r0 *service.Request
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*service.Request)
	}
	var r1 *kinesis.SplitShardOutput
	if ret.Get(1) != nil {
		r1 = ret.Get(1).(*kinesis.SplitShardOutput)
	}

	return r0, r1
}
func (m *Kinesis) SplitShard(_a0 *kinesis.SplitShardInput) (*kinesis.SplitShardOutput, error) {
	ret := m.Called(_a0)

	var r0 *kinesis.SplitShardOutput
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*kinesis.SplitShardOutput)
	}
	r1 := ret.Error(1)

	return r0, r1
}
<commit_msg>Formatting<commit_after>package mocks

import (
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/service"
	"github.com/aws/aws-sdk-go/service/kinesis"
	"github.com/stretchr/testify/mock"
)

type Kinesis struct {
	mock.Mock
}

func (m *Kinesis) AddTagsToStreamRequest(_a0 *kinesis.AddTagsToStreamInput) (*service.Request, *kinesis.AddTagsToStreamOutput) {
	ret := m.Called(_a0)

	var r0 *service.Request
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*service.Request)
	}
	var r1 *kinesis.AddTagsToStreamOutput
	if ret.Get(1) != nil {
		r1 = ret.Get(1).(*kinesis.AddTagsToStreamOutput)
	}

	return r0, r1
}
func (m *Kinesis) AddTagsToStream(_a0 *kinesis.AddTagsToStreamInput) (*kinesis.AddTagsToStreamOutput, error) {
	ret := m.Called(_a0)

	var r0 *kinesis.AddTagsToStreamOutput
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*kinesis.AddTagsToStreamOutput)
	}
	r1 := ret.Error(1)

	return r0, r1
}
func (m *Kinesis) CreateStreamRequest(_a0 *kinesis.CreateStreamInput) (*service.Request, *kinesis.CreateStreamOutput) {
	ret := m.Called(_a0)

	var r0 *service.Request
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*service.Request)
	}
	var r1 *kinesis.CreateStreamOutput
	if ret.Get(1) != nil {
		r1 = ret.Get(1).(*kinesis.CreateStreamOutput)
	}

	return r0, r1
}
func (m *Kinesis) CreateStream(_a0 *kinesis.CreateStreamInput) (*kinesis.CreateStreamOutput, error) {
	ret := m.Called(_a0)

	var r0 *kinesis.CreateStreamOutput
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*kinesis.CreateStreamOutput)
	}
	r1 := ret.Error(1)

	return r0, r1
}
func (m *Kinesis) DeleteStreamRequest(_a0 *kinesis.DeleteStreamInput) (*service.Request, *kinesis.DeleteStreamOutput) {
	ret := m.Called(_a0)

	var r0 *service.Request
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*service.Request)
	}
	var r1 *kinesis.DeleteStreamOutput
	if ret.Get(1) != nil {
		r1 = ret.Get(1).(*kinesis.DeleteStreamOutput)
	}

	return r0, r1
}
func (m *Kinesis) DeleteStream(_a0 *kinesis.DeleteStreamInput) (*kinesis.DeleteStreamOutput, error) {
	ret := m.Called(_a0)

	var r0 *kinesis.DeleteStreamOutput
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*kinesis.DeleteStreamOutput)
	}
	r1 := ret.Error(1)

	return r0, r1
}
func (m *Kinesis) DescribeStreamRequest(_a0 *kinesis.DescribeStreamInput) (*service.Request, *kinesis.DescribeStreamOutput) {
	ret := m.Called(_a0)

	var r0 *service.Request
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*service.Request)
	}
	var r1 *kinesis.DescribeStreamOutput
	if ret.Get(1) != nil {
		r1 = ret.Get(1).(*kinesis.DescribeStreamOutput)
	}

	return r0, r1
}
func (m *Kinesis) DescribeStream(_a0 *kinesis.DescribeStreamInput) (*kinesis.DescribeStreamOutput, error) {
	ret := m.Called(_a0)

	var r0 *kinesis.DescribeStreamOutput
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*kinesis.DescribeStreamOutput)
	}
	r1 := ret.Error(1)

	return r0, r1
}
func (m *Kinesis) DescribeStreamPages(_a0 *kinesis.DescribeStreamInput, _a1 func(*kinesis.DescribeStreamOutput, bool) bool) error {
	ret := m.Called(_a0, _a1)

	a := kinesis.Shard{
		AdjacentParentShardID: nil,
		HashKeyRange: &kinesis.HashKeyRange{
			StartingHashKey: aws.String("0"),
			EndingHashKey:   aws.String("7f"),
		},
		ParentShardID: nil,
		SequenceNumberRange: &kinesis.SequenceNumberRange{
			StartingSequenceNumber: aws.String("0"),
			EndingSequenceNumber:   aws.String("100"),
		},
		ShardID: aws.String("shard0"),
	}
	b := kinesis.Shard{
		AdjacentParentShardID: nil,
		HashKeyRange: &kinesis.HashKeyRange{
			StartingHashKey: aws.String("80"),
			EndingHashKey:   aws.String("ff"),
		},
		ParentShardID: nil,
		SequenceNumberRange: &kinesis.SequenceNumberRange{
			StartingSequenceNumber: aws.String("101"),
			EndingSequenceNumber:   aws.String("200"),
		},
		ShardID: aws.String("shard1"),
	}
	cont := _a1(
		&kinesis.DescribeStreamOutput{
			StreamDescription: &kinesis.StreamDescription{
				HasMoreShards: aws.Bool(true),
				Shards:        []*kinesis.Shard{&a},
				StreamName:    aws.String("TestStream"),
				StreamStatus:  aws.String("ACTIVE"),
			},
		}, true)
	if cont {
		_a1(
			&kinesis.DescribeStreamOutput{
				StreamDescription: &kinesis.StreamDescription{
					HasMoreShards: aws.Bool(true),
					Shards:        []*kinesis.Shard{&b},
					StreamName:    aws.String("TestStream"),
					StreamStatus:  aws.String("ACTIVE"),
				},
			}, false)
	}
	r0 := ret.Error(0)

	return r0
}
func (m *Kinesis) GetRecordsRequest(_a0 *kinesis.GetRecordsInput) (*service.Request, *kinesis.GetRecordsOutput) {
	ret := m.Called(_a0)

	var r0 *service.Request
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*service.Request)
	}
	var r1 *kinesis.GetRecordsOutput
	if ret.Get(1) != nil {
		r1 = ret.Get(1).(*kinesis.GetRecordsOutput)
	}

	return r0, r1
}
func (m *Kinesis) GetRecords(_a0 *kinesis.GetRecordsInput) (*kinesis.GetRecordsOutput, error) {
	ret := m.Called(_a0)

	var r0 *kinesis.GetRecordsOutput
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*kinesis.GetRecordsOutput)
	}
	r1 := ret.Error(1)

	return r0, r1
}
func (m *Kinesis) GetShardIteratorRequest(_a0 *kinesis.GetShardIteratorInput) (*service.Request, *kinesis.GetShardIteratorOutput) {
	ret := m.Called(_a0)

	var r0 *service.Request
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*service.Request)
	}
	var r1 *kinesis.GetShardIteratorOutput
	if ret.Get(1) != nil {
		r1 = ret.Get(1).(*kinesis.GetShardIteratorOutput)
	}

	return r0, r1
}
func (m *Kinesis) GetShardIterator(_a0 *kinesis.GetShardIteratorInput) (*kinesis.GetShardIteratorOutput, error) {
	ret := m.Called(_a0)

	var r0 *kinesis.GetShardIteratorOutput
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*kinesis.GetShardIteratorOutput)
	}
	r1 := ret.Error(1)

	return r0, r1
}
func (m *Kinesis) ListStreamsRequest(_a0 *kinesis.ListStreamsInput) (*service.Request, *kinesis.ListStreamsOutput) {
	ret := m.Called(_a0)

	var r0 *service.Request
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*service.Request)
	}
	var r1 *kinesis.ListStreamsOutput
	if ret.Get(1) != nil {
		r1 = ret.Get(1).(*kinesis.ListStreamsOutput)
	}

	return r0, r1
}
func (m *Kinesis) ListStreams(_a0 *kinesis.ListStreamsInput) (*kinesis.ListStreamsOutput, error) {
	ret := m.Called(_a0)

	var r0 *kinesis.ListStreamsOutput
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*kinesis.ListStreamsOutput)
	}
	r1 := ret.Error(1)

	return r0, r1
}
func (m *Kinesis) ListStreamsPages(_a0 *kinesis.ListStreamsInput, _a1 func(*kinesis.ListStreamsOutput, bool) bool) error {
	ret := m.Called(_a0, _a1)

	cont := _a1(&kinesis.ListStreamsOutput{
		HasMoreStreams: aws.Bool(true),
		StreamNames:    []*string{aws.String("a"), aws.String("b")},
	}, true)
	if cont {
		_a1(&kinesis.ListStreamsOutput{
			HasMoreStreams: aws.Bool(false),
			StreamNames:    []*string{aws.String("c")},
		}, false)
	}
	r0 := ret.Error(0)

	return r0
}
func (m *Kinesis) ListTagsForStreamRequest(_a0 *kinesis.ListTagsForStreamInput) (*service.Request, *kinesis.ListTagsForStreamOutput) {
	ret := m.Called(_a0)

	var r0 *service.Request
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*service.Request)
	}
	var r1 *kinesis.ListTagsForStreamOutput
	if ret.Get(1) != nil {
		r1 = ret.Get(1).(*kinesis.ListTagsForStreamOutput)
	}

	return r0, r1
}
func (m *Kinesis) ListTagsForStream(_a0 *kinesis.ListTagsForStreamInput) (*kinesis.ListTagsForStreamOutput, error) {
	ret := m.Called(_a0)

	var r0 *kinesis.ListTagsForStreamOutput
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*kinesis.ListTagsForStreamOutput)
	}
	r1 := ret.Error(1)

	return r0, r1
}
func (m *Kinesis) MergeShardsRequest(_a0 *kinesis.MergeShardsInput) (*service.Request, *kinesis.MergeShardsOutput) {
	ret := m.Called(_a0)

	var r0 *service.Request
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*service.Request)
	}
	var r1 *kinesis.MergeShardsOutput
	if ret.Get(1) != nil {
		r1 = ret.Get(1).(*kinesis.MergeShardsOutput)
	}

	return r0, r1
}
func (m *Kinesis) MergeShards(_a0 *kinesis.MergeShardsInput) (*kinesis.MergeShardsOutput, error) {
	ret := m.Called(_a0)

	var r0 *kinesis.MergeShardsOutput
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*kinesis.MergeShardsOutput)
	}
	r1 := ret.Error(1)

	return r0, r1
}
func (m *Kinesis) PutRecordRequest(_a0 *kinesis.PutRecordInput) (*service.Request, *kinesis.PutRecordOutput) {
	ret := m.Called(_a0)

	var r0 *service.Request
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*service.Request)
	}
	var r1 *kinesis.PutRecordOutput
	if ret.Get(1) != nil {
		r1 = ret.Get(1).(*kinesis.PutRecordOutput)
	}

	return r0, r1
}
func (m *Kinesis) PutRecord(_a0 *kinesis.PutRecordInput) (*kinesis.PutRecordOutput, error) {
	ret := m.Called(_a0)

	var r0 *kinesis.PutRecordOutput
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*kinesis.PutRecordOutput)
	}
	r1 := ret.Error(1)

	return r0, r1
}
func (m *Kinesis) PutRecordsRequest(_a0 *kinesis.PutRecordsInput) (*service.Request, *kinesis.PutRecordsOutput) {
	ret := m.Called(_a0)

	var r0 *service.Request
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*service.Request)
	}
	var r1 *kinesis.PutRecordsOutput
	if ret.Get(1) != nil {
		r1 = ret.Get(1).(*kinesis.PutRecordsOutput)
	}

	return r0, r1
}
func (m *Kinesis) PutRecords(_a0 *kinesis.PutRecordsInput) (*kinesis.PutRecordsOutput, error) {
	ret := m.Called(_a0)

	var r0 *kinesis.PutRecordsOutput
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*kinesis.PutRecordsOutput)
	}
	r1 := ret.Error(1)

	return r0, r1
}
func (m *Kinesis) RemoveTagsFromStreamRequest(_a0 *kinesis.RemoveTagsFromStreamInput) (*service.Request, *kinesis.RemoveTagsFromStreamOutput) {
	ret := m.Called(_a0)

	var r0 *service.Request
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*service.Request)
	}
	var r1 *kinesis.RemoveTagsFromStreamOutput
	if ret.Get(1) != nil {
		r1 = ret.Get(1).(*kinesis.RemoveTagsFromStreamOutput)
	}

	return r0, r1
}
func (m *Kinesis) RemoveTagsFromStream(_a0 *kinesis.RemoveTagsFromStreamInput) (*kinesis.RemoveTagsFromStreamOutput, error) {
	ret := m.Called(_a0)

	var r0 *kinesis.RemoveTagsFromStreamOutput
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*kinesis.RemoveTagsFromStreamOutput)
	}
	r1 := ret.Error(1)

	return r0, r1
}
func (m *Kinesis) SplitShardRequest(_a0 *kinesis.SplitShardInput) (*service.Request, *kinesis.SplitShardOutput) {
	ret := m.Called(_a0)

	var r0 *service.Request
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*service.Request)
	}
	var r1 *kinesis.SplitShardOutput
	if ret.Get(1) != nil {
		r1 = ret.Get(1).(*kinesis.SplitShardOutput)
	}

	return r0, r1
}
func (m *Kinesis) SplitShard(_a0 *kinesis.SplitShardInput) (*kinesis.SplitShardOutput, error) {
	ret := m.Called(_a0)

	var r0 *kinesis.SplitShardOutput
	if ret.Get(0) != nil {
		r0 = ret.Get(0).(*kinesis.SplitShardOutput)
	}
	r1 := ret.Error(1)

	return r0, r1
}
<|endoftext|>


<commit_before>package revok

import (
	"context"
	"cred-alert/db"
	"cred-alert/gitclient"
	"cred-alert/kolsch"
	"cred-alert/metrics"
	"encoding/json"
	"os"
	"time"

	git "github.com/libgit2/git2go"
	"github.com/tedsuo/ifrit"

	"code.cloudfoundry.org/clock"
	"code.cloudfoundry.org/lager"
)

type ChangeDiscoverer struct {
	logger               lager.Logger
	gitClient            gitclient.Client
	clock                clock.Clock
	interval             time.Duration
	scanner              Scanner
	repositoryRepository db.RepositoryRepository
	fetchRepository      db.FetchRepository

	fetchTimer             metrics.Timer
	fetchedRepositoryGauge metrics.Gauge
	runCounter             metrics.Counter
	fetchSuccessCounter    metrics.Counter
	fetchFailedCounter     metrics.Counter
	scanSuccessCounter     metrics.Counter
	scanFailedCounter      metrics.Counter
}

func NewChangeDiscoverer(
	logger lager.Logger,
	gitClient gitclient.Client,
	clock clock.Clock,
	interval time.Duration,
	scanner Scanner,
	repositoryRepository db.RepositoryRepository,
	fetchRepository db.FetchRepository,
	emitter metrics.Emitter,
) ifrit.Runner {
	return &ChangeDiscoverer{
		logger:               logger,
		gitClient:            gitClient,
		clock:                clock,
		interval:             interval,
		scanner:              scanner,
		repositoryRepository: repositoryRepository,
		fetchRepository:      fetchRepository,

		fetchTimer:             emitter.Timer("revok.change_discoverer.fetch_time"),
		fetchedRepositoryGauge: emitter.Gauge("revok.change_discoverer.repositories_to_fetch"),
		runCounter:             emitter.Counter("revok.change_discoverer.run"),
		fetchSuccessCounter:    emitter.Counter("revok.change_discoverer.fetch.success"),
		fetchFailedCounter:     emitter.Counter("revok.change_discoverer.fetch.failed"),
		scanSuccessCounter:     emitter.Counter("revok.change_discoverer.scan.success"),
		scanFailedCounter:      emitter.Counter("revok.change_discoverer.scan.failed"),
	}
}

func (c *ChangeDiscoverer) Run(signals <-chan os.Signal, ready chan<- struct{}) error {
	logger := c.logger.Session("change-discoverer")
	logger.Info("started")

	close(ready)

	timer := c.clock.NewTicker(c.interval)
	firstTickCh := c.clock.NewTimer(0).C()

	ctx, cancel := context.WithCancel(context.Background())

	for {
		select {
		case <-firstTickCh:
			firstTickCh = nil
			c.work(ctx, logger)
		case <-timer.C():
			c.work(ctx, logger)
		case <-signals:
			cancel()
			logger.Info("done")
			timer.Stop()
			return nil
		}
	}

	return nil
}

func (c *ChangeDiscoverer) work(ctx context.Context, logger lager.Logger) {
	c.runCounter.Inc(logger)

	repos, err := c.repositoryRepository.NotFetchedSince(c.clock.Now().Add(-c.interval))
	if err != nil {
		logger.Error("failed-getting-repos", err)
		return
	}

	c.fetchedRepositoryGauge.Update(logger, float32(len(repos)))

	if len(repos) == 0 {
		return
	}

	err = c.fetch(logger, repos[0])
	if err != nil {
		return
	}

	if len(repos) > 1 {
		repoFetchDelay := time.Duration(c.interval.Nanoseconds()/int64(len(repos))) * time.Nanosecond
		waitCh := c.clock.NewTicker(repoFetchDelay).C()
		errCh := make(chan error)

		for _, repo := range repos[1:] {
			<-waitCh

			go func() { errCh <- c.fetch(logger, repo) }()

			select {
			case <-errCh:
			case <-ctx.Done():
			}
		}
	}

	return
}

func (c *ChangeDiscoverer) fetch(
	logger lager.Logger,
	repo db.Repository,
) error {
	repoLogger := logger.WithData(lager.Data{
		"owner":      repo.Owner,
		"repository": repo.Name,
		"path":       repo.Path,
	})

	var changes map[string][]*git.Oid
	var fetchErr error
	c.fetchTimer.Time(repoLogger, func() {
		changes, fetchErr = c.gitClient.Fetch(repo.Path)
	})

	if fetchErr != nil {
		repoLogger.Error("failed-to-fetch", fetchErr)
		c.fetchFailedCounter.Inc(repoLogger)
		return fetchErr
	}

	c.fetchSuccessCounter.Inc(repoLogger)

	bs, err := json.Marshal(changes)
	if err != nil {
		repoLogger.Error("failed-to-marshal-json", err)
		return err
	}

	fetch := db.Fetch{
		Repository: repo,
		Path:       repo.Path,
		Changes:    bs,
	}

	err = c.fetchRepository.SaveFetch(repoLogger, &fetch)
	if err != nil {
		repoLogger.Error("failed-to-save-fetch", err)
		return err
	}

	quietLogger := kolsch.NewLogger()

	for _, oids := range changes {
		err := c.scanner.Scan(quietLogger, repo.Owner, repo.Name, oids[1].String(), oids[0].String())
		if err != nil {
			c.scanFailedCounter.Inc(repoLogger)
		} else {
			c.scanSuccessCounter.Inc(repoLogger)
		}
	}

	return nil
}
<commit_msg>Remove context.Context from ChangeDiscoverer<commit_after>package revok

import (
	"cred-alert/db"
	"cred-alert/gitclient"
	"cred-alert/kolsch"
	"cred-alert/metrics"
	"encoding/json"
	"os"
	"time"

	git "github.com/libgit2/git2go"
	"github.com/tedsuo/ifrit"

	"code.cloudfoundry.org/clock"
	"code.cloudfoundry.org/lager"
)

type ChangeDiscoverer struct {
	logger               lager.Logger
	gitClient            gitclient.Client
	clock                clock.Clock
	interval             time.Duration
	scanner              Scanner
	repositoryRepository db.RepositoryRepository
	fetchRepository      db.FetchRepository

	fetchTimer             metrics.Timer
	fetchedRepositoryGauge metrics.Gauge
	runCounter             metrics.Counter
	fetchSuccessCounter    metrics.Counter
	fetchFailedCounter     metrics.Counter
	scanSuccessCounter     metrics.Counter
	scanFailedCounter      metrics.Counter
}

func NewChangeDiscoverer(
	logger lager.Logger,
	gitClient gitclient.Client,
	clock clock.Clock,
	interval time.Duration,
	scanner Scanner,
	repositoryRepository db.RepositoryRepository,
	fetchRepository db.FetchRepository,
	emitter metrics.Emitter,
) ifrit.Runner {
	return &ChangeDiscoverer{
		logger:               logger,
		gitClient:            gitClient,
		clock:                clock,
		interval:             interval,
		scanner:              scanner,
		repositoryRepository: repositoryRepository,
		fetchRepository:      fetchRepository,

		fetchTimer:             emitter.Timer("revok.change_discoverer.fetch_time"),
		fetchedRepositoryGauge: emitter.Gauge("revok.change_discoverer.repositories_to_fetch"),
		runCounter:             emitter.Counter("revok.change_discoverer.run"),
		fetchSuccessCounter:    emitter.Counter("revok.change_discoverer.fetch.success"),
		fetchFailedCounter:     emitter.Counter("revok.change_discoverer.fetch.failed"),
		scanSuccessCounter:     emitter.Counter("revok.change_discoverer.scan.success"),
		scanFailedCounter:      emitter.Counter("revok.change_discoverer.scan.failed"),
	}
}

func (c *ChangeDiscoverer) Run(signals <-chan os.Signal, ready chan<- struct{}) error {
	logger := c.logger.Session("change-discoverer")
	logger.Info("started")

	close(ready)

	c.work(signals, logger)

	timer := c.clock.NewTicker(c.interval)

	for {
		select {
		case <-timer.C():
			c.work(signals, logger)
		case <-signals:
			logger.Info("done")
			timer.Stop()
			return nil
		}
	}

	return nil
}

func (c *ChangeDiscoverer) work(signals <-chan os.Signal, logger lager.Logger) {
	c.runCounter.Inc(logger)

	repos, err := c.repositoryRepository.NotFetchedSince(c.clock.Now().Add(-c.interval))
	if err != nil {
		logger.Error("failed-getting-repos", err)
		return
	}

	c.fetchedRepositoryGauge.Update(logger, float32(len(repos)))

	if len(repos) > 0 {
		repoFetchDelay := time.Duration(c.interval.Nanoseconds()/int64(len(repos))) * time.Nanosecond
		waitCh := c.clock.NewTicker(repoFetchDelay).C()

		for i := range repos {
			select {
			case <-signals:
				return
			default:
				c.fetch(logger, repos[i])
				if i < len(repos)-1 {
					<-waitCh
				}
			}
		}
	}
}

func (c *ChangeDiscoverer) fetch(
	logger lager.Logger,
	repo db.Repository,
) error {
	repoLogger := logger.WithData(lager.Data{
		"owner":      repo.Owner,
		"repository": repo.Name,
		"path":       repo.Path,
	})

	var changes map[string][]*git.Oid
	var fetchErr error
	c.fetchTimer.Time(repoLogger, func() {
		changes, fetchErr = c.gitClient.Fetch(repo.Path)
	})

	if fetchErr != nil {
		repoLogger.Error("failed-to-fetch", fetchErr)
		c.fetchFailedCounter.Inc(repoLogger)
		return fetchErr
	}

	c.fetchSuccessCounter.Inc(repoLogger)

	bs, err := json.Marshal(changes)
	if err != nil {
		repoLogger.Error("failed-to-marshal-json", err)
		return err
	}

	fetch := db.Fetch{
		Repository: repo,
		Path:       repo.Path,
		Changes:    bs,
	}

	err = c.fetchRepository.SaveFetch(repoLogger, &fetch)
	if err != nil {
		repoLogger.Error("failed-to-save-fetch", err)
		return err
	}

	quietLogger := kolsch.NewLogger()

	for _, oids := range changes {
		err := c.scanner.Scan(quietLogger, repo.Owner, repo.Name, oids[1].String(), oids[0].String())
		if err != nil {
			c.scanFailedCounter.Inc(repoLogger)
		} else {
			c.scanSuccessCounter.Inc(repoLogger)
		}
	}

	return nil
}
<|endoftext|>


<commit_before>package lzma

type readerDict struct {
	buffer
	bufferLen int
}

func newReaderDict(historyLen, bufferLen int) (rd *readerDict, err error) {
	if !(1 <= historyLen && int64(historyLen) < MaxDictLen) {
		return nil, newError("historyLen out of range")
	}
	if bufferLen <= 0 {
		return nil, newError("bufferLen must be greater than zero")
	}
	capacity := historyLen
	if bufferLen > capacity {
		capacity = bufferLen
	}
	rd = &readerDict{bufferLen: bufferLen}
	err = initBuffer(&rd.buffer, capacity)
	return
}

func (rd *readerDict) WriteRep(dist int64, n int) (written int, err error) {
	panic("TODO")
}

func (rd *readerDict) Offset() int64 {
	return rd.end
}

func (rd *readerDict) Byte(dist int) byte {
	panic("TODO")
}

type writerDict struct {
	buffer
}

func newWriterDict(historyLen, bufferLen int) (wd *writerDict, err error) {
	if !(1 <= historyLen && int64(historyLen) < MaxDictLen) {
		return nil, newError("historyLen out of range")
	}
	if bufferLen <= 0 {
		return nil, newError("bufferLen must be greater than zero")
	}
	capacity := historyLen + bufferLen
	wd = &writerDict{}
	err = initBuffer(&wd.buffer, capacity)
	if err != nil {
		return nil, err
	}
	wd.writeLimit = bufferLen
	return wd, nil
}

func (wd *writerDict) Byte(dist int) byte {
	panic("TODO")
}

func (wd *writerDict) Offset() int64 {
	return wd.cursor
}
<commit_msg>lzma: fully implemented readerDict<commit_after>package lzma

var (
	errDist = newError("distance out of range")
)

type readerDict struct {
	buffer
	bufferLen int
}

func newReaderDict(historyLen, bufferLen int) (rd *readerDict, err error) {
	if !(1 <= historyLen && int64(historyLen) < MaxDictLen) {
		return nil, newError("historyLen out of range")
	}
	if bufferLen <= 0 {
		return nil, newError("bufferLen must be greater than zero")
	}
	capacity := historyLen
	if bufferLen > capacity {
		capacity = bufferLen
	}
	rd = &readerDict{bufferLen: bufferLen}
	err = initBuffer(&rd.buffer, capacity)
	return
}

func (rd *readerDict) Offset() int64 {
	return rd.end
}

func (rd *readerDict) WriteRep(dist int64, n int) (written int, err error) {
	if !(1 <= dist && dist <= int64(rd.Len())) {
		return 0, errDist
	}
	return rd.WriteRepOff(n, rd.end-dist)
}

func (rd *readerDict) Byte(dist int) byte {
	c, _ := rd.ReadByteAt(rd.end - int64(dist))
	return c
}

type writerDict struct {
	buffer
}

func newWriterDict(historyLen, bufferLen int) (wd *writerDict, err error) {
	if !(1 <= historyLen && int64(historyLen) < MaxDictLen) {
		return nil, newError("historyLen out of range")
	}
	if bufferLen <= 0 {
		return nil, newError("bufferLen must be greater than zero")
	}
	capacity := historyLen + bufferLen
	wd = &writerDict{}
	err = initBuffer(&wd.buffer, capacity)
	if err != nil {
		return nil, err
	}
	wd.writeLimit = bufferLen
	return wd, nil
}

func (wd *writerDict) Byte(dist int) byte {
	panic("TODO")
}

func (wd *writerDict) Offset() int64 {
	return wd.cursor
}
<|endoftext|>


<commit_before>// +build e2e

/*
Copyright 2019 The Knative Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package e2e

import (
	"testing"

	apierrs "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/wait"
	"knative.dev/pkg/test/logstream"
	"knative.dev/serving-operator/test"
	"knative.dev/serving-operator/test/resources"
)

// TestKnativeServingDeployment verifies the KnativeServing creation, deployment recreation, and KnativeServing deletion.
func TestKnativeServingDeployment(t *testing.T) {
	cancel := logstream.Start(t)
	defer cancel()
	clients := Setup(t)

	names := test.ResourceNames{
		KnativeServing: test.ServingOperatorName,
		Namespace:      test.ServingOperatorNamespace,
	}

	test.CleanupOnInterrupt(func() { test.TearDown(clients, names) })
	defer test.TearDown(clients, names)

	// Create a KnativeServing
	if _, err := resources.CreateKnativeServing(clients.KnativeServingAlphaClient, names); err != nil {
		t.Fatalf("KnativeService %q failed to create: %v", names.KnativeServing, err)
	}

	// Test if KnativeServing can reach the READY status
	t.Run("create", func(t *testing.T) {
		knativeServingVerify(t, clients, names)
	})

	// Delete the deployments one by one to see if they will be recreated.
	t.Run("restore", func(t *testing.T) {
		knativeServingVerify(t, clients, names)
		deploymentRecreation(t, clients, names)
	})

	// Delete the KnativeServing to see if all the deployments will be removed as well
	t.Run("delete", func(t *testing.T) {
		knativeServingVerify(t, clients, names)
		knativeServingDeletion(t, clients, names)
	})
}

// knativeServingVerify verifies if the KnativeServing can reach the READY status.
func knativeServingVerify(t *testing.T, clients *test.Clients, names test.ResourceNames) {
	if _, err := resources.WaitForKnativeServingState(clients.KnativeServingAlphaClient, names.KnativeServing,
		resources.IsKnativeServingReady); err != nil {
		t.Fatalf("KnativeService %q failed to get to the READY status: %v", names.KnativeServing, err)
	}

}

// deploymentRecreation verify whether all the deployments for knative serving are able to recreate, when they are deleted.
func deploymentRecreation(t *testing.T, clients *test.Clients, names test.ResourceNames) {
	dpList, err := clients.KubeClient.Kube.AppsV1().Deployments(names.Namespace).List(metav1.ListOptions{})
	if err != nil {
		t.Fatalf("Failed to get any deployment under the namespace %q: %v",
			test.ServingOperatorNamespace, err)
	}
	if len(dpList.Items) == 0 {
		t.Fatalf("No deployment under the namespace %q was found",
			test.ServingOperatorNamespace)
	}
	// Delete the deployments one by one to see if they will be recreated.
	for _, deployment := range dpList.Items {
		if err := clients.KubeClient.Kube.AppsV1().Deployments(deployment.Namespace).Delete(deployment.Name,
			&metav1.DeleteOptions{}); err != nil {
			t.Fatalf("Failed to delete deployment %s/%s: %v", deployment.Namespace, deployment.Name, err)
		}

		waitErr := wait.PollImmediate(resources.Interval, resources.Timeout, func() (bool, error) {
			dep, err := clients.KubeClient.Kube.AppsV1().Deployments(deployment.Namespace).Get(deployment.Name, metav1.GetOptions{})
			if err != nil {
				// If the deployment is not found, we continue to wait for the availability.
				if apierrs.IsNotFound(err) {
					return false, nil
				}
				return false, err
			}
			return resources.IsDeploymentAvailable(dep)
		})

		if waitErr != nil {
			t.Fatalf("The deployment %s/%s failed to reach the desired state: %v", deployment.Namespace, deployment.Name, err)
		}

		if _, err := resources.WaitForKnativeServingState(clients.KnativeServingAlphaClient, test.ServingOperatorName,
			resources.IsKnativeServingReady); err != nil {
			t.Fatalf("KnativeService %q failed to reach the desired state: %v", test.ServingOperatorName, err)
		}
		t.Logf("The deployment %s/%s reached the desired state.", deployment.Namespace, deployment.Name)
	}
}

// knativeServingDeletion deletes tha KnativeServing to see if all the deployments will be removed.
func knativeServingDeletion(t *testing.T, clients *test.Clients, names test.ResourceNames) {
	if err := clients.KnativeServingAlphaClient.Delete(names.KnativeServing, &metav1.DeleteOptions{}); err != nil {
		t.Fatalf("KnativeService %q failed to delete: %v", names.KnativeServing, err)
	}

	dpList, err := clients.KubeClient.Kube.AppsV1().Deployments(names.Namespace).List(metav1.ListOptions{})
	if err != nil {
		t.Fatalf("Error getting any deployment under the namespace %q: %v", names.Namespace, err)
	}

	for _, deployment := range dpList.Items {
		waitErr := wait.PollImmediate(resources.Interval, resources.Timeout, func() (bool, error) {
			_, err := clients.KubeClient.Kube.AppsV1().Deployments(deployment.Namespace).Get(deployment.Name, metav1.GetOptions{})
			if err != nil {
				if apierrs.IsNotFound(err) {
					return true, nil
				}
				return false, err
			}
			return false, nil
		})

		if waitErr != nil {
			t.Fatalf("The deployment %s/%s failed to be deleted: %v", deployment.Namespace, deployment.Name, err)
		}
		t.Logf("The deployment %s/%s has been deleted.", deployment.Namespace, deployment.Name)
	}
}
<commit_msg>Speed up the tests by only deleting one deployment (#137)<commit_after>// +build e2e

/*
Copyright 2019 The Knative Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package e2e

import (
	"testing"

	apierrs "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/wait"
	"knative.dev/pkg/test/logstream"
	"knative.dev/serving-operator/test"
	"knative.dev/serving-operator/test/resources"
)

// TestKnativeServingDeployment verifies the KnativeServing creation, deployment recreation, and KnativeServing deletion.
func TestKnativeServingDeployment(t *testing.T) {
	cancel := logstream.Start(t)
	defer cancel()
	clients := Setup(t)

	names := test.ResourceNames{
		KnativeServing: test.ServingOperatorName,
		Namespace:      test.ServingOperatorNamespace,
	}

	test.CleanupOnInterrupt(func() { test.TearDown(clients, names) })
	defer test.TearDown(clients, names)

	// Create a KnativeServing
	if _, err := resources.CreateKnativeServing(clients.KnativeServingAlphaClient, names); err != nil {
		t.Fatalf("KnativeService %q failed to create: %v", names.KnativeServing, err)
	}

	// Test if KnativeServing can reach the READY status
	t.Run("create", func(t *testing.T) {
		knativeServingVerify(t, clients, names)
	})

	// Delete the deployments one by one to see if they will be recreated.
	t.Run("restore", func(t *testing.T) {
		knativeServingVerify(t, clients, names)
		deploymentRecreation(t, clients, names)
	})

	// Delete the KnativeServing to see if all the deployments will be removed as well
	t.Run("delete", func(t *testing.T) {
		knativeServingVerify(t, clients, names)
		knativeServingDeletion(t, clients, names)
	})
}

// knativeServingVerify verifies if the KnativeServing can reach the READY status.
func knativeServingVerify(t *testing.T, clients *test.Clients, names test.ResourceNames) {
	if _, err := resources.WaitForKnativeServingState(clients.KnativeServingAlphaClient, names.KnativeServing,
		resources.IsKnativeServingReady); err != nil {
		t.Fatalf("KnativeService %q failed to get to the READY status: %v", names.KnativeServing, err)
	}

}

// deploymentRecreation verify whether all the deployments for knative serving are able to recreate, when they are deleted.
func deploymentRecreation(t *testing.T, clients *test.Clients, names test.ResourceNames) {
	dpList, err := clients.KubeClient.Kube.AppsV1().Deployments(names.Namespace).List(metav1.ListOptions{})
	if err != nil {
		t.Fatalf("Failed to get any deployment under the namespace %q: %v",
			test.ServingOperatorNamespace, err)
	}
	if len(dpList.Items) == 0 {
		t.Fatalf("No deployment under the namespace %q was found",
			test.ServingOperatorNamespace)
	}
	// Delete the first deployment and verify the operator recreates it
	deployment := dpList.Items[0]
	if err := clients.KubeClient.Kube.AppsV1().Deployments(deployment.Namespace).Delete(deployment.Name,
		&metav1.DeleteOptions{}); err != nil {
		t.Fatalf("Failed to delete deployment %s/%s: %v", deployment.Namespace, deployment.Name, err)
	}

	waitErr := wait.PollImmediate(resources.Interval, resources.Timeout, func() (bool, error) {
		dep, err := clients.KubeClient.Kube.AppsV1().Deployments(deployment.Namespace).Get(deployment.Name, metav1.GetOptions{})
		if err != nil {
			// If the deployment is not found, we continue to wait for the availability.
			if apierrs.IsNotFound(err) {
				return false, nil
			}
			return false, err
		}
		return resources.IsDeploymentAvailable(dep)
	})

	if waitErr != nil {
		t.Fatalf("The deployment %s/%s failed to reach the desired state: %v", deployment.Namespace, deployment.Name, err)
	}

	if _, err := resources.WaitForKnativeServingState(clients.KnativeServingAlphaClient, test.ServingOperatorName,
		resources.IsKnativeServingReady); err != nil {
		t.Fatalf("KnativeService %q failed to reach the desired state: %v", test.ServingOperatorName, err)
	}
	t.Logf("The deployment %s/%s reached the desired state.", deployment.Namespace, deployment.Name)
}

// knativeServingDeletion deletes tha KnativeServing to see if all the deployments will be removed.
func knativeServingDeletion(t *testing.T, clients *test.Clients, names test.ResourceNames) {
	if err := clients.KnativeServingAlphaClient.Delete(names.KnativeServing, &metav1.DeleteOptions{}); err != nil {
		t.Fatalf("KnativeService %q failed to delete: %v", names.KnativeServing, err)
	}

	dpList, err := clients.KubeClient.Kube.AppsV1().Deployments(names.Namespace).List(metav1.ListOptions{})
	if err != nil {
		t.Fatalf("Error getting any deployment under the namespace %q: %v", names.Namespace, err)
	}

	for _, deployment := range dpList.Items {
		waitErr := wait.PollImmediate(resources.Interval, resources.Timeout, func() (bool, error) {
			_, err := clients.KubeClient.Kube.AppsV1().Deployments(deployment.Namespace).Get(deployment.Name, metav1.GetOptions{})
			if err != nil {
				if apierrs.IsNotFound(err) {
					return true, nil
				}
				return false, err
			}
			return false, nil
		})

		if waitErr != nil {
			t.Fatalf("The deployment %s/%s failed to be deleted: %v", deployment.Namespace, deployment.Name, err)
		}
		t.Logf("The deployment %s/%s has been deleted.", deployment.Namespace, deployment.Name)
	}
}
<|endoftext|>


<commit_before>package main
<commit_msg>context: add main and gen func<commit_after>package main

import (
	"context"
	"fmt"
)

func main() {

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	for n := range gen(ctx) {
		fmt.Println(n)
		if n == 5 {
			cancel()
			break
		}
	}
}

func gen(ctx context.Context) <-chan int {

	ch := make(chan int)

	go func() {

		var n int

		for {
			select {
			case <-ctx.Done():
				return
			case ch <- n:
				n++
			}
		}
	}()
	return ch
}
<|endoftext|>


<commit_before>package cli

import (
	"reflect"
	"testing"
)

func makeCtx() *Context {
	return &Context{
		Arguments: make(map[string][]string, 0),
		Options:   make(map[string][]string),
	}
}

type ArgumentParseTest struct {
	name       string
	input      string
	values     []string
	shouldFail bool
}

func argumentTest(t *testing.T, flagMgr *FlagMgr, steps []ArgumentParseTest, ctx *Context) {
	for _, step := range steps {
		err := ctx.parseArgument(flagMgr, step.input)

		if step.shouldFail && err == nil {
			t.Errorf("Test should fail for `%s`", step.input)
		}

		if !step.shouldFail && err != nil {
			t.Errorf("Got error: `%s` for input `%s`", err, step.input)
		}

		if step.shouldFail {
			continue
		}

		if _, ok := ctx.Arguments[step.name]; !ok {
			t.Errorf("Argument `%s` not found!", step.name)
		}

		if !reflect.DeepEqual(step.values, ctx.Arguments[step.name]) {
			t.Errorf("Expected values [%s] but got [%s]", step.values, ctx.Arguments[step.name])
		}
		ctx.cursor++
	}
}

func longOptionTest(t *testing.T, flagMgr *FlagMgr, steps []ArgumentParseTest, ctx *Context) {
	for _, step := range steps {
		err := ctx.parseLongOption(flagMgr, step.input)

		if step.shouldFail && err == nil {
			t.Errorf("Test should fail for `%s`", step.input)
		}

		if !step.shouldFail && err != nil {
			t.Errorf("Got error: `%s` for input `%s`", err, step.input)
		}

		if step.shouldFail {
			continue
		}

		if _, ok := ctx.Options[step.name]; !ok {
			t.Errorf("Option `%s` not found!", step.name)
		}

		if !reflect.DeepEqual(step.values, ctx.Options[step.name]) && len(step.values) > 0 && len(ctx.Options[step.name]) > 0 {
			t.Errorf("Expected values [%s] but got [%s]", step.values, ctx.Options[step.name])
		}
		ctx.cursor++
	}
}

func TestParseArgument(t *testing.T) {
	flags := []*Flag{
		&Flag{
			name:    "foo",
			kind:    argumentFlag,
			options: required,
		},
		&Flag{
			name:    "bar",
			kind:    argumentFlag,
			options: required,
		},
	}
	flagMgr := newFlagMgr(flags)

	ctx := makeCtx()
	ctx.cursor = 0

	steps := []ArgumentParseTest{
		ArgumentParseTest{
			name:       "foo",
			input:      "val1",
			values:     []string{"val1"},
			shouldFail: false,
		},
		ArgumentParseTest{
			name:       "bar",
			input:      "val2",
			values:     []string{"val2"},
			shouldFail: false,
		},
		ArgumentParseTest{
			name:       "fuu",
			input:      "val1",
			values:     []string{"val1"},
			shouldFail: true,
		},
	}

	argumentTest(t, flagMgr, steps, ctx)
}

func TestParseArgumentArray(t *testing.T) {
	flags := []*Flag{
		&Flag{
			name:    "foo",
			kind:    argumentFlag,
			options: required,
		},
		&Flag{
			name:    "bar",
			kind:    argumentFlag,
			options: required | isArray,
		},
	}
	flagMgr := newFlagMgr(flags)

	ctx := makeCtx()
	ctx.cursor = 0

	steps := []ArgumentParseTest{
		ArgumentParseTest{
			name:       "foo",
			input:      "val1",
			values:     []string{"val1"},
			shouldFail: false,
		},
		ArgumentParseTest{
			name:       "bar",
			input:      "val2",
			values:     []string{"val2"},
			shouldFail: false,
		},
		ArgumentParseTest{
			name:       "bar",
			input:      "val3",
			values:     []string{"val2", "val3"},
			shouldFail: false,
		},
	}

	argumentTest(t, flagMgr, steps, ctx)
}

func TestParseArgumentWithMissingArguments(t *testing.T) {
	flags := []*Flag{
		&Flag{
			name:    "foo",
			kind:    argumentFlag,
			options: required,
		},
		&Flag{
			name:    "bar",
			kind:    argumentFlag,
			options: required,
		},
	}
	flagMgr := newFlagMgr(flags)

	ctx := makeCtx()
	ctx.cursor = 0
	err := ctx.parse([]string{}, flagMgr)

	if err == nil || err.Error() != "Not enough arguments (missing: `foo`)." {
		t.Errorf("Parse with 1 missing argument failed with wrong error: %s", err)
	}
}

func TestParseLongOption(t *testing.T) {
	flags := []*Flag{
		&Flag{
			name:    "file",
			kind:    longOptionFlag,
			options: valueRequired,
		},
		&Flag{
			name:    "use-something",
			kind:    longOptionFlag,
			options: valueNone,
		},
		&Flag{
			name:    "output",
			kind:    longOptionFlag,
			options: valueOptional,
		},
	}
	flagMgr := newFlagMgr(flags)

	ctx := makeCtx()
	ctx.cursor = 0
	ctx.args = []string{"--file", "test.txt", "--use-something", "--output=file.out"}

	steps := []ArgumentParseTest{
		ArgumentParseTest{
			name:       "file",
			input:      "--file",
			values:     []string{"test.txt"},
			shouldFail: false,
		},
		ArgumentParseTest{
			name:       "use-something",
			input:      "--use-something",
			values:     []string{},
			shouldFail: false,
		},
		ArgumentParseTest{
			name:       "output",
			input:      "--output=file.out",
			values:     []string{"file.out"},
			shouldFail: false,
		},
	}

	longOptionTest(t, flagMgr, steps, ctx)
}

func TestParseLongOptionWithDefaultValue(t *testing.T) {
	flags := []*Flag{
		&Flag{
			name:    "file",
			kind:    longOptionFlag,
			options: valueOptional,
			value:   "default",
		},
	}
	flagMgr := newFlagMgr(flags)

	ctx := makeCtx()
	ctx.cursor = 0
	ctx.args = []string{"--file"}

	steps := []ArgumentParseTest{
		ArgumentParseTest{
			name:       "file",
			input:      "--file",
			values:     []string{"default"},
			shouldFail: false,
		},
	}

	longOptionTest(t, flagMgr, steps, ctx)
}
<commit_msg>More basic tests<commit_after>package cli

import (
	"reflect"
	"testing"
)

func makeCtx() *Context {
	return &Context{
		Arguments: make(map[string][]string, 0),
		Options:   make(map[string][]string),
	}
}

type ArgumentParseTest struct {
	name       string
	input      string
	values     []string
	shouldFail bool
}

func argumentTest(t *testing.T, flagMgr *FlagMgr, steps []ArgumentParseTest, ctx *Context) {
	for _, step := range steps {
		err := ctx.parseArgument(flagMgr, step.input)

		if step.shouldFail && err == nil {
			t.Errorf("Test should fail for `%s`", step.input)
		}

		if !step.shouldFail && err != nil {
			t.Errorf("Got error: `%s` for input `%s`", err, step.input)
		}

		if step.shouldFail {
			continue
		}

		if _, ok := ctx.Arguments[step.name]; !ok {
			t.Errorf("Argument `%s` not found!", step.name)
		}

		if !reflect.DeepEqual(step.values, ctx.Arguments[step.name]) {
			t.Errorf("Expected values [%s] but got [%s]", step.values, ctx.Arguments[step.name])
		}
		ctx.cursor++
	}
}

func longOptionTest(t *testing.T, flagMgr *FlagMgr, steps []ArgumentParseTest, ctx *Context) {
	for _, step := range steps {
		err := ctx.parseLongOption(flagMgr, step.input)

		if step.shouldFail && err == nil {
			t.Errorf("Test should fail for `%s`", step.input)
		}

		if !step.shouldFail && err != nil {
			t.Errorf("Got error: `%s` for input `%s`", err, step.input)
		}

		if step.shouldFail {
			continue
		}

		if _, ok := ctx.Options[step.name]; !ok {
			t.Errorf("Option `%s` not found!", step.name)
		}

		if !reflect.DeepEqual(step.values, ctx.Options[step.name]) && len(step.values) > 0 && len(ctx.Options[step.name]) > 0 {
			t.Errorf("Expected values [%s] but got [%s]", step.values, ctx.Options[step.name])
		}
		ctx.cursor++
	}
}

func TestParseArgument(t *testing.T) {
	flags := []*Flag{
		&Flag{
			name:    "foo",
			kind:    argumentFlag,
			options: required,
		},
		&Flag{
			name:    "bar",
			kind:    argumentFlag,
			options: required,
		},
	}
	flagMgr := newFlagMgr(flags)

	ctx := makeCtx()
	ctx.cursor = 0

	steps := []ArgumentParseTest{
		ArgumentParseTest{
			name:       "foo",
			input:      "val1",
			values:     []string{"val1"},
			shouldFail: false,
		},
		ArgumentParseTest{
			name:       "bar",
			input:      "val2",
			values:     []string{"val2"},
			shouldFail: false,
		},
		ArgumentParseTest{
			name:       "fuu",
			input:      "val1",
			values:     []string{"val1"},
			shouldFail: true,
		},
	}

	argumentTest(t, flagMgr, steps, ctx)
}

func TestParseArgumentArray(t *testing.T) {
	flags := []*Flag{
		&Flag{
			name:    "foo",
			kind:    argumentFlag,
			options: required,
		},
		&Flag{
			name:    "bar",
			kind:    argumentFlag,
			options: required | isArray,
		},
	}
	flagMgr := newFlagMgr(flags)

	ctx := makeCtx()
	ctx.cursor = 0

	steps := []ArgumentParseTest{
		ArgumentParseTest{
			name:       "foo",
			input:      "val1",
			values:     []string{"val1"},
			shouldFail: false,
		},
		ArgumentParseTest{
			name:       "bar",
			input:      "val2",
			values:     []string{"val2"},
			shouldFail: false,
		},
		ArgumentParseTest{
			name:       "bar",
			input:      "val3",
			values:     []string{"val2", "val3"},
			shouldFail: false,
		},
	}

	argumentTest(t, flagMgr, steps, ctx)
}

func TestParseArgumentWithMissingArguments(t *testing.T) {
	flags := []*Flag{
		&Flag{
			name:    "foo",
			kind:    argumentFlag,
			options: required,
		},
		&Flag{
			name:    "bar",
			kind:    argumentFlag,
			options: required,
		},
	}
	flagMgr := newFlagMgr(flags)

	ctx := makeCtx()
	ctx.cursor = 0
	err := ctx.parse([]string{}, flagMgr)

	if err == nil || err.Error() != "Not enough arguments (missing: `foo`)." {
		t.Errorf("Parse with 1 missing argument failed with wrong error: %s", err)
	}
}

func TestParseLongOption(t *testing.T) {
	flags := []*Flag{
		&Flag{
			name:    "file",
			kind:    longOptionFlag,
			options: valueRequired,
		},
		&Flag{
			name:    "use-something",
			kind:    longOptionFlag,
			options: valueNone,
		},
		&Flag{
			name:    "output",
			kind:    longOptionFlag,
			options: valueOptional,
		},
	}
	flagMgr := newFlagMgr(flags)

	ctx := makeCtx()
	ctx.cursor = 0
	ctx.args = []string{"--file", "test.txt", "--use-something", "--output=file.out"}

	steps := []ArgumentParseTest{
		ArgumentParseTest{
			name:       "file",
			input:      "--file",
			values:     []string{"test.txt"},
			shouldFail: false,
		},
		ArgumentParseTest{
			name:       "use-something",
			input:      "--use-something",
			values:     []string{},
			shouldFail: false,
		},
		ArgumentParseTest{
			name:       "output",
			input:      "--output=file.out",
			values:     []string{"file.out"},
			shouldFail: false,
		},
	}

	longOptionTest(t, flagMgr, steps, ctx)
}

func TestParseLongOptionWithDefaultValue(t *testing.T) {
	flags := []*Flag{
		&Flag{
			name:    "file",
			kind:    longOptionFlag,
			options: valueOptional,
			value:   "default",
		},
	}
	flagMgr := newFlagMgr(flags)

	ctx := makeCtx()
	ctx.cursor = 0
	ctx.args = []string{"--file"}

	steps := []ArgumentParseTest{
		ArgumentParseTest{
			name:       "file",
			input:      "--file",
			values:     []string{"default"},
			shouldFail: false,
		},
	}

	longOptionTest(t, flagMgr, steps, ctx)
}

func TestParseOptionWithMissingValue(t *testing.T) {
	flags := []*Flag{
		&Flag{
			name:    "foo",
			kind:    longOptionFlag,
			options: valueRequired,
		},
	}
	flagMgr := newFlagMgr(flags)

	ctx := makeCtx()
	ctx.cursor = 0
	err := ctx.parse([]string{"--foo"}, flagMgr)

	if err == nil || err.Error() != "The `--foo` option requres a value!" {
		t.Errorf("Parse with missing option value failed with wrong error: %s", err)
	}
}

func TestParseOptionInvalidOptionProvided(t *testing.T) {
	flags := []*Flag{
		&Flag{
			name:    "foo",
			kind:    longOptionFlag,
			options: valueOptional,
		},
	}
	flagMgr := newFlagMgr(flags)

	ctx := makeCtx()
	ctx.cursor = 0
	err := ctx.parse([]string{"--boo"}, flagMgr)

	if err == nil || err.Error() != "The `--boo` option does not exist." {
		t.Errorf("Parse with invalid option failed with wrong error: %s", err)
	}
}

func TestParseOptionWithNoWantedValue(t *testing.T) {
	flags := []*Flag{
		&Flag{
			name:    "foo",
			kind:    longOptionFlag,
			options: valueNone,
		},
	}
	flagMgr := newFlagMgr(flags)

	ctx := makeCtx()
	ctx.cursor = 0
	err := ctx.parse([]string{"--foo=\"bar\""}, flagMgr)

	if err == nil || err.Error() != "The `--foo` option does not accept a value!" {
		t.Errorf("Parse with invalid option failed with wrong error: %s", err)
	}
}
<|endoftext|>