<commit_before>//
// Last.Backend LLC CONFIDENTIAL
// __________________
//
// [2014] - [2017] Last.Backend LLC
// All Rights Reserved.
//
// NOTICE:  All information contained herein is, and remains
// the property of Last.Backend LLC and its suppliers,
// if any.  The intellectual and technical concepts contained
// herein are proprietary to Last.Backend LLC
// and its suppliers and may be covered by Russian Federation and Foreign Patents,
// patents in process, and are protected by trade secret or copyright law.
// Dissemination of this information or reproduction of this material
// is strictly forbidden unless prior written permission is obtained
// from Last.Backend LLC.
//

package service

import (
	"context"
	"encoding/json"
	"github.com/lastbackend/lastbackend/pkg/apis/types"
	ctx "github.com/lastbackend/lastbackend/pkg/daemon/context"
	"github.com/lastbackend/lastbackend/pkg/daemon/node"
	"github.com/lastbackend/lastbackend/pkg/daemon/service/routes/request"
	"github.com/lastbackend/lastbackend/pkg/util/validator"
	"github.com/pkg/errors"
	"github.com/satori/go.uuid"
	"reflect"
	"strconv"
	"time"
	"strings"
)

type service struct {
	Context   context.Context
	Namespace types.Meta
}

func New(ctx context.Context, namespace types.Meta) *service {
	return &service{
		Context:   ctx,
		Namespace: namespace,
	}
}

func (s *service) List() (*types.ServiceList, error) {
	var storage = ctx.Get().GetStorage()
	return storage.Service().ListByNamespace(s.Context, s.Namespace.ID)
}

func (s *service) Get(service string) (*types.Service, error) {

	var (
		err     error
		log     = ctx.Get().GetLogger()
		storage = ctx.Get().GetStorage()
		svc     *types.Service
	)

	if validator.IsUUID(service) {
		svc, err = storage.Service().GetByID(s.Context, s.Namespace.ID, service)
	} else {
		svc, err = storage.Service().GetByName(s.Context, s.Namespace.ID, service)
	}

	if err != nil {
		log.Error("Error: find service by name", err.Error())
		return svc, err
	}

	return svc, nil
}

func (s *service) Create(rq *request.RequestServiceCreateS) (*types.Service, error) {

	var (
		log     = ctx.Get().GetLogger()
		storage = ctx.Get().GetStorage()
		svc     = new(types.Service)
	)

	log.Debug("Service: create new service")

	svc.Meta = types.ServiceMeta{}
	svc.Meta.ID = uuid.NewV4().String()
	svc.Meta.Name = rq.Name
	svc.Meta.Region = rq.Region
	svc.Meta.Namespace = s.Namespace.Name
	svc.Meta.Description = rq.Description
	svc.Meta.Updated = time.Now()
	svc.Meta.Created = time.Now()

	config, err := createConfig(rq.Config)
	if err != nil {
		log.Errorf("Error: create config from request opts : %s", err.Error())
		return svc, err
	}

	svc.Config = *config

	log.Debugf("Service: Create: add pods : %d", svc.Config.Replicas)
	for i := 0; i < svc.Config.Replicas; i++ {
		log.Debug("Service: Create: add new pod")
		if err := s.AddPod(svc); err != nil {
			log.Errorf("Service: Create: add new pod error: %s", err.Error())
			return svc, err
		}
	}

	svc, err = storage.Service().Insert(s.Context, svc)
	if err != nil {
		log.Errorf("Error: insert service to db : %s", err.Error())
		return svc, err
	}

	return svc, nil
}

func (s *service) Update(service *types.Service, rq *request.RequestServiceUpdateS) (*types.Service, error) {

	var (
		err     error
		log     = ctx.Get().GetLogger()
		storage = ctx.Get().GetStorage()
		svc     *types.Service
	)

	log.Debug("Service: update service info and config")

	if rq.Name != "" {
		service.Meta.Name = rq.Name
	}

	if rq.Description != "" {
		service.Meta.Description = rq.Description
	}

	if rq.Domains != nil {
		service.Domains = rq.Domains
	}

	if err := updateConfig(rq.Config, &service.Config); err != nil {
		log.Error("Error: update service config from request opts", err)
		return svc, err
	}

	// Update pod spec
	spec := s.GenerateSpec(service)

	log.Debugf("Service: Update: pods count: %d", len(service.Pods))
	for _, pod := range service.Pods {
		log.Debugf("Service: Update: pod %s update", pod.Meta.ID)
		pod.Spec = spec
	}

	svc, err = storage.Service().Update(s.Context, service)
	if err != nil {
		log.Error("Error: insert service to db", err)
		return svc, err
	}

	return svc, nil
}

func (s *service) Remove(service *types.Service) error {
	var (
		log     = ctx.Get().GetLogger()
		storage = ctx.Get().GetStorage()
	)

	if err := storage.Service().Remove(s.Context, service); err != nil {
		log.Error("Error: insert service to db", err)
		return err
	}
	return nil
}

func (s *service) AddPod(service *types.Service) error {

	var (
		log = ctx.Get().GetLogger()
	)

	log.Debug("Create new pod state on service")

	pod := new(types.Pod)
	pod.State.State = "running"
	pod.Meta.ID = uuid.NewV4().String()
	pod.Meta.Created = time.Now()
	pod.Meta.Updated = time.Now()
	pod.Spec = s.GenerateSpec(service)

	n, err := node.New().Allocate(s.Context, pod.Spec)
	if err != nil {
		return err
	}

	log.Debugf("Service: Add pod: Node meta: %s", n.Meta)
	pod.Meta.Hostname = n.Meta.Hostname

	service.Pods = append(service.Pods, pod)

	return nil
}

func (s *service) DelPod(service *types.Service) error {

	var (
		log = ctx.Get().GetLogger()
		pod *types.Pod
	)

	log.Debug("Create new pod state on service")

	for i := len(service.Pods); i >= 0; i-- {
		pod = service.Pods[i-1]
		if pod.State.State != "deleting" {
			break
		}
	}

	pod.State.State = "deleting"
	return nil
}

func (s *service) SetPods(c context.Context, pods []types.PodNodeState) error {
	var (
		log     = ctx.Get().GetLogger()
		storage = ctx.Get().GetStorage()
	)

	for _, pod := range pods {
		svc, err := storage.Service().GetByPodID(c, pod.Meta.ID)
		if err != nil {
			log.Errorf("Error: get pod from db: %s", err)
			return err
		}

		if svc == nil {
			continue
		}

		if p, e := storage.Pod().GetByID(c, svc.Meta.Namespace, svc.Meta.ID, pod.Meta.ID); p == nil || e != nil {

			if err != nil {
				log.Errorf("Error: get pod from db: %s", err)
				return err
			}

			if p == nil {
				log.Warnf("Pod not found, skip setting: %s", pod.Meta.ID)
			}

		}

		if err := storage.Pod().Update(c, svc.Meta.Namespace, svc.Meta.ID, &pod); err != nil {
			log.Errorf("Error: set pod to db: %s", err)
			return err
		}
	}

	return nil
}

func (s *service) Scale(c context.Context, service *types.Service) (*types.Service, error) {
	var (
		log      = ctx.Get().GetLogger()
		storage  = ctx.Get().GetStorage()
		pod      *types.Pod
		replicas int
	)

	for i := 0; i < len(service.Pods); i++ {
		pod = service.Pods[i]
		if pod.State.State == "deleting" {
			continue
		}
		replicas++
	}

	if replicas == service.Config.Replicas {
		log.Debug("Service: Replicas not needed, replicas equal")
		return service, nil
	}

	if replicas < service.Config.Replicas {
		for i := 0; i < (service.Config.Replicas - replicas); i++ {
			if err := s.AddPod(service); err != nil {
				return service, err
			}
		}
	}

	if replicas > service.Config.Replicas {
		for i := 0; i < (replicas - service.Config.Replicas); i++ {
			if err := s.DelPod(service); err != nil {
				return service, err
			}
		}
	}

	svc, err := storage.Service().Update(s.Context, service)
	if err != nil {
		log.Error("Error: insert service to db", err)
		return svc, err
	}

	return svc, nil
}

func (s *service) GenerateSpec(service *types.Service) types.PodSpec {

	var (
		log = ctx.Get().GetLogger()
	)

	log.Debug("Generate new node pod spec")
	var spec = types.PodSpec{}
	spec.ID = uuid.NewV4().String()
	spec.Created = time.Now()
	spec.Updated = time.Now()

	cs := new(types.ContainerSpec)
	cs.Image = types.ImageSpec{
		Name: service.Config.Image,
		Pull: true,
	}

	for _, port := range service.Config.Ports {
		cs.Ports = append(cs.Ports, types.ContainerPortSpec{
			ContainerPort: port.Container,
			Protocol:      port.Protocol,
		})
	}

	cs.Command = service.Config.Command
	cs.Entrypoint = service.Config.Entrypoint
	cs.Envs = service.Config.EnvVars
	cs.Quota = types.ContainerQuotaSpec{
		Memory: service.Config.Memory,
	}

	cs.RestartPolicy = types.ContainerRestartPolicySpec{
		Name:    "always",
		Attempt: 0,
	}

	spec.Containers = append(spec.Containers, cs)

	var state = new(types.PodState)
	state.State = service.State.State

	return spec
}

func createConfig(opts map[string]interface{}) (*types.ServiceConfig, error) {
	config := new(types.ServiceConfig)
	if err := patchConfig(opts, config); err != nil {
		return nil, err
	}
	return config, nil
}

func updateConfig(opts map[string]interface{}, config *types.ServiceConfig) error {
	if config == nil {
		config = new(types.ServiceConfig)
	}

	tmp := make(map[string]interface{})
	for k, v := range opts {
		tmp[k] = v
	}
	delete(tmp, "image")

	return patchConfig(tmp, config)
}

func patchConfig(opts map[string]interface{}, config *types.ServiceConfig) error {

	config.Replicas = int(1)
	config.Memory = int64(32)

	if val, ok := opts["replicas"]; ok {
		switch reflect.ValueOf(val).Kind() {
		case reflect.Float64:
			config.Replicas = int(val.(float64))
		case reflect.String:
			i, err := strconv.Atoi(val.(string))
			if err != nil {
				return err
			}
			config.Replicas = i
		default:
			return errors.New("replicas incorrect format")
		}
	}

	if val, ok := opts["memory"]; ok {
		switch reflect.ValueOf(val).Kind() {
		case reflect.Float64:
			config.Memory = int64(val.(float64))
		case reflect.String:
			i, err := strconv.ParseInt(val.(string), 10, 64)
			if err != nil {
				return err
			}
			config.Memory = i
		default:
			return errors.New("memory incorrect format")
		}
	}

	if val, ok := opts["image"]; ok {
		if reflect.ValueOf(val).Kind() != reflect.String {
			return errors.New("image incorrect format")
		}
		config.Image = val.(string)
	}

	if val, ok := opts["entrypoint"]; ok {
		if err := json.Unmarshal([]byte(val.(string)), &config.Entrypoint); err != nil {
			return errors.New("entrypoint incorrect format")
		}
	}

	if val, ok := opts["command"]; ok {
		if reflect.ValueOf(val).Kind() != reflect.String {
			return errors.New("command incorrect format")
		}
		config.Command = strings.Split(val.(string), " ")
	}

	if val, ok := opts["env"]; ok {
		if reflect.ValueOf(val).Kind() != reflect.String {
			return errors.New("env incorrect format")
		}
		// TODO: Validate format data (key=val,key=val)
		config.Command = strings.Split(val.(string), " ")
	}

	if val, ok := opts["ports"]; ok {
		if reflect.ValueOf(val).Kind() == reflect.String {
			return errors.New("ports incorrect format")
		}
		if err := json.Unmarshal([]byte(val.(string)), &config.Ports); err != nil {
			return errors.New("ports incorrect format")
		}
	}

	return nil
}<commit_msg>update service method update<commit_after>//
// Last.Backend LLC CONFIDENTIAL
// __________________
//
// [2014] - [2017] Last.Backend LLC
// All Rights Reserved.
//
// NOTICE:  All information contained herein is, and remains
// the property of Last.Backend LLC and its suppliers,
// if any.  The intellectual and technical concepts contained
// herein are proprietary to Last.Backend LLC
// and its suppliers and may be covered by Russian Federation and Foreign Patents,
// patents in process, and are protected by trade secret or copyright law.
// Dissemination of this information or reproduction of this material
// is strictly forbidden unless prior written permission is obtained
// from Last.Backend LLC.
//

package service

import (
	"context"
	"encoding/json"
	"github.com/lastbackend/lastbackend/pkg/apis/types"
	ctx "github.com/lastbackend/lastbackend/pkg/daemon/context"
	"github.com/lastbackend/lastbackend/pkg/daemon/node"
	"github.com/lastbackend/lastbackend/pkg/daemon/service/routes/request"
	"github.com/lastbackend/lastbackend/pkg/util/validator"
	"github.com/pkg/errors"
	"github.com/satori/go.uuid"
	"reflect"
	"strconv"
	"strings"
	"time"
	"fmt"
)

type service struct {
	Context   context.Context
	Namespace types.Meta
}

func New(ctx context.Context, namespace types.Meta) *service {
	return &service{
		Context:   ctx,
		Namespace: namespace,
	}
}

func (s *service) List() (*types.ServiceList, error) {
	var storage = ctx.Get().GetStorage()
	return storage.Service().ListByNamespace(s.Context, s.Namespace.ID)
}

func (s *service) Get(service string) (*types.Service, error) {

	var (
		err     error
		log     = ctx.Get().GetLogger()
		storage = ctx.Get().GetStorage()
		svc     *types.Service
	)

	if validator.IsUUID(service) {
		svc, err = storage.Service().GetByID(s.Context, s.Namespace.ID, service)
	} else {
		svc, err = storage.Service().GetByName(s.Context, s.Namespace.ID, service)
	}

	if err != nil {
		log.Error("Error: find service by name", err.Error())
		return svc, err
	}

	return svc, nil
}

func (s *service) Create(rq *request.RequestServiceCreateS) (*types.Service, error) {

	var (
		log     = ctx.Get().GetLogger()
		storage = ctx.Get().GetStorage()
		svc     = new(types.Service)
	)

	log.Debug("Service: create new service")

	svc.Meta = types.ServiceMeta{}
	svc.Meta.ID = uuid.NewV4().String()
	svc.Meta.Name = rq.Name
	svc.Meta.Region = rq.Region
	svc.Meta.Namespace = s.Namespace.Name
	svc.Meta.Description = rq.Description
	svc.Meta.Updated = time.Now()
	svc.Meta.Created = time.Now()

	config, err := createConfig(rq.Config)
	if err != nil {
		log.Errorf("Error: create config from request opts : %s", err.Error())
		return svc, err
	}

	svc.Config = *config

	log.Debugf("Service: Create: add pods : %d", svc.Config.Replicas)
	for i := 0; i < svc.Config.Replicas; i++ {
		log.Debug("Service: Create: add new pod")
		if err := s.AddPod(svc); err != nil {
			log.Errorf("Service: Create: add new pod error: %s", err.Error())
			return svc, err
		}
	}

	svc, err = storage.Service().Insert(s.Context, svc)
	if err != nil {
		log.Errorf("Error: insert service to db : %s", err.Error())
		return svc, err
	}

	return svc, nil
}

func (s *service) Update(service *types.Service, rq *request.RequestServiceUpdateS) (*types.Service, error) {

	var (
		err     error
		log     = ctx.Get().GetLogger()
		storage = ctx.Get().GetStorage()
		svc     *types.Service
	)

	log.Debug("Service: update service info and config")

	if rq.Name != "" {
		service.Meta.Name = rq.Name
	}

	if rq.Description != "" {
		service.Meta.Description = rq.Description
	}

	if rq.Domains != nil {
		service.Domains = rq.Domains
	}

	if err := updateConfig(rq.Config, &service.Config); err != nil {
		log.Error("Error: update service config from request opts", err)
		return svc, err
	}

	// Update pod spec
	spec := s.GenerateSpec(service)

	log.Debugf("Service: Update: pods count: %d", len(service.Pods))
	for _, pod := range service.Pods {
		log.Debugf("Service: Update: pod %s update", pod.Meta.ID)
		pod.Spec = spec
	}

	fmt.Println("4 ::: >>>>", service.Config.EnvVars)

	svc, err = storage.Service().Update(s.Context, service)
	if err != nil {
		log.Error("Error: insert service to db", err)
		return svc, err
	}

	return svc, nil
}

func (s *service) Remove(service *types.Service) error {
	var (
		log     = ctx.Get().GetLogger()
		storage = ctx.Get().GetStorage()
	)

	if err := storage.Service().Remove(s.Context, service); err != nil {
		log.Error("Error: insert service to db", err)
		return err
	}
	return nil
}

func (s *service) AddPod(service *types.Service) error {

	var (
		log = ctx.Get().GetLogger()
	)

	log.Debug("Create new pod state on service")

	pod := new(types.Pod)
	pod.State.State = "running"
	pod.Meta.ID = uuid.NewV4().String()
	pod.Meta.Created = time.Now()
	pod.Meta.Updated = time.Now()
	pod.Spec = s.GenerateSpec(service)

	n, err := node.New().Allocate(s.Context, pod.Spec)
	if err != nil {
		return err
	}

	log.Debugf("Service: Add pod: Node meta: %s", n.Meta)
	pod.Meta.Hostname = n.Meta.Hostname

	service.Pods = append(service.Pods, pod)

	return nil
}

func (s *service) DelPod(service *types.Service) error {

	var (
		log = ctx.Get().GetLogger()
		pod *types.Pod
	)

	log.Debug("Create new pod state on service")

	for i := len(service.Pods); i >= 0; i-- {
		pod = service.Pods[i-1]
		if pod.State.State != "deleting" {
			break
		}
	}

	pod.State.State = "deleting"
	return nil
}

func (s *service) SetPods(c context.Context, pods []types.PodNodeState) error {
	var (
		log     = ctx.Get().GetLogger()
		storage = ctx.Get().GetStorage()
	)

	for _, pod := range pods {
		svc, err := storage.Service().GetByPodID(c, pod.Meta.ID)
		if err != nil {
			log.Errorf("Error: get pod from db: %s", err)
			return err
		}

		if svc == nil {
			continue
		}

		if p, e := storage.Pod().GetByID(c, svc.Meta.Namespace, svc.Meta.ID, pod.Meta.ID); p == nil || e != nil {

			if err != nil {
				log.Errorf("Error: get pod from db: %s", err)
				return err
			}

			if p == nil {
				log.Warnf("Pod not found, skip setting: %s", pod.Meta.ID)
			}

		}

		if err := storage.Pod().Update(c, svc.Meta.Namespace, svc.Meta.ID, &pod); err != nil {
			log.Errorf("Error: set pod to db: %s", err)
			return err
		}
	}

	return nil
}

func (s *service) Scale(c context.Context, service *types.Service) (*types.Service, error) {
	var (
		log      = ctx.Get().GetLogger()
		storage  = ctx.Get().GetStorage()
		pod      *types.Pod
		replicas int
	)

	for i := 0; i < len(service.Pods); i++ {
		pod = service.Pods[i]
		if pod.State.State == "deleting" {
			continue
		}
		replicas++
	}

	if replicas == service.Config.Replicas {
		log.Debug("Service: Replicas not needed, replicas equal")
		return service, nil
	}

	if replicas < service.Config.Replicas {
		for i := 0; i < (service.Config.Replicas - replicas); i++ {
			if err := s.AddPod(service); err != nil {
				return service, err
			}
		}
	}

	if replicas > service.Config.Replicas {
		for i := 0; i < (replicas - service.Config.Replicas); i++ {
			if err := s.DelPod(service); err != nil {
				return service, err
			}
		}
	}

	svc, err := storage.Service().Update(s.Context, service)
	if err != nil {
		log.Error("Error: insert service to db", err)
		return svc, err
	}

	return svc, nil
}

func (s *service) GenerateSpec(service *types.Service) types.PodSpec {

	var (
		log = ctx.Get().GetLogger()
	)

	log.Debug("Generate new node pod spec")
	var spec = types.PodSpec{}
	spec.ID = uuid.NewV4().String()
	spec.Created = time.Now()
	spec.Updated = time.Now()

	cs := new(types.ContainerSpec)
	cs.Image = types.ImageSpec{
		Name: service.Config.Image,
		Pull: true,
	}

	for _, port := range service.Config.Ports {
		cs.Ports = append(cs.Ports, types.ContainerPortSpec{
			ContainerPort: port.Container,
			Protocol:      port.Protocol,
		})
	}

	cs.Command = service.Config.Command
	cs.Entrypoint = service.Config.Entrypoint
	cs.Envs = service.Config.EnvVars
	cs.Quota = types.ContainerQuotaSpec{
		Memory: service.Config.Memory,
	}

	cs.RestartPolicy = types.ContainerRestartPolicySpec{
		Name:    "always",
		Attempt: 0,
	}

	spec.Containers = append(spec.Containers, cs)

	var state = new(types.PodState)
	state.State = service.State.State

	return spec
}

func createConfig(opts map[string]interface{}) (*types.ServiceConfig, error) {
	config := new(types.ServiceConfig)
	if err := patchConfig(opts, config); err != nil {
		return nil, err
	}
	return config, nil
}

func updateConfig(opts map[string]interface{}, config *types.ServiceConfig) error {
	if config == nil {
		config = new(types.ServiceConfig)
	}

	tmp := make(map[string]interface{})
	for k, v := range opts {
		tmp[k] = v
	}

	return patchConfig(tmp, config)
}

func patchConfig(opts map[string]interface{}, config *types.ServiceConfig) error {

	config.Replicas = int(1)
	config.Memory = int64(32)

	if val, ok := opts["replicas"]; ok {
		switch reflect.ValueOf(val).Kind() {
		case reflect.Float64:
			config.Replicas = int(val.(float64))
		case reflect.String:
			i, err := strconv.Atoi(val.(string))
			if err != nil {
				return err
			}
			config.Replicas = i
		default:
			return errors.New("replicas incorrect format")
		}
	}

	if val, ok := opts["memory"]; ok {
		switch reflect.ValueOf(val).Kind() {
		case reflect.Float64:
			config.Memory = int64(val.(float64))
		case reflect.String:
			i, err := strconv.ParseInt(val.(string), 10, 64)
			if err != nil {
				return err
			}
			config.Memory = i
		default:
			return errors.New("memory incorrect format")
		}
	}

	if val, ok := opts["image"]; ok {
		if reflect.ValueOf(val).Kind() != reflect.String {
			return errors.New("image incorrect format")
		}
		config.Image = val.(string)
	}

	if val, ok := opts["entrypoint"]; ok {
		if err := json.Unmarshal([]byte(val.(string)), &config.Entrypoint); err != nil {
			return errors.New("entrypoint incorrect format")
		}
	}

	if val, ok := opts["command"]; ok {
		if reflect.ValueOf(val).Kind() != reflect.String {
			return errors.New("command incorrect format")
		}
		config.Command = strings.Split(val.(string), " ")
	}

	if val, ok := opts["env"]; ok {
		v := reflect.ValueOf(val)
		if v.Kind() != reflect.Slice {
			return errors.New("env incorrect format")
		}
		// TODO: Validate format data (key=val,key=val)
		ret := make([]string, v.Len())
		for i := 0; i < v.Len(); i++ {
			ret[i] = v.Index(i).Interface().(string)
		}
		config.EnvVars = ret
		fmt.Println("3 ::: >>>>", config.EnvVars)
	}

	if val, ok := opts["ports"]; ok {
		v := reflect.ValueOf(val)
		if v.Kind() == reflect.Slice {
			return errors.New("ports incorrect format")
		}
		ret := make([]types.Port, v.Len())
		for i := 0; i < v.Len(); i++ {
			ret[i] = v.Index(i).Interface().(types.Port)
		}
		config.Ports = ret
		//if err := json.Unmarshal([]byte(val.(string)), &config.Ports); err != nil {
		//	return errors.New("ports incorrect format")
		//}
	}

	return nil
}
<|endoftext|>


<commit_before>package exchange

import (
	"encoding/json"
	"fmt"
	"sync"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"

	"nimona.io/internal/store/graph"
	"nimona.io/internal/store/kv"
	"nimona.io/pkg/context"
	"nimona.io/pkg/crypto"
	"nimona.io/pkg/discovery"
	"nimona.io/pkg/discovery/mocks"
	"nimona.io/pkg/hash"
	"nimona.io/pkg/middleware/handshake"
	"nimona.io/pkg/net"
	"nimona.io/pkg/object"
	"nimona.io/pkg/peer"
)

func TestSendSuccess(t *testing.T) {
	disc1 := discovery.NewDiscoverer()
	disc2 := discovery.NewDiscoverer()

	k1, _, x1, _, l1 := newPeer(t, "", disc1, true, false)
	k2, _, x2, _, l2 := newPeer(t, "", disc2, true, false)

	disc1.Add(l2.GetSignedPeer())
	disc2.Add(l1.GetSignedPeer())

	em1 := map[string]interface{}{
		"@ctx:s": "test/msg",
		"body:s": "bar1",
	}
	eo1 := object.FromMap(em1)

	em2 := map[string]interface{}{
		"@ctx:s": "test/msg",
		"body:s": "bar1",
	}
	eo2 := object.FromMap(em2)

	wg := sync.WaitGroup{}
	wg.Add(2)

	w1ObjectHandled := false
	w2ObjectHandled := false

	err := crypto.Sign(eo1, k2)
	assert.NoError(t, err)

	// nolint: dupl
	_, err = x1.Handle("test/msg", func(e *Envelope) error {
		o := e.Payload
		assert.Equal(t, eo1.Get("body:s"), o.Get("body:s"))
		w1ObjectHandled = true
		wg.Done()
		return nil
	})
	assert.NoError(t, err)

	_, err = x2.Handle("tes**", func(e *Envelope) error {
		o := e.Payload
		assert.Equal(t, eo2.Get("body:s"), o.Get("body:s"))
		w2ObjectHandled = true
		wg.Done()
		return nil
	})
	assert.NoError(t, err)

	ctx := context.Background()

	errS1 := x2.Send(ctx, eo1, "peer:"+k1.PublicKey.Fingerprint().String())
	assert.NoError(t, errS1)

	time.Sleep(time.Second)

	// TODO should be able to send not signed
	errS2 := x1.Send(ctx, eo2, "peer:"+k2.PublicKey.Fingerprint().String())
	assert.NoError(t, errS2)

	if errS1 == nil && errS2 == nil {
		wg.Wait()
	}

	assert.True(t, w1ObjectHandled)
	assert.True(t, w2ObjectHandled)
}

func TestSendWithResponseSuccess(t *testing.T) {
	disc1 := discovery.NewDiscoverer()
	disc2 := discovery.NewDiscoverer()

	k1, _, x1, _, l1 := newPeer(t, "", disc1, true, false)
	k2, _, x2, _, l2 := newPeer(t, "", disc2, true, false)

	disc1.Add(l2.GetSignedPeer())
	disc2.Add(l1.GetSignedPeer())

	mp2 := &mocks.Provider{}
	err := disc2.AddProvider(mp2)
	assert.NoError(t, err)

	// send object with request id
	em1 := map[string]interface{}{
		"@ctx:s": "test/msg",
		"body:s": "bar1",
	}
	eo1 := object.FromMap(em1)
	err = crypto.Sign(eo1, k1)
	assert.NoError(t, err)

	out := make(chan *Envelope, 1)

	ctx := context.New(context.WithTimeout(time.Second * 3))
	err = x2.Send(
		ctx,
		eo1,
		l1.GetAddresses()[0],
		WithResponse("foo", out),
	)
	assert.NoError(t, err)

	// send object in response with the same request id

	em2 := map[string]interface{}{
		"@ctx:s":        "test/msg",
		"body:s":        "bar2",
		ObjectRequestID: "foo",
	}
	eo2 := object.FromMap(em2)
	err = crypto.Sign(eo2, k2)
	assert.NoError(t, err)

	err = x1.Send(
		ctx,
		eo2,
		l2.GetAddresses()[0],
	)
	assert.NoError(t, err)

	select {
	case <-ctx.Done():
		t.Log("did not receive response in time")
		t.FailNow()
	case o2r := <-out:
		compareObjects(t, eo2, o2r.Payload)
	}
}

func TestSendWithResponseSuccessHTTP(t *testing.T) {
	disc1 := discovery.NewDiscoverer()
	disc2 := discovery.NewDiscoverer()

	k1, _, x1, _, l1 := newPeer(t, "", disc1, false, true)
	k2, _, x2, _, l2 := newPeer(t, "", disc2, false, true)

	disc1.Add(l2.GetSignedPeer())
	disc2.Add(l1.GetSignedPeer())

	mp2 := &mocks.Provider{}
	err := disc2.AddProvider(mp2)
	assert.NoError(t, err)

	// send object with request id
	em1 := map[string]interface{}{
		"@ctx:s": "test/msg",
		"body:s": "bar1",
	}
	eo1 := object.FromMap(em1)
	err = crypto.Sign(eo1, k1)
	assert.NoError(t, err)

	out := make(chan *Envelope, 1)

	ctx := context.New(context.WithTimeout(time.Second * 3))
	err = x2.Send(
		ctx,
		eo1,
		l1.GetAddresses()[0],
		WithResponse("foo", out),
	)
	assert.NoError(t, err)

	// send object in response with the same request id

	em2 := map[string]interface{}{
		"@ctx:s":        "test/msg",
		"body:s":        "bar2",
		ObjectRequestID: "foo",
	}
	eo2 := object.FromMap(em2)
	err = crypto.Sign(eo2, k2)
	assert.NoError(t, err)

	err = x1.Send(
		ctx,
		eo2,
		l2.GetAddresses()[0],
	)
	assert.NoError(t, err)

	select {
	case <-ctx.Done():
		t.Log("did not receive response in time")
		t.FailNow()
	case o2r := <-out:
		compareObjects(t, eo2, o2r.Payload)
	}
}

func TestRequestSuccess(t *testing.T) {
	disc1 := discovery.NewDiscoverer()
	disc2 := discovery.NewDiscoverer()

	_, _, x1, _, l1 := newPeer(t, "", disc1, true, false)
	_, _, _, d2, l2 := newPeer(t, "", disc2, true, false)

	disc1.Add(l2.GetSignedPeer())
	disc2.Add(l1.GetSignedPeer())

	mp2 := &mocks.Provider{}
	err := disc2.AddProvider(mp2)
	assert.NoError(t, err)

	// add an object to n2's store
	em1 := map[string]interface{}{
		"@ctx:s": "test/msg",
		"body:s": "bar1",
	}
	eo1 := object.FromMap(em1)
	err = d2.Put(eo1)
	assert.NoError(t, err)

	// request object, with req id
	out := make(chan *Envelope, 1)
	ctx := context.New(context.WithTimeout(time.Second * 3))
	err = x1.Request(
		ctx,
		hash.New(eo1),
		l2.GetAddresses()[0],
		WithResponse("foo", out),
	)
	assert.NoError(t, err)

	// check if we got back the expected obj
	select {
	case <-ctx.Done():
		t.Log("did not receive response in time")
		t.FailNow()
	case o1r := <-out:
		eo1.Set("_reqID:s", "foo")
		compareObjects(t, eo1, o1r.Payload)
	}
}

func TestRequestSuccessHTTP(t *testing.T) {
	disc1 := discovery.NewDiscoverer()
	disc2 := discovery.NewDiscoverer()

	_, _, x1, _, l1 := newPeer(t, "", disc1, false, true)
	_, _, _, d2, l2 := newPeer(t, "", disc2, false, true)

	disc1.Add(l2.GetSignedPeer())
	disc2.Add(l1.GetSignedPeer())

	mp2 := &mocks.Provider{}
	err := disc2.AddProvider(mp2)
	assert.NoError(t, err)

	// add an object to n2's store
	em1 := map[string]interface{}{
		"@ctx:s": "test/msg",
		"body:s": "bar1",
	}
	eo1 := object.FromMap(em1)
	err = d2.Put(eo1)
	assert.NoError(t, err)

	// request object, with req id
	out := make(chan *Envelope, 1)
	ctx := context.New(context.WithTimeout(time.Second * 3))
	err = x1.Request(
		ctx,
		hash.New(eo1),
		l2.GetAddresses()[0],
		WithResponse("foo", out),
	)
	assert.NoError(t, err)

	// check if we got back the expected obj
	select {
	case <-ctx.Done():
		t.Log("did not receive response in time")
		t.FailNow()
	case o1r := <-out:
		eo1.Set("_reqID:s", "foo")
		compareObjects(t, eo1, o1r.Payload)
	}
}

func TestSendRelay(t *testing.T) {
	// enable binding to local addresses
	disc1 := discovery.NewDiscoverer()
	disc2 := discovery.NewDiscoverer()
	disc3 := discovery.NewDiscoverer()

	net.BindLocal = true
	k0, _, _, _, l0 := newPeer(t, "", disc1, true, false)

	// disable binding to local addresses
	net.BindLocal = false
	k1, _, x1, _, l1 := newPeer(t, "relay:"+l0.GetAddresses()[0], disc2, true, false)
	k2, _, x2, _, l2 := newPeer(t, "relay:"+l0.GetAddresses()[0], disc3, true, false)

	fmt.Printf("\n\n\n\n-----------------------------\n")
	fmt.Println("k0:",
		k0.PublicKey.Fingerprint(),
		l0.GetAddresses(),
	)
	fmt.Println("k1:",
		k1.PublicKey.Fingerprint(),
		l1.GetAddresses(),
	)
	fmt.Println("k2:",
		k2.PublicKey.Fingerprint(),
		l2.GetAddresses(),
	)
	fmt.Printf("-----------------------------\n\n\n\n")

	disc1.Add(l1.GetSignedPeer())
	disc1.Add(l2.GetSignedPeer())
	disc2.Add(l2.GetSignedPeer())
	disc3.Add(l1.GetSignedPeer())

	// init connection from n1 to n0
	err := x1.Send(
		context.Background(),
		object.FromMap(map[string]interface{}{"foo": "bar"}),
		l0.GetAddresses()[0],
	)
	assert.NoError(t, err)

	// init connection from n2 to n0
	err = x2.Send(
		context.Background(),
		object.FromMap(map[string]interface{}{"foo": "bar"}),
		l0.GetAddresses()[0],
	)
	assert.NoError(t, err)

	// now we should be able to relay objects between n1 and n2
	em1 := map[string]interface{}{
		"@ctx:s": "test/msg",
		"body:s": "bar1",
	}
	eo1 := object.FromMap(em1)

	em2 := map[string]interface{}{
		"@ctx:s": "test/msg",
		"body:s": "bar1",
	}
	eo2 := object.FromMap(em2)

	wg := sync.WaitGroup{}
	wg.Add(2)

	w1ObjectHandled := false
	w2ObjectHandled := false

	err = crypto.Sign(eo1, k2)
	assert.NoError(t, err)

	// nolint: dupl
	_, err = x1.Handle("test/msg", func(e *Envelope) error {
		o := e.Payload
		assert.Equal(t, eo1.Get("body:s"), o.Get("body:s"))
		w1ObjectHandled = true
		wg.Done()
		return nil
	})
	assert.NoError(t, err)

	_, err = x2.Handle("tes**", func(e *Envelope) error {
		o := e.Payload
		assert.Equal(t, eo2.Get("body:s"), o.Get("body:s"))
		w2ObjectHandled = true
		wg.Done()
		return nil
	})
	assert.NoError(t, err)

	ctx := context.New(context.WithTimeout(time.Second * 5))
	defer ctx.Cancel()

	err = x2.Send(ctx, eo1, "peer:"+k1.PublicKey.Fingerprint().String())
	assert.NoError(t, err)

	time.Sleep(time.Second)

	ctx2 := context.New(context.WithTimeout(time.Second * 5))
	defer ctx2.Cancel()

	// TODO should be able to send not signed
	err = x1.Send(ctx2, eo2, "peer:"+k2.PublicKey.Fingerprint().String())
	assert.NoError(t, err)

	wg.Wait()

	assert.True(t, w1ObjectHandled)
	assert.True(t, w2ObjectHandled)
}

func newPeer(
	t *testing.T,
	relayAddress string,
	discover discovery.Discoverer,
	listenTCP bool,
	listenHTTP bool,
) (
	*crypto.PrivateKey,
	net.Network,
	*exchange,
	graph.Store,
	*peer.LocalPeer,
) {
	pk, err := crypto.GenerateKey()
	assert.NoError(t, err)

	ds := graph.New(kv.NewMemory())

	li, err := peer.NewLocalPeer("", pk)
	assert.NoError(t, err)

	if relayAddress != "" {
		li.AddAddress("relay", []string{relayAddress})
	}

	n, err := net.New(discover, li)
	assert.NoError(t, err)

	if listenTCP {
		tcp := net.NewTCPTransport(li, "0.0.0.0:0")
		n.AddTransport("tcps", tcp)
	}

	if listenHTTP {
		http := net.NewHTTPTransport(li, "0.0.0.0:0")
		n.AddTransport("https", http)
	}

	hsm := handshake.New(li, discover)
	n.AddMiddleware(hsm.Handle())

	ctx := context.Background()

	x, err := New(ctx, pk, n, ds, discover, li)
	assert.NoError(t, err)

	return pk, n, x.(*exchange), ds, li
}

func compareObjects(t *testing.T, expected, actual object.Object) {
	assert.Equal(t, jp(expected), jp(actual))
}

// jp is a lazy approach to comparing the mess that is unmarshaling json when
// dealing with numbers
func jp(v interface{}) string {
	b, _ := json.MarshalIndent(v, "", "  ") // nolint
	return string(b)
}
<commit_msg>chore(exchange): remove http tests<commit_after>package exchange

import (
	"encoding/json"
	"fmt"
	"sync"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"

	"nimona.io/internal/store/graph"
	"nimona.io/internal/store/kv"
	"nimona.io/pkg/context"
	"nimona.io/pkg/crypto"
	"nimona.io/pkg/discovery"
	"nimona.io/pkg/discovery/mocks"
	"nimona.io/pkg/hash"
	"nimona.io/pkg/middleware/handshake"
	"nimona.io/pkg/net"
	"nimona.io/pkg/object"
	"nimona.io/pkg/peer"
)

func TestSendSuccess(t *testing.T) {
	disc1 := discovery.NewDiscoverer()
	disc2 := discovery.NewDiscoverer()

	k1, _, x1, _, l1 := newPeer(t, "", disc1, true, false)
	k2, _, x2, _, l2 := newPeer(t, "", disc2, true, false)

	disc1.Add(l2.GetSignedPeer())
	disc2.Add(l1.GetSignedPeer())

	em1 := map[string]interface{}{
		"@ctx:s": "test/msg",
		"body:s": "bar1",
	}
	eo1 := object.FromMap(em1)

	em2 := map[string]interface{}{
		"@ctx:s": "test/msg",
		"body:s": "bar1",
	}
	eo2 := object.FromMap(em2)

	wg := sync.WaitGroup{}
	wg.Add(2)

	w1ObjectHandled := false
	w2ObjectHandled := false

	err := crypto.Sign(eo1, k2)
	assert.NoError(t, err)

	// nolint: dupl
	_, err = x1.Handle("test/msg", func(e *Envelope) error {
		o := e.Payload
		assert.Equal(t, eo1.Get("body:s"), o.Get("body:s"))
		w1ObjectHandled = true
		wg.Done()
		return nil
	})
	assert.NoError(t, err)

	_, err = x2.Handle("tes**", func(e *Envelope) error {
		o := e.Payload
		assert.Equal(t, eo2.Get("body:s"), o.Get("body:s"))
		w2ObjectHandled = true
		wg.Done()
		return nil
	})
	assert.NoError(t, err)

	ctx := context.Background()

	errS1 := x2.Send(ctx, eo1, "peer:"+k1.PublicKey.Fingerprint().String())
	assert.NoError(t, errS1)

	time.Sleep(time.Second)

	// TODO should be able to send not signed
	errS2 := x1.Send(ctx, eo2, "peer:"+k2.PublicKey.Fingerprint().String())
	assert.NoError(t, errS2)

	if errS1 == nil && errS2 == nil {
		wg.Wait()
	}

	assert.True(t, w1ObjectHandled)
	assert.True(t, w2ObjectHandled)
}

func TestSendWithResponseSuccess(t *testing.T) {
	disc1 := discovery.NewDiscoverer()
	disc2 := discovery.NewDiscoverer()

	k1, _, x1, _, l1 := newPeer(t, "", disc1, true, false)
	k2, _, x2, _, l2 := newPeer(t, "", disc2, true, false)

	disc1.Add(l2.GetSignedPeer())
	disc2.Add(l1.GetSignedPeer())

	mp2 := &mocks.Provider{}
	err := disc2.AddProvider(mp2)
	assert.NoError(t, err)

	// send object with request id
	em1 := map[string]interface{}{
		"@ctx:s": "test/msg",
		"body:s": "bar1",
	}
	eo1 := object.FromMap(em1)
	err = crypto.Sign(eo1, k1)
	assert.NoError(t, err)

	out := make(chan *Envelope, 1)

	ctx := context.New(context.WithTimeout(time.Second * 3))
	err = x2.Send(
		ctx,
		eo1,
		l1.GetAddresses()[0],
		WithResponse("foo", out),
	)
	assert.NoError(t, err)

	// send object in response with the same request id

	em2 := map[string]interface{}{
		"@ctx:s":        "test/msg",
		"body:s":        "bar2",
		ObjectRequestID: "foo",
	}
	eo2 := object.FromMap(em2)
	err = crypto.Sign(eo2, k2)
	assert.NoError(t, err)

	err = x1.Send(
		ctx,
		eo2,
		l2.GetAddresses()[0],
	)
	assert.NoError(t, err)

	select {
	case <-ctx.Done():
		t.Log("did not receive response in time")
		t.FailNow()
	case o2r := <-out:
		compareObjects(t, eo2, o2r.Payload)
	}
}

func TestRequestSuccess(t *testing.T) {
	disc1 := discovery.NewDiscoverer()
	disc2 := discovery.NewDiscoverer()

	_, _, x1, _, l1 := newPeer(t, "", disc1, true, false)
	_, _, _, d2, l2 := newPeer(t, "", disc2, true, false)

	disc1.Add(l2.GetSignedPeer())
	disc2.Add(l1.GetSignedPeer())

	mp2 := &mocks.Provider{}
	err := disc2.AddProvider(mp2)
	assert.NoError(t, err)

	// add an object to n2's store
	em1 := map[string]interface{}{
		"@ctx:s": "test/msg",
		"body:s": "bar1",
	}
	eo1 := object.FromMap(em1)
	err = d2.Put(eo1)
	assert.NoError(t, err)

	// request object, with req id
	out := make(chan *Envelope, 1)
	ctx := context.New(context.WithTimeout(time.Second * 3))
	err = x1.Request(
		ctx,
		hash.New(eo1),
		l2.GetAddresses()[0],
		WithResponse("foo", out),
	)
	assert.NoError(t, err)

	// check if we got back the expected obj
	select {
	case <-ctx.Done():
		t.Log("did not receive response in time")
		t.FailNow()
	case o1r := <-out:
		eo1.Set("_reqID:s", "foo")
		compareObjects(t, eo1, o1r.Payload)
	}
}

func TestSendRelay(t *testing.T) {
	// enable binding to local addresses
	disc1 := discovery.NewDiscoverer()
	disc2 := discovery.NewDiscoverer()
	disc3 := discovery.NewDiscoverer()

	net.BindLocal = true
	k0, _, _, _, l0 := newPeer(t, "", disc1, true, false)

	// disable binding to local addresses
	net.BindLocal = false
	k1, _, x1, _, l1 := newPeer(t, "relay:"+l0.GetAddresses()[0], disc2, true, false)
	k2, _, x2, _, l2 := newPeer(t, "relay:"+l0.GetAddresses()[0], disc3, true, false)

	fmt.Printf("\n\n\n\n-----------------------------\n")
	fmt.Println("k0:",
		k0.PublicKey.Fingerprint(),
		l0.GetAddresses(),
	)
	fmt.Println("k1:",
		k1.PublicKey.Fingerprint(),
		l1.GetAddresses(),
	)
	fmt.Println("k2:",
		k2.PublicKey.Fingerprint(),
		l2.GetAddresses(),
	)
	fmt.Printf("-----------------------------\n\n\n\n")

	disc1.Add(l1.GetSignedPeer())
	disc1.Add(l2.GetSignedPeer())
	disc2.Add(l2.GetSignedPeer())
	disc3.Add(l1.GetSignedPeer())

	// init connection from n1 to n0
	err := x1.Send(
		context.Background(),
		object.FromMap(map[string]interface{}{"foo": "bar"}),
		l0.GetAddresses()[0],
	)
	assert.NoError(t, err)

	// init connection from n2 to n0
	err = x2.Send(
		context.Background(),
		object.FromMap(map[string]interface{}{"foo": "bar"}),
		l0.GetAddresses()[0],
	)
	assert.NoError(t, err)

	// now we should be able to relay objects between n1 and n2
	em1 := map[string]interface{}{
		"@ctx:s": "test/msg",
		"body:s": "bar1",
	}
	eo1 := object.FromMap(em1)

	em2 := map[string]interface{}{
		"@ctx:s": "test/msg",
		"body:s": "bar1",
	}
	eo2 := object.FromMap(em2)

	wg := sync.WaitGroup{}
	wg.Add(2)

	w1ObjectHandled := false
	w2ObjectHandled := false

	err = crypto.Sign(eo1, k2)
	assert.NoError(t, err)

	// nolint: dupl
	_, err = x1.Handle("test/msg", func(e *Envelope) error {
		o := e.Payload
		assert.Equal(t, eo1.Get("body:s"), o.Get("body:s"))
		w1ObjectHandled = true
		wg.Done()
		return nil
	})
	assert.NoError(t, err)

	_, err = x2.Handle("tes**", func(e *Envelope) error {
		o := e.Payload
		assert.Equal(t, eo2.Get("body:s"), o.Get("body:s"))
		w2ObjectHandled = true
		wg.Done()
		return nil
	})
	assert.NoError(t, err)

	ctx := context.New(context.WithTimeout(time.Second * 5))
	defer ctx.Cancel()

	err = x2.Send(ctx, eo1, "peer:"+k1.PublicKey.Fingerprint().String())
	assert.NoError(t, err)

	time.Sleep(time.Second)

	ctx2 := context.New(context.WithTimeout(time.Second * 5))
	defer ctx2.Cancel()

	// TODO should be able to send not signed
	err = x1.Send(ctx2, eo2, "peer:"+k2.PublicKey.Fingerprint().String())
	assert.NoError(t, err)

	wg.Wait()

	assert.True(t, w1ObjectHandled)
	assert.True(t, w2ObjectHandled)
}

func newPeer(
	t *testing.T,
	relayAddress string,
	discover discovery.Discoverer,
	listenTCP bool,
	listenHTTP bool,
) (
	*crypto.PrivateKey,
	net.Network,
	*exchange,
	graph.Store,
	*peer.LocalPeer,
) {
	pk, err := crypto.GenerateKey()
	assert.NoError(t, err)

	ds := graph.New(kv.NewMemory())

	li, err := peer.NewLocalPeer("", pk)
	assert.NoError(t, err)

	if relayAddress != "" {
		li.AddAddress("relay", []string{relayAddress})
	}

	n, err := net.New(discover, li)
	assert.NoError(t, err)

	if listenTCP {
		tcp := net.NewTCPTransport(li, "0.0.0.0:0")
		n.AddTransport("tcps", tcp)
	}

	if listenHTTP {
		http := net.NewHTTPTransport(li, "0.0.0.0:0")
		n.AddTransport("https", http)
	}

	hsm := handshake.New(li, discover)
	n.AddMiddleware(hsm.Handle())

	ctx := context.Background()

	x, err := New(ctx, pk, n, ds, discover, li)
	assert.NoError(t, err)

	return pk, n, x.(*exchange), ds, li
}

func compareObjects(t *testing.T, expected, actual object.Object) {
	assert.Equal(t, jp(expected), jp(actual))
}

// jp is a lazy approach to comparing the mess that is unmarshaling json when
// dealing with numbers
func jp(v interface{}) string {
	b, _ := json.MarshalIndent(v, "", "  ") // nolint
	return string(b)
}
<|endoftext|>


<commit_before>package main

import (
	"github.com/ghthor/gospec"
)

func DescribeEntryCase(c gospec.Context) {
	c.Specify("an entry case", func() {
		c.Specify("can be read", func() {
			c.Specify("from an io.Reader", func() {
			})

			c.Specify("from a file", func() {
			})
		})

		c.Specify("can be fixed", func() {
			c.Specify("by returning an entry case for the current standard", func() {
			})
		})

		c.Specify("can be written", func() {
		})
	})
}
<commit_msg>Implemented entry case specifications<commit_after>package main

import (
	"fmt"
	"github.com/ghthor/gospec"
	. "github.com/ghthor/gospec"
	"io/ioutil"
	"path/filepath"
	"strings"
)

func DescribeEntryCase(c gospec.Context) {
	entryCasesData := []string{}
	entryCases := make([]EntryCase, 0, len(entryCasesData))

	for _, data := range entryCasesData {
		entryCase, err := NewEntryCase(strings.NewReader(data))
		c.Assume(err, IsNil)

		entryCases = append(entryCases, entryCase)
	}

	c.Specify("an entry case", func() {
		c.Specify("can be read", func() {
			c.Specify("from an io.Reader", func() {
				for _, data := range entryCasesData {
					entryCase, err := NewEntryCase(strings.NewReader(data))
					c.Expect(err, IsNil)

					actualData, err := ioutil.ReadAll(entryCase.NewReader())
					c.Assume(err, IsNil)
					c.Expect(string(actualData), Equals, string(data))
				}
			})

			c.Specify("from a file", func() {
				d, err := ioutil.TempDir("_test", "entry_can_be_read_from_file_")
				c.Assume(err, IsNil)

				for i, data := range entryCasesData {
					filename := filepath.Join(d, fmt.Sprintf("case_%d", i))
					c.Assume(ioutil.WriteFile(filename, []byte(data), 0600), IsNil)

					entryCase, err := NewEntryCaseFromFile(filename)
					c.Expect(err, IsNil)

					actualData, err := ioutil.ReadAll(entryCase.NewReader())
					c.Assume(err, IsNil)
					c.Expect(string(actualData), Equals, string(data))
				}
			})
		})

		c.Specify("can be fixed", func() {
			entriesFixed := make([]EntryCase, 0, len(entryCases))

			for _, entryCase := range entryCases {
				entriesFixed = append(entriesFixed, entryCase.Fix())
			}

			c.Specify("by returning an entry case for the current standard", func() {
				for _, fixedEntry := range entriesFixed {
					actualData, err := ioutil.ReadAll(fixedEntry.NewReader())
					c.Assume(err, IsNil)

					c.Expect(string(actualData), Equals, string("the expected output"))
				}
			})
		})

		c.Specify("can be written", func() {
			for i, entryCase := range entryCases {
				actualData, err := ioutil.ReadAll(entryCase.NewReader())
				c.Assume(err, IsNil)
				c.Expect(string(actualData), Equals, entryCasesData[i])
			}
		})
	})
}
<|endoftext|>


<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 features

import (
	"k8s.io/apimachinery/pkg/util/runtime"

	utilfeature "k8s.io/apiserver/pkg/util/feature"
	"k8s.io/component-base/featuregate"
)

const (
	// Every feature gate should add method here following this template:
	//
	// // owner: @username
	// // alpha: v1.4
	// MyFeature() bool

	// owner: @tallclair
	// alpha: v1.5
	// beta: v1.6
	// deprecated: v1.18
	//
	// StreamingProxyRedirects controls whether the apiserver should intercept (and follow)
	// redirects from the backend (Kubelet) for streaming requests (exec/attach/port-forward).
	//
	// This feature is deprecated, and will be removed in v1.22.
	StreamingProxyRedirects featuregate.Feature = "StreamingProxyRedirects"

	// owner: @tallclair
	// alpha: v1.12
	// beta: v1.14
	//
	// ValidateProxyRedirects controls whether the apiserver should validate that redirects are only
	// followed to the same host. Only used if StreamingProxyRedirects is enabled.
	ValidateProxyRedirects featuregate.Feature = "ValidateProxyRedirects"

	// owner: @tallclair
	// alpha: v1.7
	// beta: v1.8
	// GA: v1.12
	//
	// AdvancedAuditing enables a much more general API auditing pipeline, which includes support for
	// pluggable output backends and an audit policy specifying how different requests should be
	// audited.
	AdvancedAuditing featuregate.Feature = "AdvancedAuditing"

	// owner: @ilackams
	// alpha: v1.7
	// beta: v1.16
	//
	// Enables compression of REST responses (GET and LIST only)
	APIResponseCompression featuregate.Feature = "APIResponseCompression"

	// owner: @smarterclayton
	// alpha: v1.8
	// beta: v1.9
	//
	// Allow API clients to retrieve resource lists in chunks rather than
	// all at once.
	APIListChunking featuregate.Feature = "APIListChunking"

	// owner: @apelisse
	// alpha: v1.12
	// beta: v1.13
	// stable: v1.18
	//
	// Allow requests to be processed but not stored, so that
	// validation, merging, mutation can be tested without
	// committing.
	DryRun featuregate.Feature = "DryRun"

	// owner: @caesarxuchao
	// alpha: v1.15
	// beta: v1.16
	//
	// Allow apiservers to show a count of remaining items in the response
	// to a chunking list request.
	RemainingItemCount featuregate.Feature = "RemainingItemCount"

	// owner: @apelisse, @lavalamp
	// alpha: v1.14
	// beta: v1.16
	// stable: v1.21
	//
	// Server-side apply. Merging happens on the server.
	ServerSideApply featuregate.Feature = "ServerSideApply"

	// owner: @caesarxuchao
	// alpha: v1.14
	// beta: v1.15
	//
	// Allow apiservers to expose the storage version hash in the discovery
	// document.
	StorageVersionHash featuregate.Feature = "StorageVersionHash"

	// owner: @caesarxuchao @roycaihw
	// alpha: v1.20
	//
	// Enable the storage version API.
	StorageVersionAPI featuregate.Feature = "StorageVersionAPI"

	// owner: @wojtek-t
	// alpha: v1.15
	// beta: v1.16
	// GA: v1.17
	//
	// Enables support for watch bookmark events.
	WatchBookmark featuregate.Feature = "WatchBookmark"

	// owner: @MikeSpreitzer @yue9944882
	// alpha: v1.15
	//
	//
	// Enables managing request concurrency with prioritization and fairness at each server
	APIPriorityAndFairness featuregate.Feature = "APIPriorityAndFairness"

	// owner: @wojtek-t
	// alpha: v1.16
	// beta: v1.20
	//
	// Deprecates and removes SelfLink from ObjectMeta and ListMeta.
	RemoveSelfLink featuregate.Feature = "RemoveSelfLink"

	// owner: @shaloulcy, @wojtek-t
	// alpha: v1.18
	// beta: v1.19
	// GA: v1.20
	//
	// Allows label and field based indexes in apiserver watch cache to accelerate list operations.
	SelectorIndex featuregate.Feature = "SelectorIndex"

	// owner: @liggitt
	// beta: v1.19
	//
	// Allows sending warning headers in API responses.
	WarningHeaders featuregate.Feature = "WarningHeaders"

	// owner: @wojtek-t
	// alpha: v1.20
	// beta: v1.21
	//
	// Allows for updating watchcache resource version with progress notify events.
	EfficientWatchResumption featuregate.Feature = "EfficientWatchResumption"

	// owner: @roycaihw
	// alpha: v1.20
	//
	// Assigns each kube-apiserver an ID in a cluster.
	APIServerIdentity featuregate.Feature = "APIServerIdentity"
)

func init() {
	runtime.Must(utilfeature.DefaultMutableFeatureGate.Add(defaultKubernetesFeatureGates))
}

// defaultKubernetesFeatureGates consists of all known Kubernetes-specific feature keys.
// To add a new feature, define a key for it above and add it here. The features will be
// available throughout Kubernetes binaries.
var defaultKubernetesFeatureGates = map[featuregate.Feature]featuregate.FeatureSpec{
	StreamingProxyRedirects:  {Default: true, PreRelease: featuregate.Deprecated},
	ValidateProxyRedirects:   {Default: true, PreRelease: featuregate.Beta},
	AdvancedAuditing:         {Default: true, PreRelease: featuregate.GA},
	APIResponseCompression:   {Default: true, PreRelease: featuregate.Beta},
	APIListChunking:          {Default: true, PreRelease: featuregate.Beta},
	DryRun:                   {Default: true, PreRelease: featuregate.GA},
	RemainingItemCount:       {Default: true, PreRelease: featuregate.Beta},
	ServerSideApply:          {Default: true, PreRelease: featuregate.GA},
	StorageVersionHash:       {Default: true, PreRelease: featuregate.Beta},
	StorageVersionAPI:        {Default: false, PreRelease: featuregate.Alpha},
	WatchBookmark:            {Default: true, PreRelease: featuregate.GA, LockToDefault: true},
	APIPriorityAndFairness:   {Default: true, PreRelease: featuregate.Beta},
	RemoveSelfLink:           {Default: true, PreRelease: featuregate.Beta},
	SelectorIndex:            {Default: true, PreRelease: featuregate.GA, LockToDefault: true},
	WarningHeaders:           {Default: true, PreRelease: featuregate.Beta},
	EfficientWatchResumption: {Default: true, PreRelease: featuregate.Beta},
	APIServerIdentity:        {Default: false, PreRelease: featuregate.Alpha},
}
<commit_msg>Revert SSA GA<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 features

import (
	"k8s.io/apimachinery/pkg/util/runtime"

	utilfeature "k8s.io/apiserver/pkg/util/feature"
	"k8s.io/component-base/featuregate"
)

const (
	// Every feature gate should add method here following this template:
	//
	// // owner: @username
	// // alpha: v1.4
	// MyFeature() bool

	// owner: @tallclair
	// alpha: v1.5
	// beta: v1.6
	// deprecated: v1.18
	//
	// StreamingProxyRedirects controls whether the apiserver should intercept (and follow)
	// redirects from the backend (Kubelet) for streaming requests (exec/attach/port-forward).
	//
	// This feature is deprecated, and will be removed in v1.22.
	StreamingProxyRedirects featuregate.Feature = "StreamingProxyRedirects"

	// owner: @tallclair
	// alpha: v1.12
	// beta: v1.14
	//
	// ValidateProxyRedirects controls whether the apiserver should validate that redirects are only
	// followed to the same host. Only used if StreamingProxyRedirects is enabled.
	ValidateProxyRedirects featuregate.Feature = "ValidateProxyRedirects"

	// owner: @tallclair
	// alpha: v1.7
	// beta: v1.8
	// GA: v1.12
	//
	// AdvancedAuditing enables a much more general API auditing pipeline, which includes support for
	// pluggable output backends and an audit policy specifying how different requests should be
	// audited.
	AdvancedAuditing featuregate.Feature = "AdvancedAuditing"

	// owner: @ilackams
	// alpha: v1.7
	// beta: v1.16
	//
	// Enables compression of REST responses (GET and LIST only)
	APIResponseCompression featuregate.Feature = "APIResponseCompression"

	// owner: @smarterclayton
	// alpha: v1.8
	// beta: v1.9
	//
	// Allow API clients to retrieve resource lists in chunks rather than
	// all at once.
	APIListChunking featuregate.Feature = "APIListChunking"

	// owner: @apelisse
	// alpha: v1.12
	// beta: v1.13
	// stable: v1.18
	//
	// Allow requests to be processed but not stored, so that
	// validation, merging, mutation can be tested without
	// committing.
	DryRun featuregate.Feature = "DryRun"

	// owner: @caesarxuchao
	// alpha: v1.15
	// beta: v1.16
	//
	// Allow apiservers to show a count of remaining items in the response
	// to a chunking list request.
	RemainingItemCount featuregate.Feature = "RemainingItemCount"

	// owner: @apelisse, @lavalamp
	// alpha: v1.14
	// beta: v1.16
	//
	// Server-side apply. Merging happens on the server.
	ServerSideApply featuregate.Feature = "ServerSideApply"

	// owner: @caesarxuchao
	// alpha: v1.14
	// beta: v1.15
	//
	// Allow apiservers to expose the storage version hash in the discovery
	// document.
	StorageVersionHash featuregate.Feature = "StorageVersionHash"

	// owner: @caesarxuchao @roycaihw
	// alpha: v1.20
	//
	// Enable the storage version API.
	StorageVersionAPI featuregate.Feature = "StorageVersionAPI"

	// owner: @wojtek-t
	// alpha: v1.15
	// beta: v1.16
	// GA: v1.17
	//
	// Enables support for watch bookmark events.
	WatchBookmark featuregate.Feature = "WatchBookmark"

	// owner: @MikeSpreitzer @yue9944882
	// alpha: v1.15
	//
	//
	// Enables managing request concurrency with prioritization and fairness at each server
	APIPriorityAndFairness featuregate.Feature = "APIPriorityAndFairness"

	// owner: @wojtek-t
	// alpha: v1.16
	// beta: v1.20
	//
	// Deprecates and removes SelfLink from ObjectMeta and ListMeta.
	RemoveSelfLink featuregate.Feature = "RemoveSelfLink"

	// owner: @shaloulcy, @wojtek-t
	// alpha: v1.18
	// beta: v1.19
	// GA: v1.20
	//
	// Allows label and field based indexes in apiserver watch cache to accelerate list operations.
	SelectorIndex featuregate.Feature = "SelectorIndex"

	// owner: @liggitt
	// beta: v1.19
	//
	// Allows sending warning headers in API responses.
	WarningHeaders featuregate.Feature = "WarningHeaders"

	// owner: @wojtek-t
	// alpha: v1.20
	// beta: v1.21
	//
	// Allows for updating watchcache resource version with progress notify events.
	EfficientWatchResumption featuregate.Feature = "EfficientWatchResumption"

	// owner: @roycaihw
	// alpha: v1.20
	//
	// Assigns each kube-apiserver an ID in a cluster.
	APIServerIdentity featuregate.Feature = "APIServerIdentity"
)

func init() {
	runtime.Must(utilfeature.DefaultMutableFeatureGate.Add(defaultKubernetesFeatureGates))
}

// defaultKubernetesFeatureGates consists of all known Kubernetes-specific feature keys.
// To add a new feature, define a key for it above and add it here. The features will be
// available throughout Kubernetes binaries.
var defaultKubernetesFeatureGates = map[featuregate.Feature]featuregate.FeatureSpec{
	StreamingProxyRedirects:  {Default: true, PreRelease: featuregate.Deprecated},
	ValidateProxyRedirects:   {Default: true, PreRelease: featuregate.Beta},
	AdvancedAuditing:         {Default: true, PreRelease: featuregate.GA},
	APIResponseCompression:   {Default: true, PreRelease: featuregate.Beta},
	APIListChunking:          {Default: true, PreRelease: featuregate.Beta},
	DryRun:                   {Default: true, PreRelease: featuregate.GA},
	RemainingItemCount:       {Default: true, PreRelease: featuregate.Beta},
	ServerSideApply:          {Default: true, PreRelease: featuregate.Beta},
	StorageVersionHash:       {Default: true, PreRelease: featuregate.Beta},
	StorageVersionAPI:        {Default: false, PreRelease: featuregate.Alpha},
	WatchBookmark:            {Default: true, PreRelease: featuregate.GA, LockToDefault: true},
	APIPriorityAndFairness:   {Default: true, PreRelease: featuregate.Beta},
	RemoveSelfLink:           {Default: true, PreRelease: featuregate.Beta},
	SelectorIndex:            {Default: true, PreRelease: featuregate.GA, LockToDefault: true},
	WarningHeaders:           {Default: true, PreRelease: featuregate.Beta},
	EfficientWatchResumption: {Default: true, PreRelease: featuregate.Beta},
	APIServerIdentity:        {Default: false, PreRelease: featuregate.Alpha},
}
<|endoftext|>


<commit_before>package main

import (
	"bufio"
	"fmt"
	jseg "github.com/garyhouston/jpegsegs"
	"log"
	"os"
)

// Print the JPEG markers and segment lengths, up to SOS.
func main() {
	if len(os.Args) != 2 {
		fmt.Printf("Usage: %s file\n", os.Args[0])
		return
	}
	in, err := os.Open(os.Args[1])
	if err != nil {
		log.Fatal(err)
	}
	defer in.Close()
	reader := bufio.NewReader(in)
	scanner, err := jseg.NewScanner(reader)
	if err != nil {
		log.Fatal(err)
	}
	for {
		marker, buf, err := scanner.Scan()
		if err != nil {
			log.Fatal(err)
		}
		if marker == jseg.SOS {
			fmt.Println(marker.Name())
			break
		}
		if marker == jseg.APP0+2 {
			isMPF, _ := jseg.GetMPFHeader(buf)
			if isMPF {
				fmt.Printf("%s, %d bytes (MPF segment)\n", marker.Name(), len(buf))
				continue
			}
		}
		fmt.Printf("%s, %d bytes\n", marker.Name(), len(buf))
	}
	buf := make([]byte, 10000)
	reset := 0
	total := 0
	for {
		var marker jseg.Marker
		var err error
		buf, marker, err = jseg.ReadImageData(reader, buf)
		if err != nil {
			log.Fatal(err)
		}
		total += len(buf)
		if marker >= jseg.RST0 && marker <= jseg.RST0+7 {
			reset++
		} else if marker == jseg.EOI {
			fmt.Printf("%d bytes of scan data and %d reset markers\n", total, reset)
			fmt.Println(marker.Name())
			break
		} else {
			fmt.Printf("%s, unexpected marker\n", marker.Name())
		}
	}
}
<commit_msg>Adjust for SOS change in library.<commit_after>package main

import (
	"bufio"
	"fmt"
	jseg "github.com/garyhouston/jpegsegs"
	"log"
	"os"
)

// Print the JPEG markers and segment lengths, up to SOS.
func main() {
	if len(os.Args) != 2 {
		fmt.Printf("Usage: %s file\n", os.Args[0])
		return
	}
	in, err := os.Open(os.Args[1])
	if err != nil {
		log.Fatal(err)
	}
	defer in.Close()
	reader := bufio.NewReader(in)
	scanner, err := jseg.NewScanner(reader)
	if err != nil {
		log.Fatal(err)
	}
	for {
		marker, buf, err := scanner.Scan()
		if err != nil {
			log.Fatal(err)
		}
		if marker == jseg.APP0+2 {
			isMPF, _ := jseg.GetMPFHeader(buf)
			if isMPF {
				fmt.Printf("%s, %d bytes (MPF segment)\n", marker.Name(), len(buf))
				continue
			}
		}
		fmt.Printf("%s, %d bytes\n", marker.Name(), len(buf))
		if marker == jseg.SOS {
			break
		}
	}
	buf := make([]byte, 10000)
	reset := 0
	total := 0
	for {
		var marker jseg.Marker
		var err error
		buf, marker, err = jseg.ReadImageData(reader, buf)
		if err != nil {
			log.Fatal(err)
		}
		total += len(buf)
		if marker >= jseg.RST0 && marker <= jseg.RST0+7 {
			reset++
		} else if marker == jseg.EOI {
			fmt.Printf("%d bytes of scan data and %d reset markers\n", total, reset)
			fmt.Println(marker.Name())
			break
		} else {
			fmt.Printf("%s, unexpected marker\n", marker.Name())
		}
	}
}
<|endoftext|>


<commit_before>/*
Copyright 2020 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 features

import (
	"k8s.io/component-base/featuregate"
)

const (
	// Every feature gate should add method here following this template:
	//
	// // owner: @username
	// // alpha: v1.4
	// MyFeature() bool

	// owner: @khenidak
	// alpha: v1.15
	//
	// Enables ipv6 dual stack
	// Original copy from k8s.io/kubernetes/pkg/features/kube_features.go
	IPv6DualStack featuregate.Feature = "IPv6DualStack"

	// owner: @jiahuif
	// alpha: v1.21
	//
	// Enables Leader Migration for kube-controller-manager and cloud-controller-manager
	ControllerManagerLeaderMigration featuregate.Feature = "ControllerManagerLeaderMigration"
)

func SetupCurrentKubernetesSpecificFeatureGates(featuregates featuregate.MutableFeatureGate) error {
	return featuregates.Add(cloudPublicFeatureGates)
}

// cloudPublicFeatureGates consists of cloud-specific feature keys.
// To add a new feature, define a key for it at k8s.io/api/pkg/features and add it here.
var cloudPublicFeatureGates = map[featuregate.Feature]featuregate.FeatureSpec{
	IPv6DualStack:                    {Default: true, PreRelease: featuregate.Beta},
	ControllerManagerLeaderMigration: {Default: false, PreRelease: featuregate.Alpha},
}
<commit_msg>promote ControllerManagerLeaderMigration to beta.<commit_after>/*
Copyright 2020 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 features

import (
	"k8s.io/component-base/featuregate"
)

const (
	// Every feature gate should add method here following this template:
	//
	// // owner: @username
	// // alpha: v1.4
	// MyFeature() bool

	// owner: @khenidak
	// alpha: v1.15
	//
	// Enables ipv6 dual stack
	// Original copy from k8s.io/kubernetes/pkg/features/kube_features.go
	IPv6DualStack featuregate.Feature = "IPv6DualStack"

	// owner: @jiahuif
	// alpha: v1.21
	// beta:  v1.22
	//
	// Enables Leader Migration for kube-controller-manager and cloud-controller-manager
	// copied and sync'ed from k8s.io/kubernetes/pkg/features/kube_features.go
	ControllerManagerLeaderMigration featuregate.Feature = "ControllerManagerLeaderMigration"
)

func SetupCurrentKubernetesSpecificFeatureGates(featuregates featuregate.MutableFeatureGate) error {
	return featuregates.Add(cloudPublicFeatureGates)
}

// cloudPublicFeatureGates consists of cloud-specific feature keys.
// To add a new feature, define a key for it at k8s.io/api/pkg/features and add it here.
var cloudPublicFeatureGates = map[featuregate.Feature]featuregate.FeatureSpec{
	IPv6DualStack:                    {Default: true, PreRelease: featuregate.Beta},
	ControllerManagerLeaderMigration: {Default: true, PreRelease: featuregate.Beta},
}
<|endoftext|>


<commit_before>/*
Copyright 2014 The Kubernetes Authors All rights reserved.

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

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

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

package kubelet

import (
	"fmt"
	"reflect"
	"sync"

	"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/client"
	kubecontainer "github.com/GoogleCloudPlatform/kubernetes/pkg/kubelet/container"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/util"
	"github.com/golang/glog"
)

type podStatusSyncRequest struct {
	pod    *api.Pod
	status api.PodStatus
}

// Updates pod statuses in apiserver. Writes only when new status has changed.
// All methods are thread-safe.
type statusManager struct {
	kubeClient client.Interface
	// Map from pod full name to sync status of the corresponding pod.
	podStatusesLock  sync.RWMutex
	podStatuses      map[string]api.PodStatus
	podStatusChannel chan podStatusSyncRequest
}

func newStatusManager(kubeClient client.Interface) *statusManager {
	return &statusManager{
		kubeClient:       kubeClient,
		podStatuses:      make(map[string]api.PodStatus),
		podStatusChannel: make(chan podStatusSyncRequest, 1000), // Buffer up to 1000 statuses
	}
}

func (s *statusManager) Start() {
	// syncBatch blocks when no updates are available, we can run it in a tight loop.
	glog.Info("Starting to sync pod status with apiserver")
	go util.Forever(func() {
		err := s.syncBatch()
		if err != nil {
			glog.Warningf("Failed to updated pod status: %v", err)
		}
	}, 0)
}

func (s *statusManager) GetPodStatus(podFullName string) (api.PodStatus, bool) {
	s.podStatusesLock.RLock()
	defer s.podStatusesLock.RUnlock()
	status, ok := s.podStatuses[podFullName]
	return status, ok
}

func (s *statusManager) SetPodStatus(pod *api.Pod, status api.PodStatus) {
	podFullName := kubecontainer.GetPodFullName(pod)
	s.podStatusesLock.Lock()
	defer s.podStatusesLock.Unlock()
	oldStatus, found := s.podStatuses[podFullName]

	// ensure that the start time does not change across updates.
	if found && oldStatus.StartTime != nil {
		status.StartTime = oldStatus.StartTime
	}

	// if the status has no start time, we need to set an initial time
	// TODO(yujuhong): Consider setting StartTime when generating the pod
	// status instead, which would allow statusManager to become a simple cache
	// again.
	if status.StartTime.IsZero() {
		if pod.Status.StartTime.IsZero() {
			// the pod did not have a previously recorded value so set to now
			now := util.Now()
			status.StartTime = &now
		} else {
			// the pod had a recorded value, but the kubelet restarted so we need to rebuild cache
			// based on last observed value
			status.StartTime = pod.Status.StartTime
		}
	}

	if !found || !reflect.DeepEqual(oldStatus, status) {
		s.podStatuses[podFullName] = status
		s.podStatusChannel <- podStatusSyncRequest{pod, status}
	} else {
		glog.V(3).Infof("Ignoring same pod status for %s - old: %s new: %s", podFullName, oldStatus, status)
	}
}

func (s *statusManager) DeletePodStatus(podFullName string) {
	s.podStatusesLock.Lock()
	defer s.podStatusesLock.Unlock()
	delete(s.podStatuses, podFullName)
}

// TODO(filipg): It'd be cleaner if we can do this without signal from user.
func (s *statusManager) RemoveOrphanedStatuses(podFullNames map[string]bool) {
	s.podStatusesLock.Lock()
	defer s.podStatusesLock.Unlock()
	for key := range s.podStatuses {
		if _, ok := podFullNames[key]; !ok {
			glog.V(5).Infof("Removing %q from status map.", key)
			delete(s.podStatuses, key)
		}
	}
}

// syncBatch syncs pods statuses with the apiserver.
func (s *statusManager) syncBatch() error {
	syncRequest := <-s.podStatusChannel
	pod := syncRequest.pod
	podFullName := kubecontainer.GetPodFullName(pod)
	status := syncRequest.status

	var err error
	statusPod := &api.Pod{
		ObjectMeta: pod.ObjectMeta,
	}
	// TODO: make me easier to express from client code
	statusPod, err = s.kubeClient.Pods(statusPod.Namespace).Get(statusPod.Name)
	if err == nil {
		statusPod.Status = status
		_, err = s.kubeClient.Pods(pod.Namespace).UpdateStatus(statusPod)
		// TODO: handle conflict as a retry, make that easier too.
		if err == nil {
			glog.V(3).Infof("Status for pod %q updated successfully", pod.Name)
			return nil
		}
	}

	// We failed to update status. In order to make sure we retry next time
	// we delete cached value. This may result in an additional update, but
	// this is ok.
	s.DeletePodStatus(podFullName)
	return fmt.Errorf("error updating status for pod %q: %v", pod.Name, err)
}
<commit_msg>Fix deadlock<commit_after>/*
Copyright 2014 The Kubernetes Authors All rights reserved.

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

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

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

package kubelet

import (
	"fmt"
	"reflect"
	"sync"

	"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/client"
	kubecontainer "github.com/GoogleCloudPlatform/kubernetes/pkg/kubelet/container"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/util"
	"github.com/golang/glog"
)

type podStatusSyncRequest struct {
	pod    *api.Pod
	status api.PodStatus
}

// Updates pod statuses in apiserver. Writes only when new status has changed.
// All methods are thread-safe.
type statusManager struct {
	kubeClient client.Interface
	// Map from pod full name to sync status of the corresponding pod.
	podStatusesLock  sync.RWMutex
	podStatuses      map[string]api.PodStatus
	podStatusChannel chan podStatusSyncRequest
}

func newStatusManager(kubeClient client.Interface) *statusManager {
	return &statusManager{
		kubeClient:       kubeClient,
		podStatuses:      make(map[string]api.PodStatus),
		podStatusChannel: make(chan podStatusSyncRequest, 1000), // Buffer up to 1000 statuses
	}
}

func (s *statusManager) Start() {
	// syncBatch blocks when no updates are available, we can run it in a tight loop.
	glog.Info("Starting to sync pod status with apiserver")
	go util.Forever(func() {
		err := s.syncBatch()
		if err != nil {
			glog.Warningf("Failed to updated pod status: %v", err)
		}
	}, 0)
}

func (s *statusManager) GetPodStatus(podFullName string) (api.PodStatus, bool) {
	s.podStatusesLock.RLock()
	defer s.podStatusesLock.RUnlock()
	status, ok := s.podStatuses[podFullName]
	return status, ok
}

func (s *statusManager) SetPodStatus(pod *api.Pod, status api.PodStatus) {
	podFullName := kubecontainer.GetPodFullName(pod)
	s.podStatusesLock.Lock()
	defer s.podStatusesLock.Unlock()
	oldStatus, found := s.podStatuses[podFullName]

	// ensure that the start time does not change across updates.
	if found && oldStatus.StartTime != nil {
		status.StartTime = oldStatus.StartTime
	}

	// if the status has no start time, we need to set an initial time
	// TODO(yujuhong): Consider setting StartTime when generating the pod
	// status instead, which would allow statusManager to become a simple cache
	// again.
	if status.StartTime.IsZero() {
		if pod.Status.StartTime.IsZero() {
			// the pod did not have a previously recorded value so set to now
			now := util.Now()
			status.StartTime = &now
		} else {
			// the pod had a recorded value, but the kubelet restarted so we need to rebuild cache
			// based on last observed value
			status.StartTime = pod.Status.StartTime
		}
	}

	// TODO: Holding a lock during blocking operations is dangerous. Refactor so this isn't necessary.
	// The intent here is to prevent concurrent updates to a pod's status from
	// clobbering each other so the phase of a pod progresses monotonically.
	// Currently this routine is not called for the same pod from multiple
	// workers and/or the kubelet but dropping the lock before sending the
	// status down the channel feels like an easy way to get a bullet in foot.
	if !found || !reflect.DeepEqual(oldStatus, status) {
		s.podStatuses[podFullName] = status
		s.podStatusChannel <- podStatusSyncRequest{pod, status}
	} else {
		glog.V(3).Infof("Ignoring same pod status for %s - old: %s new: %s", podFullName, oldStatus, status)
	}
}

func (s *statusManager) DeletePodStatus(podFullName string) {
	s.podStatusesLock.Lock()
	defer s.podStatusesLock.Unlock()
	delete(s.podStatuses, podFullName)
}

// TODO(filipg): It'd be cleaner if we can do this without signal from user.
func (s *statusManager) RemoveOrphanedStatuses(podFullNames map[string]bool) {
	s.podStatusesLock.Lock()
	defer s.podStatusesLock.Unlock()
	for key := range s.podStatuses {
		if _, ok := podFullNames[key]; !ok {
			glog.V(5).Infof("Removing %q from status map.", key)
			delete(s.podStatuses, key)
		}
	}
}

// syncBatch syncs pods statuses with the apiserver.
func (s *statusManager) syncBatch() error {
	syncRequest := <-s.podStatusChannel
	pod := syncRequest.pod
	podFullName := kubecontainer.GetPodFullName(pod)
	status := syncRequest.status

	var err error
	statusPod := &api.Pod{
		ObjectMeta: pod.ObjectMeta,
	}
	// TODO: make me easier to express from client code
	statusPod, err = s.kubeClient.Pods(statusPod.Namespace).Get(statusPod.Name)
	if err == nil {
		statusPod.Status = status
		_, err = s.kubeClient.Pods(pod.Namespace).UpdateStatus(statusPod)
		// TODO: handle conflict as a retry, make that easier too.
		if err == nil {
			glog.V(3).Infof("Status for pod %q updated successfully", pod.Name)
			return nil
		}
	}

	// We failed to update status. In order to make sure we retry next time
	// we delete cached value. This may result in an additional update, but
	// this is ok.
	// Doing this synchronously will lead to a deadlock if the podStatusChannel
	// is full, and the pod worker holding the lock is waiting on this method
	// to clear the channel. Even if this delete never runs subsequent container
	// changes on the node should trigger updates.
	go s.DeletePodStatus(podFullName)
	return fmt.Errorf("error updating status for pod %q: %v", pod.Name, err)
}
<|endoftext|>


<commit_before>// +build linux solaris darwin freebsd

package lockfile

import (
	"fmt"
	"os"
	"path/filepath"
	"sync"
	"time"

	"github.com/containers/storage/pkg/stringid"
	"github.com/containers/storage/pkg/system"
	"github.com/pkg/errors"
	"golang.org/x/sys/unix"
)

type lockfile struct {
	// rwMutex serializes concurrent reader-writer acquisitions in the same process space
	rwMutex *sync.RWMutex
	// stateMutex is used to synchronize concurrent accesses to the state below
	stateMutex *sync.Mutex
	counter    int64
	file       string
	fd         uintptr
	lw         string
	locktype   int16
	locked     bool
	ro         bool
	recursive  bool
}

// openLock opens the file at path and returns the corresponding file
// descriptor.  Note that the path is opened read-only when ro is set.  If ro
// is unset, openLock will open the path read-write and create the file if
// necessary.
func openLock(path string, ro bool) (fd int, err error) {
	if ro {
		fd, err = unix.Open(path, os.O_RDONLY|unix.O_CLOEXEC, 0)
	} else {
		fd, err = unix.Open(path,
			os.O_RDWR|unix.O_CLOEXEC|os.O_CREATE,
			unix.S_IRUSR|unix.S_IWUSR|unix.S_IRGRP|unix.S_IROTH,
		)
	}

	if err == nil {
		return
	}

	// the directory of the lockfile seems to be removed, try to create it
	if os.IsNotExist(err) {
		if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
			return fd, errors.Wrap(err, "creating locker directory")
		}

		return openLock(path, ro)
	}

	return
}

// createLockerForPath returns a Locker object, possibly (depending on the platform)
// working inter-process and associated with the specified path.
//
// This function will be called at most once for each path value within a single process.
//
// If ro, the lock is a read-write lock and the returned Locker should correspond to the
// “lock for reading” (shared) operation; otherwise, the lock is either an exclusive lock,
// or a read-write lock and Locker should correspond to the “lock for writing” (exclusive) operation.
//
// WARNING:
// - The lock may or MAY NOT be inter-process.
// - There may or MAY NOT be an actual object on the filesystem created for the specified path.
// - Even if ro, the lock MAY be exclusive.
func createLockerForPath(path string, ro bool) (Locker, error) {
	// Check if we can open the lock.
	fd, err := openLock(path, ro)
	if err != nil {
		return nil, errors.Wrapf(err, "error opening %q", path)
	}
	unix.Close(fd)

	locktype := unix.F_WRLCK
	if ro {
		locktype = unix.F_RDLCK
	}
	return &lockfile{
		stateMutex: &sync.Mutex{},
		rwMutex:    &sync.RWMutex{},
		file:       path,
		lw:         stringid.GenerateRandomID(),
		locktype:   int16(locktype),
		locked:     false,
		ro:         ro}, nil
}

// lock locks the lockfile via FCTNL(2) based on the specified type and
// command.
func (l *lockfile) lock(lType int16, recursive bool) {
	lk := unix.Flock_t{
		Type:   lType,
		Whence: int16(os.SEEK_SET),
		Start:  0,
		Len:    0,
	}
	switch lType {
	case unix.F_RDLCK:
		l.rwMutex.RLock()
	case unix.F_WRLCK:
		if recursive {
			// NOTE: that's okay as recursive is only set in RecursiveLock(), so
			// there's no need to protect against hypothetical RDLCK cases.
			l.rwMutex.RLock()
		} else {
			l.rwMutex.Lock()
		}
	default:
		panic(fmt.Sprintf("attempted to acquire a file lock of unrecognized type %d", lType))
	}
	l.stateMutex.Lock()
	defer l.stateMutex.Unlock()
	if l.counter == 0 {
		// If we're the first reference on the lock, we need to open the file again.
		fd, err := openLock(l.file, l.ro)
		if err != nil {
			panic(fmt.Sprintf("error opening %q: %v", l.file, err))
		}
		l.fd = uintptr(fd)

		// Optimization: only use the (expensive) fcntl syscall when
		// the counter is 0.  In this case, we're either the first
		// reader lock or a writer lock.
		for unix.FcntlFlock(l.fd, unix.F_SETLKW, &lk) != nil {
			time.Sleep(10 * time.Millisecond)
		}
	}
	l.locktype = lType
	l.locked = true
	l.recursive = recursive
	l.counter++
}

// Lock locks the lockfile as a writer.  Panic if the lock is a read-only one.
func (l *lockfile) Lock() {
	if l.ro {
		panic("can't take write lock on read-only lock file")
	} else {
		l.lock(unix.F_WRLCK, false)
	}
}

// RecursiveLock locks the lockfile as a writer but allows for recursive
// acquisitions within the same process space.  Note that RLock() will be called
// if it's a lockTypReader lock.
func (l *lockfile) RecursiveLock() {
	if l.ro {
		l.RLock()
	} else {
		l.lock(unix.F_WRLCK, true)
	}
}

// LockRead locks the lockfile as a reader.
func (l *lockfile) RLock() {
	l.lock(unix.F_RDLCK, false)
}

// Unlock unlocks the lockfile.
func (l *lockfile) Unlock() {
	l.stateMutex.Lock()
	if l.locked == false {
		// Panic when unlocking an unlocked lock.  That's a violation
		// of the lock semantics and will reveal such.
		panic("calling Unlock on unlocked lock")
	}
	l.counter--
	if l.counter < 0 {
		// Panic when the counter is negative.  There is no way we can
		// recover from a corrupted lock and we need to protect the
		// storage from corruption.
		panic(fmt.Sprintf("lock %q has been unlocked too often", l.file))
	}
	if l.counter == 0 {
		// We should only release the lock when the counter is 0 to
		// avoid releasing read-locks too early; a given process may
		// acquire a read lock multiple times.
		l.locked = false
		// Close the file descriptor on the last unlock, releasing the
		// file lock.
		unix.Close(int(l.fd))
	}
	if l.locktype == unix.F_RDLCK || l.recursive {
		l.rwMutex.RUnlock()
	} else {
		l.rwMutex.Unlock()
	}
	l.stateMutex.Unlock()
}

// Locked checks if lockfile is locked for writing by a thread in this process.
func (l *lockfile) Locked() bool {
	l.stateMutex.Lock()
	defer l.stateMutex.Unlock()
	return l.locked && (l.locktype == unix.F_WRLCK)
}

// Touch updates the lock file with the UID of the user.
func (l *lockfile) Touch() error {
	l.stateMutex.Lock()
	if !l.locked || (l.locktype != unix.F_WRLCK) {
		panic("attempted to update last-writer in lockfile without the write lock")
	}
	defer l.stateMutex.Unlock()
	l.lw = stringid.GenerateRandomID()
	id := []byte(l.lw)
	n, err := unix.Pwrite(int(l.fd), id, 0)
	if err != nil {
		return err
	}
	if n != len(id) {
		return unix.ENOSPC
	}
	return nil
}

// Modified indicates if the lockfile has been updated since the last time it
// was loaded.
func (l *lockfile) Modified() (bool, error) {
	l.stateMutex.Lock()
	id := []byte(l.lw)
	if !l.locked {
		panic("attempted to check last-writer in lockfile without locking it first")
	}
	defer l.stateMutex.Unlock()
	n, err := unix.Pread(int(l.fd), id, 0)
	if err != nil {
		return true, err
	}
	if n != len(id) {
		return true, nil
	}
	lw := l.lw
	l.lw = string(id)
	return l.lw != lw, nil
}

// IsReadWriteLock indicates if the lock file is a read-write lock.
func (l *lockfile) IsReadWrite() bool {
	return !l.ro
}

// TouchedSince indicates if the lock file has been touched since the specified time
func (l *lockfile) TouchedSince(when time.Time) bool {
	st, err := system.Fstat(int(l.fd))
	if err != nil {
		return true
	}
	mtim := st.Mtim()
	touched := time.Unix(mtim.Unix())
	return when.Before(touched)
}
<commit_msg>Create readonly locks if the lockfile does not exists<commit_after>// +build linux solaris darwin freebsd

package lockfile

import (
	"fmt"
	"os"
	"path/filepath"
	"sync"
	"time"

	"github.com/containers/storage/pkg/stringid"
	"github.com/containers/storage/pkg/system"
	"github.com/pkg/errors"
	"golang.org/x/sys/unix"
)

type lockfile struct {
	// rwMutex serializes concurrent reader-writer acquisitions in the same process space
	rwMutex *sync.RWMutex
	// stateMutex is used to synchronize concurrent accesses to the state below
	stateMutex *sync.Mutex
	counter    int64
	file       string
	fd         uintptr
	lw         string
	locktype   int16
	locked     bool
	ro         bool
	recursive  bool
}

// openLock opens the file at path and returns the corresponding file
// descriptor.  Note that the path is opened read-only when ro is set.  If ro
// is unset, openLock will open the path read-write and create the file if
// necessary.
func openLock(path string, ro bool) (fd int, err error) {
	if ro {
		fd, err = unix.Open(path, os.O_RDONLY|unix.O_CLOEXEC|os.O_CREATE, 0)
	} else {
		fd, err = unix.Open(path,
			os.O_RDWR|unix.O_CLOEXEC|os.O_CREATE,
			unix.S_IRUSR|unix.S_IWUSR|unix.S_IRGRP|unix.S_IROTH,
		)
	}

	if err == nil {
		return
	}

	// the directory of the lockfile seems to be removed, try to create it
	if os.IsNotExist(err) {
		if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
			return fd, errors.Wrap(err, "creating locker directory")
		}

		return openLock(path, ro)
	}

	return
}

// createLockerForPath returns a Locker object, possibly (depending on the platform)
// working inter-process and associated with the specified path.
//
// This function will be called at most once for each path value within a single process.
//
// If ro, the lock is a read-write lock and the returned Locker should correspond to the
// “lock for reading” (shared) operation; otherwise, the lock is either an exclusive lock,
// or a read-write lock and Locker should correspond to the “lock for writing” (exclusive) operation.
//
// WARNING:
// - The lock may or MAY NOT be inter-process.
// - There may or MAY NOT be an actual object on the filesystem created for the specified path.
// - Even if ro, the lock MAY be exclusive.
func createLockerForPath(path string, ro bool) (Locker, error) {
	// Check if we can open the lock.
	fd, err := openLock(path, ro)
	if err != nil {
		return nil, errors.Wrapf(err, "error opening %q", path)
	}
	unix.Close(fd)

	locktype := unix.F_WRLCK
	if ro {
		locktype = unix.F_RDLCK
	}
	return &lockfile{
		stateMutex: &sync.Mutex{},
		rwMutex:    &sync.RWMutex{},
		file:       path,
		lw:         stringid.GenerateRandomID(),
		locktype:   int16(locktype),
		locked:     false,
		ro:         ro}, nil
}

// lock locks the lockfile via FCTNL(2) based on the specified type and
// command.
func (l *lockfile) lock(lType int16, recursive bool) {
	lk := unix.Flock_t{
		Type:   lType,
		Whence: int16(os.SEEK_SET),
		Start:  0,
		Len:    0,
	}
	switch lType {
	case unix.F_RDLCK:
		l.rwMutex.RLock()
	case unix.F_WRLCK:
		if recursive {
			// NOTE: that's okay as recursive is only set in RecursiveLock(), so
			// there's no need to protect against hypothetical RDLCK cases.
			l.rwMutex.RLock()
		} else {
			l.rwMutex.Lock()
		}
	default:
		panic(fmt.Sprintf("attempted to acquire a file lock of unrecognized type %d", lType))
	}
	l.stateMutex.Lock()
	defer l.stateMutex.Unlock()
	if l.counter == 0 {
		// If we're the first reference on the lock, we need to open the file again.
		fd, err := openLock(l.file, l.ro)
		if err != nil {
			panic(fmt.Sprintf("error opening %q: %v", l.file, err))
		}
		l.fd = uintptr(fd)

		// Optimization: only use the (expensive) fcntl syscall when
		// the counter is 0.  In this case, we're either the first
		// reader lock or a writer lock.
		for unix.FcntlFlock(l.fd, unix.F_SETLKW, &lk) != nil {
			time.Sleep(10 * time.Millisecond)
		}
	}
	l.locktype = lType
	l.locked = true
	l.recursive = recursive
	l.counter++
}

// Lock locks the lockfile as a writer.  Panic if the lock is a read-only one.
func (l *lockfile) Lock() {
	if l.ro {
		panic("can't take write lock on read-only lock file")
	} else {
		l.lock(unix.F_WRLCK, false)
	}
}

// RecursiveLock locks the lockfile as a writer but allows for recursive
// acquisitions within the same process space.  Note that RLock() will be called
// if it's a lockTypReader lock.
func (l *lockfile) RecursiveLock() {
	if l.ro {
		l.RLock()
	} else {
		l.lock(unix.F_WRLCK, true)
	}
}

// LockRead locks the lockfile as a reader.
func (l *lockfile) RLock() {
	l.lock(unix.F_RDLCK, false)
}

// Unlock unlocks the lockfile.
func (l *lockfile) Unlock() {
	l.stateMutex.Lock()
	if l.locked == false {
		// Panic when unlocking an unlocked lock.  That's a violation
		// of the lock semantics and will reveal such.
		panic("calling Unlock on unlocked lock")
	}
	l.counter--
	if l.counter < 0 {
		// Panic when the counter is negative.  There is no way we can
		// recover from a corrupted lock and we need to protect the
		// storage from corruption.
		panic(fmt.Sprintf("lock %q has been unlocked too often", l.file))
	}
	if l.counter == 0 {
		// We should only release the lock when the counter is 0 to
		// avoid releasing read-locks too early; a given process may
		// acquire a read lock multiple times.
		l.locked = false
		// Close the file descriptor on the last unlock, releasing the
		// file lock.
		unix.Close(int(l.fd))
	}
	if l.locktype == unix.F_RDLCK || l.recursive {
		l.rwMutex.RUnlock()
	} else {
		l.rwMutex.Unlock()
	}
	l.stateMutex.Unlock()
}

// Locked checks if lockfile is locked for writing by a thread in this process.
func (l *lockfile) Locked() bool {
	l.stateMutex.Lock()
	defer l.stateMutex.Unlock()
	return l.locked && (l.locktype == unix.F_WRLCK)
}

// Touch updates the lock file with the UID of the user.
func (l *lockfile) Touch() error {
	l.stateMutex.Lock()
	if !l.locked || (l.locktype != unix.F_WRLCK) {
		panic("attempted to update last-writer in lockfile without the write lock")
	}
	defer l.stateMutex.Unlock()
	l.lw = stringid.GenerateRandomID()
	id := []byte(l.lw)
	n, err := unix.Pwrite(int(l.fd), id, 0)
	if err != nil {
		return err
	}
	if n != len(id) {
		return unix.ENOSPC
	}
	return nil
}

// Modified indicates if the lockfile has been updated since the last time it
// was loaded.
func (l *lockfile) Modified() (bool, error) {
	l.stateMutex.Lock()
	id := []byte(l.lw)
	if !l.locked {
		panic("attempted to check last-writer in lockfile without locking it first")
	}
	defer l.stateMutex.Unlock()
	n, err := unix.Pread(int(l.fd), id, 0)
	if err != nil {
		return true, err
	}
	if n != len(id) {
		return true, nil
	}
	lw := l.lw
	l.lw = string(id)
	return l.lw != lw, nil
}

// IsReadWriteLock indicates if the lock file is a read-write lock.
func (l *lockfile) IsReadWrite() bool {
	return !l.ro
}

// TouchedSince indicates if the lock file has been touched since the specified time
func (l *lockfile) TouchedSince(when time.Time) bool {
	st, err := system.Fstat(int(l.fd))
	if err != nil {
		return true
	}
	mtim := st.Mtim()
	touched := time.Unix(mtim.Unix())
	return when.Before(touched)
}
<|endoftext|>