<commit_before>package config

import (
	"encoding/json"
	"strings"

	"github.com/ondevice/ondevice/config/internal"
	"github.com/sirupsen/logrus"
)

// migrateAuth -- move stuff from ondevice.conf to auth.json
func (c Config) migrateAuth() error {
	if !c.HasKey("device", "auth") && !c.HasKey("client", "auth") {
		return nil // doesn't have auth
	}
	logrus.Info("migrating auth info to auth.json")
	// TODO remove old auth once we're confident things work as expected

	// target configurations
	var auth internal.AuthJSON
	var err error

	// chain getValue calls until the first error happened
	var getValue = func(olderr error, section, key string) (string, error) {
		if olderr != nil {
			return "", olderr
		}
		return c.GetString(section, key)
	}

	var getOrDefault = func(section, key, defaultValue string) string {
		if s := c.cfg.Section(section); s != nil {
			if k := s.Key(key); k != nil {
				return k.String()
			}
		}
		return defaultValue
	}

	// device auth
	auth.Device = internal.AuthEntry{
		UserField: getOrDefault("device", "user", ""),
		KeyField:  getOrDefault("device", "auth", ""),
		DeviceKey: getOrDefault("device", "key", ""),
	}

	// client section
	var extraClients []internal.AuthEntry
	for key, val := range c.AllValues() {
		if strings.HasPrefix(strings.ToLower(key), "client.auth_") {
			var username = key[len("client.auth_"):]

			if len(username) == 0 || len(val) == 0 {
				logrus.Fatalf("found empty auth data for key '%s'", key)
			}
			extraClients = append(extraClients, internal.AuthEntry{
				UserField: username,
				KeyField:  val,
			})
		}
	}
	auth.ExtraClients = extraClients

	auth.Client.UserField, err = getValue(err, "client", "user")
	auth.Client.KeyField, err = getValue(err, "client", "auth")
	if err != nil {
		logrus.WithError(err).Fatal("failed to convert client config")
		return err
	}

	// TODO apply overrides
	var data []byte
	if data, err = json.Marshal(auth); err != nil {
		logrus.WithError(err).Fatal("failed to marshal auth.json")
	}

	// TODO remove old auth from ondevice.conf

	// TODO use auth.Write()
	if err = internal.WriteFile(data, c.GetFilePath("auth.json"), 0o600); err != nil {
		logrus.WithError(err).Fatal("migrateConfig(): failed to write auth.json")
		return err
	}

	return nil
}
<commit_msg>migrateAuth(): added some override code<commit_after>package config

import (
	"encoding/json"
	"os"
	"strings"

	"github.com/ondevice/ondevice/config/internal"
	"github.com/sirupsen/logrus"
)

// migrateAuth -- move stuff from ondevice.conf to auth.json
func (c Config) migrateAuth() error {
	if !c.HasKey("device", "auth") && !c.HasKey("client", "auth") {
		return nil // doesn't have auth
	}
	logrus.Info("migrating auth info to auth.json")
	// TODO remove old auth once we're confident things work as expected

	// target configurations
	var auth internal.AuthJSON
	var err error

	// chain getValue calls until the first error happened
	var getValue = func(olderr error, section, key string) (string, error) {
		if olderr != nil {
			return "", olderr
		}
		return c.GetString(section, key)
	}

	var getOrDefault = func(section, key, defaultValue string) string {
		if s := c.cfg.Section(section); s != nil {
			if k := s.Key(key); k != nil {
				return k.String()
			}
		}
		return defaultValue
	}

	// device auth
	auth.Device = internal.AuthEntry{
		UserField: getOrDefault("device", "user", ""),
		KeyField:  getOrDefault("device", "auth", ""),
		DeviceKey: getOrDefault("device", "key", ""),
	}

	// client section
	var extraClients []internal.AuthEntry
	for key, val := range c.AllValues() {
		if strings.HasPrefix(strings.ToLower(key), "client.auth_") {
			var username = key[len("client.auth_"):]

			if len(username) == 0 || len(val) == 0 {
				logrus.Fatalf("found empty auth data for key '%s'", key)
			}
			extraClients = append(extraClients, internal.AuthEntry{
				UserField: username,
				KeyField:  val,
			})
		}
	}
	auth.ExtraClients = extraClients

	auth.Client.UserField, err = getValue(err, "client", "user")
	auth.Client.KeyField, err = getValue(err, "client", "auth")
	if err != nil {
		logrus.WithError(err).Fatal("failed to convert client config")
		return err
	}

	if user, pw := os.Getenv("ONDEVICE_USER"), os.Getenv("ONDEVICE_AUTH"); user != "" || pw != "" {
		// apply overrides
		if auth.Device.UserField != "" || auth.Device.KeyField != "" {
			// TODO think about how to behave here
			logrus.Fatal("migrateAuth(): got both device.user/device.auth and ONDEVICE_USER/ONDEVICE_AUTH")
		}
		auth.Device.UserField = user
		auth.Device.KeyField = pw

		// TODO should we also apply them to .Client?
	}

	var data []byte
	if data, err = json.Marshal(auth); err != nil {
		logrus.WithError(err).Fatal("failed to marshal auth.json")
	}

	// TODO remove old auth from ondevice.conf

	// TODO use auth.Write()
	if err = internal.WriteFile(data, c.GetFilePath("auth.json"), 0o600); err != nil {
		logrus.WithError(err).Fatal("migrateConfig(): failed to write auth.json")
		return err
	}

	return nil
}
<|endoftext|>


<commit_before>// Copyright 2015 Google Inc. 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 inode

import (
	"fmt"
	"os"
	"path"

	"github.com/jacobsa/fuse"
	"github.com/jacobsa/fuse/fuseops"
	"github.com/jacobsa/fuse/fuseutil"
	"github.com/jacobsa/gcloud/gcs"
	"github.com/jacobsa/gcloud/syncutil"
	"golang.org/x/net/context"
)

type DirInode struct {
	/////////////////////////
	// Dependencies
	/////////////////////////

	bucket gcs.Bucket

	/////////////////////////
	// Constant data
	/////////////////////////

	id           fuseops.InodeID
	implicitDirs bool

	// The the GCS object backing the inode. The object's name is used as a
	// prefix when listing. Special case: the empty string means this is the root
	// inode.
	//
	// INVARIANT: src != nil
	// INVARIANT: src.Name == "" || src.Name[len(name)-1] == '/'
	src gcs.Object
}

var _ Inode = &DirInode{}

// Set notes on NewRootInode.
const RootGen int64 = 0

// Create a directory inode for the root of the file system. For this inode,
// the result of SourceGeneration() is guaranteed to be RootGen.
func NewRootInode(
	bucket gcs.Bucket,
	implicitDirs bool) (d *DirInode) {
	dummy := &gcs.Object{
		Name:       "",
		Generation: RootGen,
	}

	d = NewDirInode(bucket, fuseops.RootInodeID, dummy, implicitDirs)
	return
}

// Create a directory inode for the supplied source object. The object's name
// must end with a slash unless this is the root directory, in which case it
// must be empty.
//
// If implicitDirs is set, LookUpChild will use ListObjects to find child
// directories that are "implicitly" defined by the existence of their own
// descendents. For example, if there is an object named "foo/bar/baz" and this
// is the directory "foo", a child directory named "bar" will be implied.
//
// REQUIRES: o != nil
// REQUIRES: o.Name == "" || o.Name[len(o.Name)-1] == '/'
func NewDirInode(
	bucket gcs.Bucket,
	id fuseops.InodeID,
	o *gcs.Object,
	implicitDirs bool) (d *DirInode) {
	if o.Name != "" && o.Name[len(o.Name)-1] != '/' {
		panic(fmt.Sprintf("Unexpected name: %s", o.Name))
	}

	// Set up the struct.
	d = &DirInode{
		bucket:       bucket,
		id:           id,
		implicitDirs: implicitDirs,
		src:          *o,
	}

	return
}

////////////////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////////////////

func (d *DirInode) checkInvariants() {
	// INVARIANT: src.Name == "" || src.Name[len(name)-1] == '/'
	if !(d.src.Name == "" || d.src.Name[len(d.src.Name)-1] == '/') {
		panic(fmt.Sprintf("Unexpected name: %s", d.src.Name))
	}
}

func (d *DirInode) clobbered(ctx context.Context) (clobbered bool, err error) {
	// Special case: the root is never clobbered.
	if d.ID() == fuseops.RootInodeID {
		return
	}

	// Stat the backing object.
	req := &gcs.StatObjectRequest{
		Name: d.Name(),
	}

	o, err := d.bucket.StatObject(ctx, req)

	// "Not found" means clobbered.
	if _, ok := err.(*gcs.NotFoundError); ok {
		clobbered = true
		err = nil
		return
	}

	// Propagate other errors.
	if err != nil {
		err = fmt.Errorf("StatObject: %v", err)
		return
	}

	// We are clobbered if the generation number has changed.
	clobbered = o.Generation != d.SourceGeneration()

	return
}

func (d *DirInode) lookUpChildFile(
	ctx context.Context,
	name string) (o *gcs.Object, err error) {
	o, err = statObjectMayNotExist(ctx, d.bucket, d.Name()+name)
	if err != nil {
		err = fmt.Errorf("statObjectMayNotExist: %v", err)
		return
	}

	return
}

func (d *DirInode) lookUpChildDir(
	ctx context.Context,
	name string) (o *gcs.Object, err error) {
	b := syncutil.NewBundle(ctx)

	// Stat the placeholder object.
	b.Add(func(ctx context.Context) (err error) {
		o, err = statObjectMayNotExist(ctx, d.bucket, d.Name()+name+"/")
		if err != nil {
			err = fmt.Errorf("statObjectMayNotExist: %v", err)
			return
		}

		return
	})

	// If implicit directories are enabled, find out whether the child name is
	// implicitly defined.
	var implicitlyDefined bool
	if d.implicitDirs {
		b.Add(func(ctx context.Context) (err error) {
			implicitlyDefined, err = objectNamePrefixNonEmpty(
				ctx,
				d.bucket,
				d.Name()+name+"/")

			if err != nil {
				err = fmt.Errorf("objectNamePrefixNonEmpty: %v", err)
				return
			}

			return
		})
	}

	// Wait for both.
	err = b.Join()
	if err != nil {
		return
	}

	// If statting failed by the directory is implicitly defined, fake a source
	// object.
	if o == nil && implicitlyDefined {
		o = &gcs.Object{
			Name:       d.Name() + name + "/",
			Generation: ImplicitDirGen,
		}
	}

	return
}

// List the supplied object name prefix to find out whether it is non-empty.
func objectNamePrefixNonEmpty(
	ctx context.Context,
	bucket gcs.Bucket,
	prefix string) (nonEmpty bool, err error) {
	req := &gcs.ListObjectsRequest{
		Prefix:     prefix,
		MaxResults: 1,
	}

	listing, err := bucket.ListObjects(ctx, req)
	if err != nil {
		err = fmt.Errorf("ListObjects: %v", err)
		return
	}

	nonEmpty = len(listing.Objects) != 0
	return
}

// Stat the object with the given name, returning (nil, nil) if the object
// doesn't exist rather than failing.
func statObjectMayNotExist(
	ctx context.Context,
	bucket gcs.Bucket,
	name string) (o *gcs.Object, err error) {
	// Call the bucket.
	req := &gcs.StatObjectRequest{
		Name: name,
	}

	o, err = bucket.StatObject(ctx, req)

	// Suppress "not found" errors.
	if _, ok := err.(*gcs.NotFoundError); ok {
		err = nil
	}

	// Annotate others.
	if err != nil {
		err = fmt.Errorf("StatObject: %v", err)
		return
	}

	return
}

////////////////////////////////////////////////////////////////////////
// Public interface
////////////////////////////////////////////////////////////////////////

func (d *DirInode) Lock() {
	// We don't require locks.
}

func (d *DirInode) Unlock() {
	// We don't require locks.
}

// Return the ID of this inode.
func (d *DirInode) ID() fuseops.InodeID {
	return d.id
}

// Return the full name of the directory object in GCS, including the trailing
// slash (e.g. "foo/bar/").
func (d *DirInode) Name() string {
	return d.src.Name
}

// Return the generation number from which this inode was branched.
func (d *DirInode) SourceGeneration() int64 {
	return d.src.Generation
}

func (d *DirInode) Attributes(
	ctx context.Context) (attrs fuseops.InodeAttributes, err error) {
	// Find out whether the backing object has been clobbered in GCS.
	clobbered, err := d.clobbered(ctx)
	if err != nil {
		err = fmt.Errorf("clobbered: %v", err)
		return
	}

	// Set up basic attributes.
	attrs = fuseops.InodeAttributes{
		Mode: 0700 | os.ModeDir,
	}

	// Modify Nlink as appropriate.
	if !clobbered {
		attrs.Nlink = 1
	}

	return
}

// See notes on DirInode.LookUpChild.
const ImplicitDirGen int64 = -1

// Look up the direct child with the given relative name, returning a record
// for the current object of that name in the GCS bucket. If both a file and a
// directory with the given name exist, be consistent from call to call about
// which is preferred. Return fuse.ENOENT if neither is found.
//
// If this inode was created with implicitDirs is set, this method will use
// ListObjects to find child directories that are "implicitly" defined by the
// existence of their own descendents. For example, if there is an object named
// "foo/bar/baz" and this is the directory "foo", a child directory named "bar"
// will be implied. In this case, the child's generation will be the sentinel
// value ImplicitDirGen.
func (d *DirInode) LookUpChild(
	ctx context.Context,
	name string) (o *gcs.Object, err error) {
	b := syncutil.NewBundle(ctx)

	// Stat the child as a file.
	var fileRecord *gcs.Object
	b.Add(func(ctx context.Context) (err error) {
		fileRecord, err = d.lookUpChildFile(ctx, name)
		return
	})

	// Stat the child as a directory.
	var dirRecord *gcs.Object
	b.Add(func(ctx context.Context) (err error) {
		dirRecord, err = d.lookUpChildDir(ctx, name)
		return
	})

	// Wait for both.
	err = b.Join()
	if err != nil {
		return
	}

	// Prefer directories over files.
	switch {
	case dirRecord != nil:
		o = dirRecord
	case fileRecord != nil:
		o = fileRecord
	default:
		err = fuse.ENOENT
	}

	return
}

// Read some number of entries from the directory, returning a continuation
// token that can be used to pick up the read operation where it left off.
// Supply the empty token on the first call.
//
// At the end of the directory, the returned continuation token will be empty.
// Otherwise it will be non-empty. There is no guarantee about the number of
// entries returned; it may be zero even with a non-empty continuation token.
//
// The contents of the Offset and Inode fields for returned entries is
// undefined.
func (d *DirInode) ReadEntries(
	ctx context.Context,
	tok string) (entries []fuseutil.Dirent, newTok string, err error) {
	// Ask the bucket to list some objects.
	req := &gcs.ListObjectsRequest{
		Delimiter:         "/",
		Prefix:            d.Name(),
		ContinuationToken: tok,
	}

	listing, err := d.bucket.ListObjects(ctx, req)
	if err != nil {
		err = fmt.Errorf("ListObjects: %v", err)
		return
	}

	// Convert objects to entries for files.
	for _, o := range listing.Objects {
		e := fuseutil.Dirent{
			Name: path.Base(o.Name),
			Type: fuseutil.DT_File,
		}

		entries = append(entries, e)
	}

	// Convert runs to entries for directories.
	for _, p := range listing.CollapsedRuns {
		e := fuseutil.Dirent{
			Name: path.Base(p),
			Type: fuseutil.DT_Directory,
		}

		entries = append(entries, e)
	}

	// Return an appropriate continuation token, if any.
	newTok = listing.ContinuationToken

	return
}
<commit_msg>Added lookup counts to DirInode.<commit_after>// Copyright 2015 Google Inc. 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 inode

import (
	"fmt"
	"os"
	"path"

	"github.com/jacobsa/fuse"
	"github.com/jacobsa/fuse/fuseops"
	"github.com/jacobsa/fuse/fuseutil"
	"github.com/jacobsa/gcloud/gcs"
	"github.com/jacobsa/gcloud/syncutil"
	"golang.org/x/net/context"
)

type DirInode struct {
	/////////////////////////
	// Dependencies
	/////////////////////////

	bucket gcs.Bucket

	/////////////////////////
	// Constant data
	/////////////////////////

	id           fuseops.InodeID
	implicitDirs bool

	// The the GCS object backing the inode. The object's name is used as a
	// prefix when listing. Special case: the empty string means this is the root
	// inode.
	//
	// INVARIANT: src != nil
	// INVARIANT: src.Name == "" || src.Name[len(name)-1] == '/'
	src gcs.Object

	/////////////////////////
	// Mutable state
	/////////////////////////

	lc lookupCount
}

var _ Inode = &DirInode{}

// Set notes on NewRootInode.
const RootGen int64 = 0

// Create a directory inode for the root of the file system. For this inode,
// the result of SourceGeneration() is guaranteed to be RootGen.
//
// The initial lookup count is one.
func NewRootInode(
	bucket gcs.Bucket,
	implicitDirs bool) (d *DirInode) {
	dummy := &gcs.Object{
		Name:       "",
		Generation: RootGen,
	}

	d = NewDirInode(bucket, fuseops.RootInodeID, dummy, implicitDirs)
	return
}

// Create a directory inode for the supplied source object. The object's name
// must end with a slash unless this is the root directory, in which case it
// must be empty.
//
// If implicitDirs is set, LookUpChild will use ListObjects to find child
// directories that are "implicitly" defined by the existence of their own
// descendents. For example, if there is an object named "foo/bar/baz" and this
// is the directory "foo", a child directory named "bar" will be implied.
//
// The initial lookup count is one.
//
// REQUIRES: o != nil
// REQUIRES: o.Name == "" || o.Name[len(o.Name)-1] == '/'
func NewDirInode(
	bucket gcs.Bucket,
	id fuseops.InodeID,
	o *gcs.Object,
	implicitDirs bool) (d *DirInode) {
	if o.Name != "" && o.Name[len(o.Name)-1] != '/' {
		panic(fmt.Sprintf("Unexpected name: %s", o.Name))
	}

	// Set up the struct.
	d = &DirInode{
		bucket:       bucket,
		id:           id,
		implicitDirs: implicitDirs,
		src:          *o,
	}

	d.lc = lookupCount{
		count:   1,
		destroy: func() error { return nil },
	}

	return
}

////////////////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////////////////

func (d *DirInode) checkInvariants() {
	// INVARIANT: src.Name == "" || src.Name[len(name)-1] == '/'
	if !(d.src.Name == "" || d.src.Name[len(d.src.Name)-1] == '/') {
		panic(fmt.Sprintf("Unexpected name: %s", d.src.Name))
	}
}

func (d *DirInode) clobbered(ctx context.Context) (clobbered bool, err error) {
	// Special case: the root is never clobbered.
	if d.ID() == fuseops.RootInodeID {
		return
	}

	// Stat the backing object.
	req := &gcs.StatObjectRequest{
		Name: d.Name(),
	}

	o, err := d.bucket.StatObject(ctx, req)

	// "Not found" means clobbered.
	if _, ok := err.(*gcs.NotFoundError); ok {
		clobbered = true
		err = nil
		return
	}

	// Propagate other errors.
	if err != nil {
		err = fmt.Errorf("StatObject: %v", err)
		return
	}

	// We are clobbered if the generation number has changed.
	clobbered = o.Generation != d.SourceGeneration()

	return
}

func (d *DirInode) lookUpChildFile(
	ctx context.Context,
	name string) (o *gcs.Object, err error) {
	o, err = statObjectMayNotExist(ctx, d.bucket, d.Name()+name)
	if err != nil {
		err = fmt.Errorf("statObjectMayNotExist: %v", err)
		return
	}

	return
}

func (d *DirInode) lookUpChildDir(
	ctx context.Context,
	name string) (o *gcs.Object, err error) {
	b := syncutil.NewBundle(ctx)

	// Stat the placeholder object.
	b.Add(func(ctx context.Context) (err error) {
		o, err = statObjectMayNotExist(ctx, d.bucket, d.Name()+name+"/")
		if err != nil {
			err = fmt.Errorf("statObjectMayNotExist: %v", err)
			return
		}

		return
	})

	// If implicit directories are enabled, find out whether the child name is
	// implicitly defined.
	var implicitlyDefined bool
	if d.implicitDirs {
		b.Add(func(ctx context.Context) (err error) {
			implicitlyDefined, err = objectNamePrefixNonEmpty(
				ctx,
				d.bucket,
				d.Name()+name+"/")

			if err != nil {
				err = fmt.Errorf("objectNamePrefixNonEmpty: %v", err)
				return
			}

			return
		})
	}

	// Wait for both.
	err = b.Join()
	if err != nil {
		return
	}

	// If statting failed by the directory is implicitly defined, fake a source
	// object.
	if o == nil && implicitlyDefined {
		o = &gcs.Object{
			Name:       d.Name() + name + "/",
			Generation: ImplicitDirGen,
		}
	}

	return
}

// List the supplied object name prefix to find out whether it is non-empty.
func objectNamePrefixNonEmpty(
	ctx context.Context,
	bucket gcs.Bucket,
	prefix string) (nonEmpty bool, err error) {
	req := &gcs.ListObjectsRequest{
		Prefix:     prefix,
		MaxResults: 1,
	}

	listing, err := bucket.ListObjects(ctx, req)
	if err != nil {
		err = fmt.Errorf("ListObjects: %v", err)
		return
	}

	nonEmpty = len(listing.Objects) != 0
	return
}

// Stat the object with the given name, returning (nil, nil) if the object
// doesn't exist rather than failing.
func statObjectMayNotExist(
	ctx context.Context,
	bucket gcs.Bucket,
	name string) (o *gcs.Object, err error) {
	// Call the bucket.
	req := &gcs.StatObjectRequest{
		Name: name,
	}

	o, err = bucket.StatObject(ctx, req)

	// Suppress "not found" errors.
	if _, ok := err.(*gcs.NotFoundError); ok {
		err = nil
	}

	// Annotate others.
	if err != nil {
		err = fmt.Errorf("StatObject: %v", err)
		return
	}

	return
}

////////////////////////////////////////////////////////////////////////
// Public interface
////////////////////////////////////////////////////////////////////////

func (d *DirInode) Lock() {
	// We don't require locks.
}

func (d *DirInode) Unlock() {
	// We don't require locks.
}

// Return the ID of this inode.
func (d *DirInode) ID() fuseops.InodeID {
	return d.id
}

// Return the full name of the directory object in GCS, including the trailing
// slash (e.g. "foo/bar/").
func (d *DirInode) Name() string {
	return d.src.Name
}

// Return the generation number from which this inode was branched.
func (d *DirInode) SourceGeneration() int64 {
	return d.src.Generation
}

// LOCKS_REQUIRED(d.mu)
func (d *DirInode) IncrementLookupCount() {
	d.lc.Inc()
}

// LOCKS_REQUIRED(d.mu)
func (d *DirInode) DecrementLookupCount(n uint64) (destroyed bool) {
	destroyed = d.lc.Dec(n)
	return
}

func (d *DirInode) Attributes(
	ctx context.Context) (attrs fuseops.InodeAttributes, err error) {
	// Find out whether the backing object has been clobbered in GCS.
	clobbered, err := d.clobbered(ctx)
	if err != nil {
		err = fmt.Errorf("clobbered: %v", err)
		return
	}

	// Set up basic attributes.
	attrs = fuseops.InodeAttributes{
		Mode: 0700 | os.ModeDir,
	}

	// Modify Nlink as appropriate.
	if !clobbered {
		attrs.Nlink = 1
	}

	return
}

// See notes on DirInode.LookUpChild.
const ImplicitDirGen int64 = -1

// Look up the direct child with the given relative name, returning a record
// for the current object of that name in the GCS bucket. If both a file and a
// directory with the given name exist, be consistent from call to call about
// which is preferred. Return fuse.ENOENT if neither is found.
//
// If this inode was created with implicitDirs is set, this method will use
// ListObjects to find child directories that are "implicitly" defined by the
// existence of their own descendents. For example, if there is an object named
// "foo/bar/baz" and this is the directory "foo", a child directory named "bar"
// will be implied. In this case, the child's generation will be the sentinel
// value ImplicitDirGen.
func (d *DirInode) LookUpChild(
	ctx context.Context,
	name string) (o *gcs.Object, err error) {
	b := syncutil.NewBundle(ctx)

	// Stat the child as a file.
	var fileRecord *gcs.Object
	b.Add(func(ctx context.Context) (err error) {
		fileRecord, err = d.lookUpChildFile(ctx, name)
		return
	})

	// Stat the child as a directory.
	var dirRecord *gcs.Object
	b.Add(func(ctx context.Context) (err error) {
		dirRecord, err = d.lookUpChildDir(ctx, name)
		return
	})

	// Wait for both.
	err = b.Join()
	if err != nil {
		return
	}

	// Prefer directories over files.
	switch {
	case dirRecord != nil:
		o = dirRecord
	case fileRecord != nil:
		o = fileRecord
	default:
		err = fuse.ENOENT
	}

	return
}

// Read some number of entries from the directory, returning a continuation
// token that can be used to pick up the read operation where it left off.
// Supply the empty token on the first call.
//
// At the end of the directory, the returned continuation token will be empty.
// Otherwise it will be non-empty. There is no guarantee about the number of
// entries returned; it may be zero even with a non-empty continuation token.
//
// The contents of the Offset and Inode fields for returned entries is
// undefined.
func (d *DirInode) ReadEntries(
	ctx context.Context,
	tok string) (entries []fuseutil.Dirent, newTok string, err error) {
	// Ask the bucket to list some objects.
	req := &gcs.ListObjectsRequest{
		Delimiter:         "/",
		Prefix:            d.Name(),
		ContinuationToken: tok,
	}

	listing, err := d.bucket.ListObjects(ctx, req)
	if err != nil {
		err = fmt.Errorf("ListObjects: %v", err)
		return
	}

	// Convert objects to entries for files.
	for _, o := range listing.Objects {
		e := fuseutil.Dirent{
			Name: path.Base(o.Name),
			Type: fuseutil.DT_File,
		}

		entries = append(entries, e)
	}

	// Convert runs to entries for directories.
	for _, p := range listing.CollapsedRuns {
		e := fuseutil.Dirent{
			Name: path.Base(p),
			Type: fuseutil.DT_Directory,
		}

		entries = append(entries, e)
	}

	// Return an appropriate continuation token, if any.
	newTok = listing.ContinuationToken

	return
}
<|endoftext|>


<commit_before>// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build freebsd openbsd netbsd darwin

//Package fsnotify implements filesystem notification.
package fsnotify

import (
	"errors"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"syscall"
)

type FileEvent struct {
	mask   uint32 // Mask of events
	Name   string // File name (optional)
	create bool   // set by fsnotify package if found new file
}

// IsCreate reports whether the FileEvent was triggerd by a creation
func (e *FileEvent) IsCreate() bool { return e.create }

// IsDelete reports whether the FileEvent was triggerd by a delete
func (e *FileEvent) IsDelete() bool { return (e.mask & NOTE_DELETE) == NOTE_DELETE }

// IsModify reports whether the FileEvent was triggerd by a file modification
func (e *FileEvent) IsModify() bool {
	return ((e.mask&NOTE_WRITE) == NOTE_WRITE || (e.mask&NOTE_ATTRIB) == NOTE_ATTRIB)
}

// IsRename reports whether the FileEvent was triggerd by a change name
func (e *FileEvent) IsRename() bool { return (e.mask & NOTE_RENAME) == NOTE_RENAME }

type Watcher struct {
	kq            int                 // File descriptor (as returned by the kqueue() syscall)
	watches       map[string]int      // Map of watched file diescriptors (key: path)
	fsnFlags      map[string]uint32   // Map of watched files to flags used for filter
	paths         map[int]string      // Map of watched paths (key: watch descriptor)
	finfo         map[int]os.FileInfo // Map of file information (isDir, isReg; key: watch descriptor)
	fileExists    map[string]bool     // Keep track of if we know this file exists (to stop duplicate create events)
	Error         chan error          // Errors are sent on this channel
	internalEvent chan *FileEvent     // Events are queued on this channel
	Event         chan *FileEvent     // Events are returned on this channel
	done          chan bool           // Channel for sending a "quit message" to the reader goroutine
	isClosed      bool                // Set to true when Close() is first called
	kbuf          [1]syscall.Kevent_t // An event buffer for Add/Remove watch
}

// NewWatcher creates and returns a new kevent instance using kqueue(2)
func NewWatcher() (*Watcher, error) {
	fd, errno := syscall.Kqueue()
	if fd == -1 {
		return nil, os.NewSyscallError("kqueue", errno)
	}
	w := &Watcher{
		kq:            fd,
		watches:       make(map[string]int),
		fsnFlags:      make(map[string]uint32),
		paths:         make(map[int]string),
		finfo:         make(map[int]os.FileInfo),
		fileExists:    make(map[string]bool),
		internalEvent: make(chan *FileEvent),
		Event:         make(chan *FileEvent),
		Error:         make(chan error),
		done:          make(chan bool, 1),
	}

	go w.readEvents()
	go w.purgeEvents()
	return w, nil
}

// Close closes a kevent watcher instance
// It sends a message to the reader goroutine to quit and removes all watches
// associated with the kevent instance
func (w *Watcher) Close() error {
	if w.isClosed {
		return nil
	}
	w.isClosed = true

	// Send "quit" message to the reader goroutine
	w.done <- true
	for path := range w.watches {
		w.removeWatch(path)
	}

	return nil
}

// AddWatch adds path to the watched file set.
// The flags are interpreted as described in kevent(2).
func (w *Watcher) addWatch(path string, flags uint32) error {
	if w.isClosed {
		return errors.New("kevent instance already closed")
	}

	watchEntry := &w.kbuf[0]
	watchEntry.Fflags = flags
	watchDir := false

	watchfd, found := w.watches[path]
	if !found {
		fi, errstat := os.Lstat(path)
		if errstat != nil {
			return errstat
		}

		// Follow Symlinks
		// Unfortunately, Linux can add bogus symlinks to watch list without
		// issue, and Windows can't do symlinks period (AFAIK). To  maintain
		// consistency, we will act like everything is fine. There will simply
		// be no file events for broken symlinks.
		// Hence the returns of nil on errors.
		if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
			path, err := filepath.EvalSymlinks(path)
			if err != nil {
				return nil
			}

			fi, errstat = os.Lstat(path)
			if errstat != nil {
				return nil
			}
		}

		fd, errno := syscall.Open(path, syscall.O_NONBLOCK|syscall.O_RDONLY, 0700)
		if fd == -1 {
			return errno
		}
		watchfd = fd

		w.watches[path] = watchfd
		w.paths[watchfd] = path

		w.finfo[watchfd] = fi
		if fi.IsDir() && (flags&NOTE_WRITE) == NOTE_WRITE {
			watchDir = true
		}
	}
	syscall.SetKevent(watchEntry, watchfd, syscall.EVFILT_VNODE, syscall.EV_ADD|syscall.EV_CLEAR)

	wd, errno := syscall.Kevent(w.kq, w.kbuf[:], nil, nil)
	if wd == -1 {
		return errno
	} else if (watchEntry.Flags & syscall.EV_ERROR) == syscall.EV_ERROR {
		return errors.New("kevent add error")
	}

	if watchDir {
		errdir := w.watchDirectoryFiles(path)
		if errdir != nil {
			return errdir
		}
	}
	return nil
}

// Watch adds path to the watched file set, watching all events.
func (w *Watcher) watch(path string) error {
	return w.addWatch(path, NOTE_ALLEVENTS)
}

// RemoveWatch removes path from the watched file set.
func (w *Watcher) removeWatch(path string) error {
	watchfd, ok := w.watches[path]
	if !ok {
		return errors.New(fmt.Sprintf("can't remove non-existent kevent watch for: %s", path))
	}
	watchEntry := &w.kbuf[0]
	syscall.SetKevent(watchEntry, w.watches[path], syscall.EVFILT_VNODE, syscall.EV_DELETE)
	success, errno := syscall.Kevent(w.kq, w.kbuf[:], nil, nil)
	if success == -1 {
		return os.NewSyscallError("kevent_rm_watch", errno)
	} else if (watchEntry.Flags & syscall.EV_ERROR) == syscall.EV_ERROR {
		return errors.New("kevent rm error")
	}
	syscall.Close(watchfd)
	delete(w.watches, path)
	return nil
}

// readEvents reads from the kqueue file descriptor, converts the
// received events into Event objects and sends them via the Event channel
func (w *Watcher) readEvents() {
	var (
		eventbuf [10]syscall.Kevent_t // Event buffer
		events   []syscall.Kevent_t   // Received events
		twait    *syscall.Timespec    // Time to block waiting for events
		n        int                  // Number of events returned from kevent
		errno    error                // Syscall errno
	)
	events = eventbuf[0:0]
	twait = new(syscall.Timespec)
	*twait = syscall.NsecToTimespec(keventWaitTime)

	for {
		// See if there is a message on the "done" channel
		var done bool
		select {
		case done = <-w.done:
		default:
		}

		// If "done" message is received
		if done {
			errno := syscall.Close(w.kq)
			if errno != nil {
				w.Error <- os.NewSyscallError("close", errno)
			}
			close(w.internalEvent)
			close(w.Error)
			return
		}

		// Get new events
		if len(events) == 0 {
			n, errno = syscall.Kevent(w.kq, nil, eventbuf[:], twait)

			// EINTR is okay, basically the syscall was interrupted before
			// timeout expired.
			if errno != nil && errno != syscall.EINTR {
				w.Error <- os.NewSyscallError("kevent", errno)
				continue
			}

			// Received some events
			if n > 0 {
				events = eventbuf[0:n]
			}
		}

		// Flush the events we recieved to the events channel
		for len(events) > 0 {
			fileEvent := new(FileEvent)
			watchEvent := &events[0]
			fileEvent.mask = uint32(watchEvent.Fflags)
			fileEvent.Name = w.paths[int(watchEvent.Ident)]

			fileInfo := w.finfo[int(watchEvent.Ident)]
			if fileInfo.IsDir() && fileEvent.IsModify() {
				w.sendDirectoryChangeEvents(fileEvent.Name)
			} else {
				// Send the event on the events channel
				w.internalEvent <- fileEvent
			}

			// Move to next event
			events = events[1:]

			if fileEvent.IsRename() {
				w.removeWatch(fileEvent.Name)
				delete(w.fileExists, fileEvent.Name)
			}
			if fileEvent.IsDelete() {
				w.removeWatch(fileEvent.Name)
				delete(w.fileExists, fileEvent.Name)
			}
		}
	}
}

func (w *Watcher) watchDirectoryFiles(dirPath string) error {
	// Get all files
	files, err := ioutil.ReadDir(dirPath)
	if err != nil {
		return err
	}

	// Search for new files
	for _, fileInfo := range files {
		filePath := filepath.Join(dirPath, fileInfo.Name())
		if fileInfo.IsDir() == false {
			// Watch file to mimic linux fsnotify
			e := w.addWatch(filePath, NOTE_DELETE|NOTE_WRITE|NOTE_RENAME)
			w.fsnFlags[filePath] = FSN_ALL
			if e != nil {
				return e
			}
		} else {
			// Linux gives deletes if not explicitly watching
			e := w.addWatch(filePath, NOTE_DELETE)
			w.fsnFlags[filePath] = FSN_ALL
			if e != nil {
				return e
			}
		}
		w.fileExists[filePath] = true
	}

	return nil
}

// sendDirectoryEvents searches the directory for newly created files
// and sends them over the event channel. This functionality is to have
// the BSD version of fsnotify mach linux fsnotify which provides a
// create event for files created in a watched directory.
func (w *Watcher) sendDirectoryChangeEvents(dirPath string) {
	// Get all files
	files, err := ioutil.ReadDir(dirPath)
	if err != nil {
		w.Error <- err
	}

	// Search for new files
	for _, fileInfo := range files {
		filePath := filepath.Join(dirPath, fileInfo.Name())
		_, doesExist := w.fileExists[filePath]
		if doesExist == false {
			w.fsnFlags[filePath] = FSN_ALL
			// Send create event
			fileEvent := new(FileEvent)
			fileEvent.Name = filePath
			fileEvent.create = true
			w.internalEvent <- fileEvent
		}
		w.fileExists[filePath] = true
	}
	w.watchDirectoryFiles(dirPath)
}

const (
	// Flags (from <sys/event.h>)
	NOTE_DELETE = 0x0001 /* vnode was removed */
	NOTE_WRITE  = 0x0002 /* data contents changed */
	NOTE_EXTEND = 0x0004 /* size increased */
	NOTE_ATTRIB = 0x0008 /* attributes changed */
	NOTE_LINK   = 0x0010 /* link count changed */
	NOTE_RENAME = 0x0020 /* vnode was renamed */
	NOTE_REVOKE = 0x0040 /* vnode access was revoked */

	// Watch all events
	NOTE_ALLEVENTS = NOTE_DELETE | NOTE_WRITE | NOTE_ATTRIB | NOTE_RENAME

	// Block for 100 ms on each call to kevent
	keventWaitTime = 100e6
)
<commit_msg>Watch the directory even if it isn't a new watch.<commit_after>// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build freebsd openbsd netbsd darwin

//Package fsnotify implements filesystem notification.
package fsnotify

import (
	"errors"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"syscall"
)

type FileEvent struct {
	mask   uint32 // Mask of events
	Name   string // File name (optional)
	create bool   // set by fsnotify package if found new file
}

// IsCreate reports whether the FileEvent was triggerd by a creation
func (e *FileEvent) IsCreate() bool { return e.create }

// IsDelete reports whether the FileEvent was triggerd by a delete
func (e *FileEvent) IsDelete() bool { return (e.mask & NOTE_DELETE) == NOTE_DELETE }

// IsModify reports whether the FileEvent was triggerd by a file modification
func (e *FileEvent) IsModify() bool {
	return ((e.mask&NOTE_WRITE) == NOTE_WRITE || (e.mask&NOTE_ATTRIB) == NOTE_ATTRIB)
}

// IsRename reports whether the FileEvent was triggerd by a change name
func (e *FileEvent) IsRename() bool { return (e.mask & NOTE_RENAME) == NOTE_RENAME }

type Watcher struct {
	kq            int                 // File descriptor (as returned by the kqueue() syscall)
	watches       map[string]int      // Map of watched file diescriptors (key: path)
	fsnFlags      map[string]uint32   // Map of watched files to flags used for filter
	paths         map[int]string      // Map of watched paths (key: watch descriptor)
	finfo         map[int]os.FileInfo // Map of file information (isDir, isReg; key: watch descriptor)
	fileExists    map[string]bool     // Keep track of if we know this file exists (to stop duplicate create events)
	Error         chan error          // Errors are sent on this channel
	internalEvent chan *FileEvent     // Events are queued on this channel
	Event         chan *FileEvent     // Events are returned on this channel
	done          chan bool           // Channel for sending a "quit message" to the reader goroutine
	isClosed      bool                // Set to true when Close() is first called
	kbuf          [1]syscall.Kevent_t // An event buffer for Add/Remove watch
}

// NewWatcher creates and returns a new kevent instance using kqueue(2)
func NewWatcher() (*Watcher, error) {
	fd, errno := syscall.Kqueue()
	if fd == -1 {
		return nil, os.NewSyscallError("kqueue", errno)
	}
	w := &Watcher{
		kq:            fd,
		watches:       make(map[string]int),
		fsnFlags:      make(map[string]uint32),
		paths:         make(map[int]string),
		finfo:         make(map[int]os.FileInfo),
		fileExists:    make(map[string]bool),
		internalEvent: make(chan *FileEvent),
		Event:         make(chan *FileEvent),
		Error:         make(chan error),
		done:          make(chan bool, 1),
	}

	go w.readEvents()
	go w.purgeEvents()
	return w, nil
}

// Close closes a kevent watcher instance
// It sends a message to the reader goroutine to quit and removes all watches
// associated with the kevent instance
func (w *Watcher) Close() error {
	if w.isClosed {
		return nil
	}
	w.isClosed = true

	// Send "quit" message to the reader goroutine
	w.done <- true
	for path := range w.watches {
		w.removeWatch(path)
	}

	return nil
}

// AddWatch adds path to the watched file set.
// The flags are interpreted as described in kevent(2).
func (w *Watcher) addWatch(path string, flags uint32) error {
	if w.isClosed {
		return errors.New("kevent instance already closed")
	}

	watchEntry := &w.kbuf[0]
	watchEntry.Fflags = flags
	watchDir := false

	watchfd, found := w.watches[path]
	if !found {
		fi, errstat := os.Lstat(path)
		if errstat != nil {
			return errstat
		}

		// Follow Symlinks
		// Unfortunately, Linux can add bogus symlinks to watch list without
		// issue, and Windows can't do symlinks period (AFAIK). To  maintain
		// consistency, we will act like everything is fine. There will simply
		// be no file events for broken symlinks.
		// Hence the returns of nil on errors.
		if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
			path, err := filepath.EvalSymlinks(path)
			if err != nil {
				return nil
			}

			fi, errstat = os.Lstat(path)
			if errstat != nil {
				return nil
			}
		}

		fd, errno := syscall.Open(path, syscall.O_NONBLOCK|syscall.O_RDONLY, 0700)
		if fd == -1 {
			return errno
		}
		watchfd = fd

		w.watches[path] = watchfd
		w.paths[watchfd] = path

		w.finfo[watchfd] = fi
	}

	if w.finfo[watchfd].IsDir() && (flags&NOTE_WRITE) == NOTE_WRITE {
		watchDir = true
	}

	syscall.SetKevent(watchEntry, watchfd, syscall.EVFILT_VNODE, syscall.EV_ADD|syscall.EV_CLEAR)

	wd, errno := syscall.Kevent(w.kq, w.kbuf[:], nil, nil)
	if wd == -1 {
		return errno
	} else if (watchEntry.Flags & syscall.EV_ERROR) == syscall.EV_ERROR {
		return errors.New("kevent add error")
	}

	if watchDir {
		errdir := w.watchDirectoryFiles(path)
		if errdir != nil {
			return errdir
		}
	}
	return nil
}

// Watch adds path to the watched file set, watching all events.
func (w *Watcher) watch(path string) error {
	return w.addWatch(path, NOTE_ALLEVENTS)
}

// RemoveWatch removes path from the watched file set.
func (w *Watcher) removeWatch(path string) error {
	watchfd, ok := w.watches[path]
	if !ok {
		return errors.New(fmt.Sprintf("can't remove non-existent kevent watch for: %s", path))
	}
	watchEntry := &w.kbuf[0]
	syscall.SetKevent(watchEntry, w.watches[path], syscall.EVFILT_VNODE, syscall.EV_DELETE)
	success, errno := syscall.Kevent(w.kq, w.kbuf[:], nil, nil)
	if success == -1 {
		return os.NewSyscallError("kevent_rm_watch", errno)
	} else if (watchEntry.Flags & syscall.EV_ERROR) == syscall.EV_ERROR {
		return errors.New("kevent rm error")
	}
	syscall.Close(watchfd)
	delete(w.watches, path)
	return nil
}

// readEvents reads from the kqueue file descriptor, converts the
// received events into Event objects and sends them via the Event channel
func (w *Watcher) readEvents() {
	var (
		eventbuf [10]syscall.Kevent_t // Event buffer
		events   []syscall.Kevent_t   // Received events
		twait    *syscall.Timespec    // Time to block waiting for events
		n        int                  // Number of events returned from kevent
		errno    error                // Syscall errno
	)
	events = eventbuf[0:0]
	twait = new(syscall.Timespec)
	*twait = syscall.NsecToTimespec(keventWaitTime)

	for {
		// See if there is a message on the "done" channel
		var done bool
		select {
		case done = <-w.done:
		default:
		}

		// If "done" message is received
		if done {
			errno := syscall.Close(w.kq)
			if errno != nil {
				w.Error <- os.NewSyscallError("close", errno)
			}
			close(w.internalEvent)
			close(w.Error)
			return
		}

		// Get new events
		if len(events) == 0 {
			n, errno = syscall.Kevent(w.kq, nil, eventbuf[:], twait)

			// EINTR is okay, basically the syscall was interrupted before
			// timeout expired.
			if errno != nil && errno != syscall.EINTR {
				w.Error <- os.NewSyscallError("kevent", errno)
				continue
			}

			// Received some events
			if n > 0 {
				events = eventbuf[0:n]
			}
		}

		// Flush the events we recieved to the events channel
		for len(events) > 0 {
			fileEvent := new(FileEvent)
			watchEvent := &events[0]
			fileEvent.mask = uint32(watchEvent.Fflags)
			fileEvent.Name = w.paths[int(watchEvent.Ident)]

			fileInfo := w.finfo[int(watchEvent.Ident)]
			if fileInfo.IsDir() && fileEvent.IsModify() {
				w.sendDirectoryChangeEvents(fileEvent.Name)
			} else {
				// Send the event on the events channel
				w.internalEvent <- fileEvent
			}

			// Move to next event
			events = events[1:]

			if fileEvent.IsRename() {
				w.removeWatch(fileEvent.Name)
				delete(w.fileExists, fileEvent.Name)
			}
			if fileEvent.IsDelete() {
				w.removeWatch(fileEvent.Name)
				delete(w.fileExists, fileEvent.Name)
			}
		}
	}
}

func (w *Watcher) watchDirectoryFiles(dirPath string) error {
	// Get all files
	files, err := ioutil.ReadDir(dirPath)
	if err != nil {
		return err
	}

	// Search for new files
	for _, fileInfo := range files {
		filePath := filepath.Join(dirPath, fileInfo.Name())
		if fileInfo.IsDir() == false {
			// Watch file to mimic linux fsnotify
			e := w.addWatch(filePath, NOTE_DELETE|NOTE_WRITE|NOTE_RENAME)
			w.fsnFlags[filePath] = FSN_ALL
			if e != nil {
				return e
			}
		} else {
			// Linux gives deletes if not explicitly watching
			e := w.addWatch(filePath, NOTE_DELETE)
			w.fsnFlags[filePath] = FSN_ALL
			if e != nil {
				return e
			}
		}
		w.fileExists[filePath] = true
	}

	return nil
}

// sendDirectoryEvents searches the directory for newly created files
// and sends them over the event channel. This functionality is to have
// the BSD version of fsnotify mach linux fsnotify which provides a
// create event for files created in a watched directory.
func (w *Watcher) sendDirectoryChangeEvents(dirPath string) {
	// Get all files
	files, err := ioutil.ReadDir(dirPath)
	if err != nil {
		w.Error <- err
	}

	// Search for new files
	for _, fileInfo := range files {
		filePath := filepath.Join(dirPath, fileInfo.Name())
		_, doesExist := w.fileExists[filePath]
		if doesExist == false {
			w.fsnFlags[filePath] = FSN_ALL
			// Send create event
			fileEvent := new(FileEvent)
			fileEvent.Name = filePath
			fileEvent.create = true
			w.internalEvent <- fileEvent
		}
		w.fileExists[filePath] = true
	}
	w.watchDirectoryFiles(dirPath)
}

const (
	// Flags (from <sys/event.h>)
	NOTE_DELETE = 0x0001 /* vnode was removed */
	NOTE_WRITE  = 0x0002 /* data contents changed */
	NOTE_EXTEND = 0x0004 /* size increased */
	NOTE_ATTRIB = 0x0008 /* attributes changed */
	NOTE_LINK   = 0x0010 /* link count changed */
	NOTE_RENAME = 0x0020 /* vnode was renamed */
	NOTE_REVOKE = 0x0040 /* vnode access was revoked */

	// Watch all events
	NOTE_ALLEVENTS = NOTE_DELETE | NOTE_WRITE | NOTE_ATTRIB | NOTE_RENAME

	// Block for 100 ms on each call to kevent
	keventWaitTime = 100e6
)
<|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 admissionwebhook

import (
	"bytes"
	"context"
	"crypto/tls"
	"crypto/x509"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"

	v1 "k8s.io/api/admission/v1"
	admissionv1 "k8s.io/api/admissionregistration/v1"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	v1validation "k8s.io/apimachinery/pkg/apis/meta/v1/validation"
	"k8s.io/apimachinery/pkg/types"
	"k8s.io/apimachinery/pkg/util/validation/field"
	"k8s.io/apimachinery/pkg/util/wait"
	"k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager"
	clientset "k8s.io/client-go/kubernetes"
	restclient "k8s.io/client-go/rest"
	kubeapiservertesting "k8s.io/kubernetes/cmd/kube-apiserver/app/testing"
	"k8s.io/kubernetes/test/integration/framework"
)

// TestMutatingWebhookResetsInvalidManagedFields ensures that the API server
// resets managedFields to their state before admission if a mutating webhook
// patches create/update requests with invalid managedFields.
func TestMutatingWebhookResetsInvalidManagedFields(t *testing.T) {
	roots := x509.NewCertPool()
	if !roots.AppendCertsFromPEM(localhostCert) {
		t.Fatal("Failed to append Cert from PEM")
	}
	cert, err := tls.X509KeyPair(localhostCert, localhostKey)
	if err != nil {
		t.Fatalf("Failed to build cert with error: %+v", err)
	}

	webhookServer := httptest.NewUnstartedServer(newInvalidManagedFieldsWebhookHandler(t))
	webhookServer.TLS = &tls.Config{
		RootCAs:      roots,
		Certificates: []tls.Certificate{cert},
	}
	webhookServer.StartTLS()
	defer webhookServer.Close()

	s := kubeapiservertesting.StartTestServerOrDie(t,
		kubeapiservertesting.NewDefaultTestServerOptions(), []string{
			"--disable-admission-plugins=ServiceAccount",
		}, framework.SharedEtcd())
	defer s.TearDownFn()

	recordedWarnings := &bytes.Buffer{}
	warningWriter := restclient.NewWarningWriter(recordedWarnings, restclient.WarningWriterOptions{})
	s.ClientConfig.WarningHandler = warningWriter
	client := clientset.NewForConfigOrDie(s.ClientConfig)

	if _, err := client.CoreV1().Pods("default").Create(
		context.TODO(), invalidManagedFieldsMarkerFixture, metav1.CreateOptions{}); err != nil {
		t.Fatal(err)
	}
	// make sure we delete the pod even on a failed test
	defer func() {
		if err := client.CoreV1().Pods("default").Delete(context.TODO(), invalidManagedFieldsMarkerFixture.Name, metav1.DeleteOptions{}); err != nil {
			t.Fatalf("failed to delete marker pod: %v", err)
		}
	}()

	fail := admissionv1.Fail
	none := admissionv1.SideEffectClassNone
	mutatingCfg, err := client.AdmissionregistrationV1().MutatingWebhookConfigurations().Create(context.TODO(), &admissionv1.MutatingWebhookConfiguration{
		ObjectMeta: metav1.ObjectMeta{Name: "invalid-managedfields.admission.integration.test"},
		Webhooks: []admissionv1.MutatingWebhook{{
			Name: "invalid-managedfields.admission.integration.test",
			ClientConfig: admissionv1.WebhookClientConfig{
				URL:      &webhookServer.URL,
				CABundle: localhostCert,
			},
			Rules: []admissionv1.RuleWithOperations{{
				Operations: []admissionv1.OperationType{admissionv1.Create, admissionv1.Update},
				Rule:       admissionv1.Rule{APIGroups: []string{""}, APIVersions: []string{"v1"}, Resources: []string{"pods"}},
			}},
			FailurePolicy:           &fail,
			AdmissionReviewVersions: []string{"v1", "v1beta1"},
			SideEffects:             &none,
		}},
	}, metav1.CreateOptions{})
	if err != nil {
		t.Fatal(err)
	}
	defer func() {
		err := client.AdmissionregistrationV1().MutatingWebhookConfigurations().Delete(context.TODO(), mutatingCfg.GetName(), metav1.DeleteOptions{})
		if err != nil {
			t.Fatal(err)
		}
	}()

	var pod *corev1.Pod
	var lastErr error
	// We just expect the general warning text as the detail order might change
	expectedWarning := fmt.Sprintf(fieldmanager.InvalidManagedFieldsAfterMutatingAdmissionWarningFormat, "")

	// Make sure reset happens on patch requests
	// wait until new webhook is called
	if err := wait.PollImmediate(time.Millisecond*5, wait.ForeverTestTimeout, func() (bool, error) {
		pod, err = client.CoreV1().Pods("default").Patch(context.TODO(), invalidManagedFieldsMarkerFixture.Name, types.JSONPatchType, []byte("[]"), metav1.PatchOptions{})
		if err != nil {
			return false, err
		}
		if err := validateManagedFieldsAndDecode(pod.ManagedFields); err != nil {
			lastErr = err
			return false, nil
		}
		return true, nil
	}); err != nil {
		t.Fatalf("failed to wait for apiserver handling webhook mutation: %v, last error: %v", err, lastErr)
	}
	if lastErr != nil {
		t.Fatal(lastErr)
	}
	if warningWriter.WarningCount() != 1 {
		t.Errorf("expected one warning, got: %v", warningWriter.WarningCount())
	}
	if !strings.Contains(recordedWarnings.String(), expectedWarning) {
		t.Errorf("unexpected warning, expected: \n%v\n, got: \n%v",
			expectedWarning, recordedWarnings.String())
	}
	recordedWarnings.Reset()

	// Make sure reset happens in update requests
	pod, err = client.CoreV1().Pods("default").Update(context.TODO(), pod, metav1.UpdateOptions{})
	if err != nil {
		t.Fatal(err)
	}
	if err := validateManagedFieldsAndDecode(pod.ManagedFields); err != nil {
		t.Error(err)
	}
	if warningWriter.WarningCount() != 2 {
		t.Errorf("expected two warnings, got: %v", warningWriter.WarningCount())
	}
	if !strings.Contains(recordedWarnings.String(), expectedWarning) {
		t.Errorf("unexpected warning, expected: \n%v\n, got: \n%v",
			expectedWarning, recordedWarnings.String())
	}
}

// validate against both decoding and validation to make sure we use the hardest rule between the both to reset
// with decoding being as strict as it gets, only using it should be enough in admission
func validateManagedFieldsAndDecode(managedFields []metav1.ManagedFieldsEntry) error {
	if _, err := fieldmanager.DecodeManagedFields(managedFields); err != nil {
		return err
	}
	validationErrs := v1validation.ValidateManagedFields(managedFields, field.NewPath("metadata").Child("managedFields"))
	return validationErrs.ToAggregate()
}

func newInvalidManagedFieldsWebhookHandler(t *testing.T) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		defer r.Body.Close()
		data, err := ioutil.ReadAll(r.Body)
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
		}
		review := v1.AdmissionReview{}
		if err := json.Unmarshal(data, &review); err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
		}

		if len(review.Request.Object.Raw) == 0 {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		pod := &corev1.Pod{}
		if err := json.Unmarshal(review.Request.Object.Raw, pod); err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}

		review.Response = &v1.AdmissionResponse{
			Allowed: true,
			UID:     review.Request.UID,
			Result:  &metav1.Status{Message: "admitted"},
		}

		if len(pod.ManagedFields) != 0 {
			t.Logf("corrupting managedFields %v", pod.ManagedFields)
			review.Response.Patch = []byte(`[
				{"op":"remove","path":"/metadata/managedFields/0/apiVersion"},
				{"op":"remove","path":"/metadata/managedFields/0/fieldsV1"},
				{"op":"remove","path":"/metadata/managedFields/0/fieldsType"}
			]`)
			jsonPatch := v1.PatchTypeJSONPatch
			review.Response.PatchType = &jsonPatch
		}

		w.Header().Set("Content-Type", "application/json")
		if err := json.NewEncoder(w).Encode(review); err != nil {
			t.Errorf("Marshal of response failed with error: %v", err)
		}
	})
}

var invalidManagedFieldsMarkerFixture = &corev1.Pod{
	ObjectMeta: metav1.ObjectMeta{
		Namespace: "default",
		Name:      "invalid-managedfields-test-marker",
	},
	Spec: corev1.PodSpec{
		Containers: []corev1.Container{{
			Name:  "fake-name",
			Image: "fakeimage",
		}},
	},
}
<commit_msg>fix TestMutatingWebhookResetsInvalidManagedFields flakes<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 admissionwebhook

import (
	"bytes"
	"context"
	"crypto/tls"
	"crypto/x509"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"

	v1 "k8s.io/api/admission/v1"
	admissionv1 "k8s.io/api/admissionregistration/v1"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	v1validation "k8s.io/apimachinery/pkg/apis/meta/v1/validation"
	"k8s.io/apimachinery/pkg/types"
	"k8s.io/apimachinery/pkg/util/validation/field"
	"k8s.io/apimachinery/pkg/util/wait"
	"k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager"
	clientset "k8s.io/client-go/kubernetes"
	restclient "k8s.io/client-go/rest"
	kubeapiservertesting "k8s.io/kubernetes/cmd/kube-apiserver/app/testing"
	"k8s.io/kubernetes/test/integration/framework"
)

// TestMutatingWebhookResetsInvalidManagedFields ensures that the API server
// resets managedFields to their state before admission if a mutating webhook
// patches create/update requests with invalid managedFields.
func TestMutatingWebhookResetsInvalidManagedFields(t *testing.T) {
	roots := x509.NewCertPool()
	if !roots.AppendCertsFromPEM(localhostCert) {
		t.Fatal("Failed to append Cert from PEM")
	}
	cert, err := tls.X509KeyPair(localhostCert, localhostKey)
	if err != nil {
		t.Fatalf("Failed to build cert with error: %+v", err)
	}

	webhookServer := httptest.NewUnstartedServer(newInvalidManagedFieldsWebhookHandler(t))
	webhookServer.TLS = &tls.Config{
		RootCAs:      roots,
		Certificates: []tls.Certificate{cert},
	}
	webhookServer.StartTLS()
	defer webhookServer.Close()

	s := kubeapiservertesting.StartTestServerOrDie(t,
		kubeapiservertesting.NewDefaultTestServerOptions(), []string{
			"--disable-admission-plugins=ServiceAccount",
		}, framework.SharedEtcd())
	defer s.TearDownFn()

	recordedWarnings := &bytes.Buffer{}
	warningWriter := restclient.NewWarningWriter(recordedWarnings, restclient.WarningWriterOptions{})
	s.ClientConfig.WarningHandler = warningWriter
	client := clientset.NewForConfigOrDie(s.ClientConfig)

	if _, err := client.CoreV1().Pods("default").Create(
		context.TODO(), invalidManagedFieldsMarkerFixture, metav1.CreateOptions{}); err != nil {
		t.Fatal(err)
	}
	// make sure we delete the pod even on a failed test
	defer func() {
		if err := client.CoreV1().Pods("default").Delete(context.TODO(), invalidManagedFieldsMarkerFixture.Name, metav1.DeleteOptions{}); err != nil {
			t.Fatalf("failed to delete marker pod: %v", err)
		}
	}()

	fail := admissionv1.Fail
	none := admissionv1.SideEffectClassNone
	mutatingCfg, err := client.AdmissionregistrationV1().MutatingWebhookConfigurations().Create(context.TODO(), &admissionv1.MutatingWebhookConfiguration{
		ObjectMeta: metav1.ObjectMeta{Name: "invalid-managedfields.admission.integration.test"},
		Webhooks: []admissionv1.MutatingWebhook{{
			Name: "invalid-managedfields.admission.integration.test",
			ClientConfig: admissionv1.WebhookClientConfig{
				URL:      &webhookServer.URL,
				CABundle: localhostCert,
			},
			Rules: []admissionv1.RuleWithOperations{{
				Operations: []admissionv1.OperationType{admissionv1.Create, admissionv1.Update},
				Rule:       admissionv1.Rule{APIGroups: []string{""}, APIVersions: []string{"v1"}, Resources: []string{"pods"}},
			}},
			FailurePolicy:           &fail,
			AdmissionReviewVersions: []string{"v1", "v1beta1"},
			SideEffects:             &none,
		}},
	}, metav1.CreateOptions{})
	if err != nil {
		t.Fatal(err)
	}
	defer func() {
		err := client.AdmissionregistrationV1().MutatingWebhookConfigurations().Delete(context.TODO(), mutatingCfg.GetName(), metav1.DeleteOptions{})
		if err != nil {
			t.Fatal(err)
		}
	}()

	var pod *corev1.Pod
	var lastErr error
	// We just expect the general warning text as the detail order might change
	expectedWarning := fmt.Sprintf(fieldmanager.InvalidManagedFieldsAfterMutatingAdmissionWarningFormat, "")

	// Make sure reset happens on patch requests
	// wait until new webhook is called
	if err := wait.PollImmediate(time.Millisecond*5, wait.ForeverTestTimeout, func() (bool, error) {
		defer recordedWarnings.Reset()
		pod, err = client.CoreV1().Pods("default").Patch(context.TODO(), invalidManagedFieldsMarkerFixture.Name, types.JSONPatchType, []byte("[]"), metav1.PatchOptions{})
		if err != nil {
			return false, err
		}
		if err := validateManagedFieldsAndDecode(pod.ManagedFields); err != nil {
			lastErr = err
			return false, nil
		}
		if warningWriter.WarningCount() != 1 {
			lastErr = fmt.Errorf("expected one warning, got: %v", warningWriter.WarningCount())
			return false, nil
		}
		if !strings.Contains(recordedWarnings.String(), expectedWarning) {
			lastErr = fmt.Errorf("unexpected warning, expected: \n%v\n, got: \n%v",
				expectedWarning, recordedWarnings.String())
			return false, nil
		}
		lastErr = nil
		return true, nil
	}); err != nil || lastErr != nil {
		t.Fatalf("failed to wait for apiserver handling webhook mutation: %v, last error: %v", err, lastErr)
	}

	// Make sure reset happens in update requests
	pod, err = client.CoreV1().Pods("default").Update(context.TODO(), pod, metav1.UpdateOptions{})
	if err != nil {
		t.Fatal(err)
	}
	if err := validateManagedFieldsAndDecode(pod.ManagedFields); err != nil {
		t.Error(err)
	}
	if warningWriter.WarningCount() != 2 {
		t.Errorf("expected two warnings, got: %v", warningWriter.WarningCount())
	}
	if !strings.Contains(recordedWarnings.String(), expectedWarning) {
		t.Errorf("unexpected warning, expected: \n%v\n, got: \n%v",
			expectedWarning, recordedWarnings.String())
	}
}

// validate against both decoding and validation to make sure we use the hardest rule between the both to reset
// with decoding being as strict as it gets, only using it should be enough in admission
func validateManagedFieldsAndDecode(managedFields []metav1.ManagedFieldsEntry) error {
	if _, err := fieldmanager.DecodeManagedFields(managedFields); err != nil {
		return err
	}
	validationErrs := v1validation.ValidateManagedFields(managedFields, field.NewPath("metadata").Child("managedFields"))
	return validationErrs.ToAggregate()
}

func newInvalidManagedFieldsWebhookHandler(t *testing.T) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		defer r.Body.Close()
		data, err := ioutil.ReadAll(r.Body)
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
		}
		review := v1.AdmissionReview{}
		if err := json.Unmarshal(data, &review); err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
		}

		if len(review.Request.Object.Raw) == 0 {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		pod := &corev1.Pod{}
		if err := json.Unmarshal(review.Request.Object.Raw, pod); err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}

		review.Response = &v1.AdmissionResponse{
			Allowed: true,
			UID:     review.Request.UID,
			Result:  &metav1.Status{Message: "admitted"},
		}

		if len(pod.ManagedFields) != 0 {
			t.Logf("corrupting managedFields %v", pod.ManagedFields)
			review.Response.Patch = []byte(`[
				{"op":"remove","path":"/metadata/managedFields/0/apiVersion"},
				{"op":"remove","path":"/metadata/managedFields/0/fieldsV1"},
				{"op":"remove","path":"/metadata/managedFields/0/fieldsType"}
			]`)
			jsonPatch := v1.PatchTypeJSONPatch
			review.Response.PatchType = &jsonPatch
		}

		w.Header().Set("Content-Type", "application/json")
		if err := json.NewEncoder(w).Encode(review); err != nil {
			t.Errorf("Marshal of response failed with error: %v", err)
		}
	})
}

var invalidManagedFieldsMarkerFixture = &corev1.Pod{
	ObjectMeta: metav1.ObjectMeta{
		Namespace: "default",
		Name:      "invalid-managedfields-test-marker",
	},
	Spec: corev1.PodSpec{
		Containers: []corev1.Container{{
			Name:  "fake-name",
			Image: "fakeimage",
		}},
	},
}
<|endoftext|>


<commit_before>package fun_test

import (
	"fmt"

	"github.com/jBugman/fun-lang/fun"
)

func ExampleParameters_String_single() {
	fmt.Println(fun.Parameters{{Name: "s", Type: "string"}})
	// Output:
	// string
}

func ExampleParameters_String_two() {
	fmt.Println(fun.Parameters{fun.NewParam("x", "int"), fun.NewParam("y", "int")})
	// Output:
	// int -> int
}

func ExampleParameters_String_zero() {
	fmt.Println(fun.Parameters{})
	// Output:
	//
}

func ExampleResults_String_one() {
	fmt.Println(fun.Results{"io.Writer"})
	// Output:
	// io.Writer
}

func ExampleResults_String_two() {
	fmt.Println(fun.Results{"int", "error"})
	// Output:
	// (int, error)
}
func ExampleResults_String_zero() {
	fmt.Println(fun.Results{})
	// Output:
	// ()
}

func ExampleFuncDecl_String_unit_undefined() {
	fn := fun.FuncDecl{Name: "main"}
	fmt.Println(fn)
	// Output:
	// main :: ()
	// main = undefined
}

func ExampleFuncDecl_String_int_unit_undefined() {
	fn := fun.FuncDecl{
		Name:   "print",
		Params: fun.Parameters{{Name: "n", Type: "int"}},
	}
	fmt.Println(fn)
	// Output:
	// print :: int -> ()
	// print n = undefined
}

func ExampleFuncDecl_String_head_undefined() {
	fn := fun.FuncDecl{
		Name:    "head",
		Params:  fun.Parameters{{Name: "xs", Type: "[int]"}},
		Results: fun.Results{"int", "error"},
	}
	fmt.Println(fn)
	// Output:
	// head :: [int] -> (int, error)
	// head xs = undefined
}

func ExampleFuncDecl_String_params() {
	fn := fun.FuncDecl{
		Name:    "enumFromTo",
		Params:  fun.Parameters{fun.NewParam("x", "a"), fun.NewParam("y", "a")},
		Results: fun.Results{"[a]"},
	}
	fmt.Println(fn)
	// Output:
	// enumFromTo :: a -> a -> [a]
	// enumFromTo x y = undefined
}

func ExampleCreateAST() {
	module := fun.Module{
		Name: "Main",
		Imports: []fun.Import{
			{Path: "fmt"},
		},
		Decls: []fun.Decl{
			fun.FuncDecl{
				Name: "main",
				Body: fun.SingleExprBody{
					Expr: fun.FuncApplication{
						Func: fun.FunctionVal{
							Module: "fmt",
							Name:   "Println",
						},
						Arguments: []fun.Expression{fun.String("Hello World!")},
					},
				},
			},
		},
	}
	fmt.Print(module)
	// Output:
	// module Main where
	//
	// import "fmt"
	//
	// main :: ()
	// main = fmt.Println "Hello World!"
}

func ExampleFuncApplication_String_local() {
	fn := fun.FuncApplication{
		Func:      fun.FunctionVal{Name: "sum"},
		Arguments: []fun.Expression{fun.Int("1"), fun.Int("2")},
	}
	fmt.Println(fn)
	// Output:
	// sum 1 2
}

func ExampleFuncApplication_String_fmtPrintln() {
	fn := fun.FuncApplication{
		Func: fun.FunctionVal{
			Name:   "Println",
			Module: "fmt",
		},
		Arguments: []fun.Expression{fun.Float("4.2")},
	}
	fmt.Println(fn)
	// Output:
	// fmt.Println 4.2
}

func ExampleFuncApplication_String_nestedFunction() {
	fn := fun.FuncApplication{
		Func: fun.FunctionVal{Name: "take"},
		Arguments: []fun.Expression{
			fun.Int("3"),
			fun.FuncApplication{
				Func:      fun.FunctionVal{Name: "reverse"},
				Arguments: []fun.Expression{fun.Val("xs")},
			},
		},
	}
	fmt.Println(fn)
	// Output:
	// take 3 (reverse xs)
}

func ExampleFuncDecl_String_singleExprBody() {
	expr := fun.FuncApplication{
		Func: fun.FunctionVal{
			Name:   "Println",
			Module: "fmt",
		},
		Arguments: []fun.Expression{fun.Val("x")},
	}
	fn := fun.FuncDecl{
		Name:   "printInt",
		Params: fun.Parameters{fun.NewParam("x", "int")},
		Body:   fun.SingleExprBody{Expr: expr},
	}
	fmt.Println(fn)
	// Output:
	// printInt :: int -> ()
	// printInt x = fmt.Println x
}

func ExampleDoBlock_String_oneLine() {
	fn := fun.DoBlock{Text: []string{`fmt.Fprintf(&b, "world!")`}}
	fmt.Println(fn)
	// Output:
	// do
	//     fmt.Fprintf(&b, "world!")
}

func ExampleFuncDecl_String_doBlock_multiline() {
	fn := fun.FuncDecl{
		Name:   "printHash",
		Params: fun.Parameters{fun.NewParam("str", "string")},
		Body: fun.DoBlock{Text: []string{
			`h := md5.New()`,
			`io.WriteString(h, str)`,
			`fmt.Printf("%x", h.Sum(nil))`,
		}},
	}
	fmt.Println(fn)
	// Output:
	// printHash :: string -> ()
	// printHash str = do
	//     h := md5.New()
	//     io.WriteString(h, str)
	//     fmt.Printf("%x", h.Sum(nil))
}
<commit_msg>Full AST printers test coverage<commit_after>package fun_test

import (
	"fmt"

	"github.com/jBugman/fun-lang/fun"
)

func ExampleImport_String_single() {
	fmt.Println(fun.Import{Path: "github.com/awesome/lib/fmt", Alias: "awfmt"})
	// Output:
	// import "github.com/awesome/lib/fmt" as "awfmt"
}

func ExampleParameters_String_single() {
	fmt.Println(fun.Parameters{{Name: "s", Type: "string"}})
	// Output:
	// string
}

func ExampleParameters_String_two() {
	fmt.Println(fun.Parameters{fun.NewParam("x", "int"), fun.NewParam("y", "int")})
	// Output:
	// int -> int
}

func ExampleParameters_String_zero() {
	fmt.Println(fun.Parameters{})
	// Output:
	//
}

func ExampleResults_String_one() {
	fmt.Println(fun.Results{"io.Writer"})
	// Output:
	// io.Writer
}

func ExampleResults_String_two() {
	fmt.Println(fun.Results{"int", "error"})
	// Output:
	// (int, error)
}
func ExampleResults_String_zero() {
	fmt.Println(fun.Results{})
	// Output:
	// ()
}

func ExampleFuncDecl_String_unit_implicit_undefined() {
	fn := fun.FuncDecl{Name: "main"}
	fmt.Println(fn)
	// Output:
	// main :: ()
	// main = undefined
}

func ExampleFuncDecl_String_unit_explicit_undefined() {
	fn := fun.FuncDecl{
		Name:   "newFunc",
		Params: fun.Parameters{fun.NewParam("launchMissles", "bool")},
		Body:   fun.Undefined,
	}
	fmt.Println(fn)
	// Output:
	// newFunc :: bool -> ()
	// newFunc launchMissles = undefined
}

func ExampleFuncDecl_String_int_unit_undefined() {
	fn := fun.FuncDecl{
		Name:   "print",
		Params: fun.Parameters{{Name: "n", Type: "int"}},
	}
	fmt.Println(fn)
	// Output:
	// print :: int -> ()
	// print n = undefined
}

func ExampleFuncDecl_String_head_undefined() {
	fn := fun.FuncDecl{
		Name:    "head",
		Params:  fun.Parameters{{Name: "xs", Type: "[int]"}},
		Results: fun.Results{"int", "error"},
	}
	fmt.Println(fn)
	// Output:
	// head :: [int] -> (int, error)
	// head xs = undefined
}

func ExampleFuncDecl_String_params() {
	fn := fun.FuncDecl{
		Name:    "enumFromTo",
		Params:  fun.Parameters{fun.NewParam("x", "a"), fun.NewParam("y", "a")},
		Results: fun.Results{"[a]"},
	}
	fmt.Println(fn)
	// Output:
	// enumFromTo :: a -> a -> [a]
	// enumFromTo x y = undefined
}

func ExampleCreateAST() {
	module := fun.Module{
		Name: "Main",
		Imports: []fun.Import{
			{Path: "fmt"},
		},
		Decls: []fun.Decl{
			fun.FuncDecl{
				Name: "main",
				Body: fun.SingleExprBody{
					Expr: fun.FuncApplication{
						Func: fun.FunctionVal{
							Module: "fmt",
							Name:   "Println",
						},
						Arguments: []fun.Expression{fun.String("Hello World!")},
					},
				},
			},
		},
	}
	fmt.Print(module)
	// Output:
	// module Main where
	//
	// import "fmt"
	//
	// main :: ()
	// main = fmt.Println "Hello World!"
}

func ExampleFuncApplication_String_local() {
	fn := fun.FuncApplication{
		Func:      fun.FunctionVal{Name: "sum"},
		Arguments: []fun.Expression{fun.Int("1"), fun.Int("2")},
	}
	fmt.Println(fn)
	// Output:
	// sum 1 2
}

func ExampleFuncApplication_String_fmtPrintln() {
	fn := fun.FuncApplication{
		Func: fun.FunctionVal{
			Name:   "Println",
			Module: "fmt",
		},
		Arguments: []fun.Expression{fun.Float("4.2")},
	}
	fmt.Println(fn)
	// Output:
	// fmt.Println 4.2
}

func ExampleFuncApplication_String_nestedFunction() {
	fn := fun.FuncApplication{
		Func: fun.FunctionVal{Name: "take"},
		Arguments: []fun.Expression{
			fun.Int("3"),
			fun.FuncApplication{
				Func:      fun.FunctionVal{Name: "reverse"},
				Arguments: []fun.Expression{fun.Val("xs")},
			},
		},
	}
	fmt.Println(fn)
	// Output:
	// take 3 (reverse xs)
}

func ExampleFuncDecl_String_singleExprBody() {
	expr := fun.FuncApplication{
		Func: fun.FunctionVal{
			Name:   "Println",
			Module: "fmt",
		},
		Arguments: []fun.Expression{fun.Val("x")},
	}
	fn := fun.FuncDecl{
		Name:   "printInt",
		Params: fun.Parameters{fun.NewParam("x", "int")},
		Body:   fun.SingleExprBody{Expr: expr},
	}
	fmt.Println(fn)
	// Output:
	// printInt :: int -> ()
	// printInt x = fmt.Println x
}

func ExampleDoBlock_String_oneLine() {
	fn := fun.DoBlock{Text: []string{`fmt.Fprintf(&b, "world!")`}}
	fmt.Println(fn)
	// Output:
	// do
	//     fmt.Fprintf(&b, "world!")
}

func ExampleFuncDecl_String_doBlock_multiline() {
	fn := fun.FuncDecl{
		Name:   "printHash",
		Params: fun.Parameters{fun.NewParam("str", "string")},
		Body: fun.DoBlock{Text: []string{
			`h := md5.New()`,
			`io.WriteString(h, str)`,
			`fmt.Printf("%x", h.Sum(nil))`,
		}},
	}
	fmt.Println(fn)
	// Output:
	// printHash :: string -> ()
	// printHash str = do
	//     h := md5.New()
	//     io.WriteString(h, str)
	//     fmt.Printf("%x", h.Sum(nil))
}

func ExampleInfixOperation_String() {
	op := fun.InfixOperation{
		X:        fun.Val("x"),
		Operator: fun.Operator("+"),
		Y:        fun.Int("2"),
	}
	fmt.Println(op)
	// Output:
	// x + 2
}

func ExampleTuple_String() {
	t := fun.Tuple{
		fun.Val("operator"),
		fun.String("plus"),
	}
	fmt.Println(t)
	// Output:
	// (operator, "plus")
}
<|endoftext|>


<commit_before>package rc_value

import (
	"github.com/iancoleman/strcase"
	"github.com/watermint/toolbox/infra/app"
	"github.com/watermint/toolbox/infra/control/app_control"
	"github.com/watermint/toolbox/infra/feed/fd_file"
	"github.com/watermint/toolbox/infra/feed/fd_file_impl"
	"github.com/watermint/toolbox/infra/recipe/rc_recipe"
	"github.com/watermint/toolbox/infra/ui/app_msg"
	"github.com/watermint/toolbox/infra/ui/app_ui"
	"github.com/watermint/toolbox/infra/util/ut_reflect"
	"reflect"
	"strings"
)

func newValueFdFileRowFeed(name string) rc_recipe.Value {
	v := &ValueFdFileRowFeed{name: name}
	v.rf = fd_file_impl.NewRowFeed(name)
	return v
}

type ValueFdFileRowFeed struct {
	name string
	rf   fd_file.RowFeed
	path string
}

func (z *ValueFdFileRowFeed) Spec() (typeName string, typeAttr interface{}) {
	return ut_reflect.Key(app.Pkg, z.rf), nil
}

func (z *ValueFdFileRowFeed) ValueText() string {
	return z.path
}

func (z *ValueFdFileRowFeed) Accept(t reflect.Type, v0 interface{}, name string) rc_recipe.Value {
	if t.Implements(reflect.TypeOf((*fd_file.RowFeed)(nil)).Elem()) {
		return newValueFdFileRowFeed(name)
	}
	return nil
}

func (z *ValueFdFileRowFeed) Bind() interface{} {
	return &z.path
}

func (z *ValueFdFileRowFeed) Init() (v interface{}) {
	return z.rf
}

func (z *ValueFdFileRowFeed) ApplyPreset(v0 interface{}) {
	z.rf = v0.(fd_file.RowFeed)
	if z.rf.FilePath() != "" {
		z.path = z.rf.FilePath()
	}
}

func (z *ValueFdFileRowFeed) Apply() (v interface{}) {
	if z.path != "" {
		z.rf.SetFilePath(z.path)
	}
	return z.rf
}

func (z *ValueFdFileRowFeed) Debug() interface{} {
	return map[string]string{
		"path": z.path,
	}
}

func (z *ValueFdFileRowFeed) SpinUp(ctl app_control.Control) (err error) {
	if z.rf.FilePath() == "" {
		err = ErrorMissingRequiredOption
	} else {
		err = z.rf.Open(ctl)
	}
	if err != nil {
		ui := ctl.UI()
		ui.Break()
		ui.Header(MValFdFileRowFeed.HeadFeed.With("Name", strcase.ToSnake(z.rf.Spec().Name())))
		ui.Info(MValFdFileRowFeed.FeedDesc)

		FeedSpec(z.rf.Spec(), ctl.UI())
		return err
	}
	return nil
}

func (z *ValueFdFileRowFeed) SpinDown(ctl app_control.Control) error {
	return nil
}

func (z *ValueFdFileRowFeed) Feed() (feed fd_file.RowFeed, valid bool) {
	return z.rf, true
}

func FeedSpec(spec fd_file.Spec, ui app_ui.UI) {
	cols := spec.Columns()
	sampleCols := make([]string, 0)
	for _, col := range cols {
		sampleCols = append(sampleCols, ui.Text(spec.ColumnExample(col)))
	}
	ui.Info(MValFdFileRowFeed.FeedSample.
		With("Header", strings.Join(cols, ",")).
		With("Body", strings.Join(sampleCols, ",")))
	ui.Break()

	t := ui.InfoTable(spec.Name())

	t.Header(
		MValFdFileRowFeed.HeadColName,
		MValFdFileRowFeed.HeadColDesc,
		MValFdFileRowFeed.HeadColExample,
	)
	for _, col := range cols {
		t.Row(
			app_msg.M("raw", app_msg.P{"Raw": col}),
			spec.ColumnDesc(col),
			spec.ColumnExample(col),
		)
	}
	t.Flush()
	ui.Break()
}
<commit_msg>apply path variable to feed values<commit_after>package rc_value

import (
	"github.com/iancoleman/strcase"
	"github.com/watermint/toolbox/infra/app"
	"github.com/watermint/toolbox/infra/control/app_control"
	"github.com/watermint/toolbox/infra/control/app_root"
	"github.com/watermint/toolbox/infra/feed/fd_file"
	"github.com/watermint/toolbox/infra/feed/fd_file_impl"
	"github.com/watermint/toolbox/infra/recipe/rc_recipe"
	"github.com/watermint/toolbox/infra/ui/app_msg"
	"github.com/watermint/toolbox/infra/ui/app_ui"
	"github.com/watermint/toolbox/infra/util/ut_filepath"
	"github.com/watermint/toolbox/infra/util/ut_reflect"
	"go.uber.org/zap"
	"reflect"
	"strings"
)

func newValueFdFileRowFeed(name string) rc_recipe.Value {
	v := &ValueFdFileRowFeed{name: name}
	v.rf = fd_file_impl.NewRowFeed(name)
	return v
}

type ValueFdFileRowFeed struct {
	name string
	rf   fd_file.RowFeed
	path string
}

func (z *ValueFdFileRowFeed) Spec() (typeName string, typeAttr interface{}) {
	return ut_reflect.Key(app.Pkg, z.rf), nil
}

func (z *ValueFdFileRowFeed) ValueText() string {
	return z.path
}

func (z *ValueFdFileRowFeed) Accept(t reflect.Type, v0 interface{}, name string) rc_recipe.Value {
	if t.Implements(reflect.TypeOf((*fd_file.RowFeed)(nil)).Elem()) {
		return newValueFdFileRowFeed(name)
	}
	return nil
}

func (z *ValueFdFileRowFeed) Bind() interface{} {
	return &z.path
}

func (z *ValueFdFileRowFeed) Init() (v interface{}) {
	return z.rf
}

func (z *ValueFdFileRowFeed) ApplyPreset(v0 interface{}) {
	z.rf = v0.(fd_file.RowFeed)
	if z.rf.FilePath() != "" {
		z.path = z.rf.FilePath()
	}
}

func (z *ValueFdFileRowFeed) Apply() (v interface{}) {
	l := app_root.Log()
	p, err := ut_filepath.FormatPathWithPredefinedVariables(z.path)
	if err != nil {
		p = z.path
		l.Debug("Unable to format", zap.String("path", z.path), zap.Error(err))
	}

	if p != "" {
		z.rf.SetFilePath(p)
	}
	return z.rf
}

func (z *ValueFdFileRowFeed) Debug() interface{} {
	return map[string]string{
		"path": z.path,
	}
}

func (z *ValueFdFileRowFeed) SpinUp(ctl app_control.Control) (err error) {
	if z.rf.FilePath() == "" {
		err = ErrorMissingRequiredOption
	} else {
		err = z.rf.Open(ctl)
	}
	if err != nil {
		ui := ctl.UI()
		ui.Break()
		ui.Header(MValFdFileRowFeed.HeadFeed.With("Name", strcase.ToSnake(z.rf.Spec().Name())))
		ui.Info(MValFdFileRowFeed.FeedDesc)

		FeedSpec(z.rf.Spec(), ctl.UI())
		return err
	}
	return nil
}

func (z *ValueFdFileRowFeed) SpinDown(ctl app_control.Control) error {
	return nil
}

func (z *ValueFdFileRowFeed) Feed() (feed fd_file.RowFeed, valid bool) {
	return z.rf, true
}

func FeedSpec(spec fd_file.Spec, ui app_ui.UI) {
	cols := spec.Columns()
	sampleCols := make([]string, 0)
	for _, col := range cols {
		sampleCols = append(sampleCols, ui.Text(spec.ColumnExample(col)))
	}
	ui.Info(MValFdFileRowFeed.FeedSample.
		With("Header", strings.Join(cols, ",")).
		With("Body", strings.Join(sampleCols, ",")))
	ui.Break()

	t := ui.InfoTable(spec.Name())

	t.Header(
		MValFdFileRowFeed.HeadColName,
		MValFdFileRowFeed.HeadColDesc,
		MValFdFileRowFeed.HeadColExample,
	)
	for _, col := range cols {
		t.Row(
			app_msg.M("raw", app_msg.P{"Raw": col}),
			spec.ColumnDesc(col),
			spec.ColumnExample(col),
		)
	}
	t.Flush()
	ui.Break()
}
<|endoftext|>


<commit_before>// Copyright 2014 mqant Author. 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 gate

import (
	"fmt"
	"github.com/golang/protobuf/proto"
	"github.com/liangdas/mqant/module"
)

type sessionagent struct {
	app       module.App
	session   *session
}

func NewSession(app module.App, data []byte) (Session,error) {
	agent:=&sessionagent{
		app:app,
	}
	se := &session{}
	err := proto.Unmarshal(data, se)
	if err != nil {
		return nil,err
	}    // 测试结果
	agent.session=se
	return agent,nil
}

func NewSessionByMap(app module.App, data map[string]interface{}) (Session,error) {
	agent:=&sessionagent{
		app:app,
		session:new(session),
	}
	err:=agent.updateMap(data)
	if err!=nil{
		return nil,err
	}
	return agent,nil
}

func (session *sessionagent) GetIP() string {
	return session.session.GetIP()
}

func (session *sessionagent) GetNetwork() string {
	return session.session.GetNetwork()
}

func (session *sessionagent) GetUserid() string {
	return session.session.GetUserid()
}

func (session *sessionagent) GetSessionid() string {
	return session.session.GetSessionid()
}

func (session *sessionagent) GetServerid() string {
	return session.session.GetServerid()
}

func (session *sessionagent) GetSettings() map[string]string {
	return session.session.GetSettings()
}

func (session *sessionagent)SetIP(ip string){
	session.session.IP=ip
}
func (session *sessionagent)SetNetwork(network string){
	session.session.Network=network
}
func (session *sessionagent)SetUserid(userid string){
	session.session.Userid=userid
}
func (session *sessionagent)SetSessionid(sessionid string){
	session.session.Sessionid=sessionid
}
func (session *sessionagent)SetServerid(serverid string){
	session.session.Serverid=serverid
}
func (session *sessionagent)SetSettings(settings map[string]string){
	session.session.Settings=settings
}

func (session *sessionagent) updateMap(s map[string]interface{})error {
	Userid := s["Userid"]
	if Userid != nil {
		session.session.Userid = Userid.(string)
	}
	IP := s["IP"]
	if IP != nil {
		session.session.IP = IP.(string)
	}
	Network := s["Network"]
	if Network != nil {
		session.session.Network = Network.(string)
	}
	Sessionid := s["Sessionid"]
	if Sessionid != nil {
		session.session.Sessionid = Sessionid.(string)
	}
	Serverid := s["Serverid"]
	if Serverid != nil {
		session.session.Serverid = Serverid.(string)
	}
	Settings := s["Settings"]
	if Settings != nil {
		session.session.Settings = Settings.(map[string]string)
	}
	return nil
}

func (session *sessionagent) update(s Session)error {
	Userid := s.GetUserid()
	session.session.Userid = Userid
	IP := s.GetIP()
	session.session.IP = IP
	Network := s.GetNetwork()
	session.session.Network = Network
	Sessionid := s.GetSessionid()
	session.session.Sessionid = Sessionid
	Serverid := s.GetServerid()
	session.session.Serverid = Serverid
	Settings := s.GetSettings()
	session.session.Settings = Settings
	return nil
}

func (session *sessionagent)Serializable()([]byte,error){
	data, err := proto.Marshal(session.session)
	if err != nil {
		return nil,err
	}    // 进行解码
	return data,nil
}

func (session *sessionagent) Update() (err string) {
	if session.app == nil {
		err = fmt.Sprintf("Module.App is nil")
		return
	}
	server, e := session.app.GetServersById(session.session.Serverid)
	if e != nil {
		err = fmt.Sprintf("Service not found id(%s)", session.session.Serverid)
		return
	}
	result, err := server.Call("Update", session.session.Sessionid)
	if err == "" {
		if result != nil {
			//绑定成功,重新更新当前Session
			session.update(result.(Session))
		}
	}
	return
}

func (session *sessionagent) Bind(Userid string) (err string) {
	if session.app == nil {
		err = fmt.Sprintf("Module.App is nil")
		return
	}
	server, e := session.app.GetServersById(session.session.Serverid)
	if e != nil {
		err = fmt.Sprintf("Service not found id(%s)", session.session.Serverid)
		return
	}
	result, err := server.Call("Bind", session.session.Sessionid, Userid)
	if err == "" {
		if result != nil {
			//绑定成功,重新更新当前Session
			session.update(result.(Session))
		}
	}
	return
}

func (session *sessionagent) UnBind() (err string) {
	if session.app == nil {
		err = fmt.Sprintf("Module.App is nil")
		return
	}
	server, e := session.app.GetServersById(session.session.Serverid)
	if e != nil {
		err = fmt.Sprintf("Service not found id(%s)", session.session.Serverid)
		return
	}
	result, err := server.Call("UnBind", session.session.Sessionid)
	if err == "" {
		if result != nil {
			//绑定成功,重新更新当前Session
			session.update(result.(Session))
		}
	}
	return
}

func (session *sessionagent) Push() (err string) {
	if session.app == nil {
		err = fmt.Sprintf("Module.App is nil")
		return
	}
	server, e := session.app.GetServersById(session.session.Serverid)
	if e != nil {
		err = fmt.Sprintf("Service not found id(%s)", session.session.Serverid)
		return
	}
	result, err := server.Call("Push", session.session.Sessionid, session.session.Settings)
	if err == "" {
		if result != nil {
			//绑定成功,重新更新当前Session
			session.update(result.(Session))
		}
	}
	return
}

func (session *sessionagent) Set(key string, value string) (err string) {
	if session.app == nil {
		err = fmt.Sprintf("Module.App is nil")
		return
	}
	if session.session.Settings == nil {
		err = fmt.Sprintf("Session.Settings is nil")
		return
	}
	session.session.Settings[key] = value
	//server,e:=session.app.GetServersById(session.Serverid)
	//if e!=nil{
	//	err=fmt.Sprintf("Service not found id(%s)",session.Serverid)
	//	return
	//}
	//result,err:=server.Call("Set",session.Sessionid,key,value)
	//if err==""{
	//	if result!=nil{
	//		//绑定成功,重新更新当前Session
	//		session.update(result.(map[string]interface {}))
	//	}
	//}
	return
}

func (session *sessionagent) Get(key string) (result string) {
	if session.session.Settings == nil {
		return
	}
	result = session.session.Settings[key]
	return
}

func (session *sessionagent) Remove(key string) (err string) {
	if session.app == nil {
		err = fmt.Sprintf("Module.App is nil")
		return
	}
	if session.session.Settings == nil {
		err = fmt.Sprintf("Session.Settings is nil")
		return
	}
	delete(session.session.Settings, key)
	//server,e:=session.app.GetServersById(session.Serverid)
	//if e!=nil{
	//	err=fmt.Sprintf("Service not found id(%s)",session.Serverid)
	//	return
	//}
	//result,err:=server.Call("Remove",session.Sessionid,key)
	//if err==""{
	//	if result!=nil{
	//		//绑定成功,重新更新当前Session
	//		session.update(result.(map[string]interface {}))
	//	}
	//}
	return
}
func (session *sessionagent) Send(topic string, body []byte) (err string) {
	if session.app == nil {
		err = fmt.Sprintf("Module.App is nil")
		return
	}
	server, e := session.app.GetServersById(session.session.Serverid)
	if e != nil {
		err = fmt.Sprintf("Service not found id(%s)", session.session.Serverid)
		return
	}
	_, err = server.Call("Send", session.session.Sessionid, topic, body)
	return
}

func (session *sessionagent) SendNR(topic string, body []byte) (err string) {
	if session.app == nil {
		err = fmt.Sprintf("Module.App is nil")
		return
	}
	server, e := session.app.GetServersById(session.session.Serverid)
	if e != nil {
		err = fmt.Sprintf("Service not found id(%s)", session.session.Serverid)
		return
	}
	e = server.CallNR("Send", session.session.Sessionid, topic, body)
	if e != nil {
		err = e.Error()
	}
	return ""
}

func (session *sessionagent) Close() (err string) {
	if session.app == nil {
		err = fmt.Sprintf("Module.App is nil")
		return
	}
	server, e := session.app.GetServersById(session.session.Serverid)
	if e != nil {
		err = fmt.Sprintf("Service not found id(%s)", session.session.Serverid)
		return
	}
	_, err = server.Call("Close", session.session.Sessionid)
	return
}
<commit_msg>=修改session修改属性的bug<commit_after>// Copyright 2014 mqant Author. 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 gate

import (
	"fmt"
	"github.com/golang/protobuf/proto"
	"github.com/liangdas/mqant/module"
)

type sessionagent struct {
	app       module.App
	session   *session
}

func NewSession(app module.App, data []byte) (Session,error) {
	agent:=&sessionagent{
		app:app,
	}
	se := &session{}
	err := proto.Unmarshal(data, se)
	if err != nil {
		return nil,err
	}    // 测试结果
	agent.session=se
	return agent,nil
}

func NewSessionByMap(app module.App, data map[string]interface{}) (Session,error) {
	agent:=&sessionagent{
		app:app,
		session:new(session),
	}
	err:=agent.updateMap(data)
	if err!=nil{
		return nil,err
	}
	return agent,nil
}

func (session *sessionagent) GetIP() string {
	return session.session.GetIP()
}

func (session *sessionagent) GetNetwork() string {
	return session.session.GetNetwork()
}

func (session *sessionagent) GetUserid() string {
	return session.session.GetUserid()
}

func (session *sessionagent) GetSessionid() string {
	return session.session.GetSessionid()
}

func (session *sessionagent) GetServerid() string {
	return session.session.GetServerid()
}

func (session *sessionagent) GetSettings() map[string]string {
	return session.session.GetSettings()
}

func (session *sessionagent)SetIP(ip string){
	session.session.IP=ip
}
func (session *sessionagent)SetNetwork(network string){
	session.session.Network=network
}
func (session *sessionagent)SetUserid(userid string){
	session.session.Userid=userid
}
func (session *sessionagent)SetSessionid(sessionid string){
	session.session.Sessionid=sessionid
}
func (session *sessionagent)SetServerid(serverid string){
	session.session.Serverid=serverid
}
func (session *sessionagent)SetSettings(settings map[string]string){
	session.session.Settings=settings
}

func (session *sessionagent) updateMap(s map[string]interface{})error {
	Userid := s["Userid"]
	if Userid != nil {
		session.session.Userid = Userid.(string)
	}
	IP := s["IP"]
	if IP != nil {
		session.session.IP = IP.(string)
	}
	Network := s["Network"]
	if Network != nil {
		session.session.Network = Network.(string)
	}
	Sessionid := s["Sessionid"]
	if Sessionid != nil {
		session.session.Sessionid = Sessionid.(string)
	}
	Serverid := s["Serverid"]
	if Serverid != nil {
		session.session.Serverid = Serverid.(string)
	}
	Settings := s["Settings"]
	if Settings != nil {
		session.session.Settings = Settings.(map[string]string)
	}
	return nil
}

func (session *sessionagent) update(s Session)error {
	Userid := s.GetUserid()
	session.session.Userid = Userid
	IP := s.GetIP()
	session.session.IP = IP
	Network := s.GetNetwork()
	session.session.Network = Network
	Sessionid := s.GetSessionid()
	session.session.Sessionid = Sessionid
	Serverid := s.GetServerid()
	session.session.Serverid = Serverid
	Settings := s.GetSettings()
	session.session.Settings = Settings
	return nil
}

func (session *sessionagent)Serializable()([]byte,error){
	data, err := proto.Marshal(session.session)
	if err != nil {
		return nil,err
	}    // 进行解码
	return data,nil
}

func (session *sessionagent) Update() (err string) {
	if session.app == nil {
		err = fmt.Sprintf("Module.App is nil")
		return
	}
	server, e := session.app.GetServersById(session.session.Serverid)
	if e != nil {
		err = fmt.Sprintf("Service not found id(%s)", session.session.Serverid)
		return
	}
	result, err := server.Call("Update", session.session.Sessionid)
	if err == "" {
		if result != nil {
			//绑定成功,重新更新当前Session
			session.update(result.(Session))
		}
	}
	return
}

func (session *sessionagent) Bind(Userid string) (err string) {
	if session.app == nil {
		err = fmt.Sprintf("Module.App is nil")
		return
	}
	server, e := session.app.GetServersById(session.session.Serverid)
	if e != nil {
		err = fmt.Sprintf("Service not found id(%s)", session.session.Serverid)
		return
	}
	result, err := server.Call("Bind", session.session.Sessionid, Userid)
	if err == "" {
		if result != nil {
			//绑定成功,重新更新当前Session
			session.update(result.(Session))
		}
	}
	return
}

func (session *sessionagent) UnBind() (err string) {
	if session.app == nil {
		err = fmt.Sprintf("Module.App is nil")
		return
	}
	server, e := session.app.GetServersById(session.session.Serverid)
	if e != nil {
		err = fmt.Sprintf("Service not found id(%s)", session.session.Serverid)
		return
	}
	result, err := server.Call("UnBind", session.session.Sessionid)
	if err == "" {
		if result != nil {
			//绑定成功,重新更新当前Session
			session.update(result.(Session))
		}
	}
	return
}

func (session *sessionagent) Push() (err string) {
	if session.app == nil {
		err = fmt.Sprintf("Module.App is nil")
		return
	}
	server, e := session.app.GetServersById(session.session.Serverid)
	if e != nil {
		err = fmt.Sprintf("Service not found id(%s)", session.session.Serverid)
		return
	}
	result, err := server.Call("Push", session.session.Sessionid, session.session.Settings)
	if err == "" {
		if result != nil {
			//绑定成功,重新更新当前Session
			session.update(result.(Session))
		}
	}
	return
}

func (session *sessionagent) Set(key string, value string) (err string) {
	if session.app == nil {
		err = fmt.Sprintf("Module.App is nil")
		return
	}
	if session.session.Settings == nil {
		session.session.Settings=map[string]string{}
	}
	session.session.Settings[key] = value
	//server,e:=session.app.GetServersById(session.Serverid)
	//if e!=nil{
	//	err=fmt.Sprintf("Service not found id(%s)",session.Serverid)
	//	return
	//}
	//result,err:=server.Call("Set",session.Sessionid,key,value)
	//if err==""{
	//	if result!=nil{
	//		//绑定成功,重新更新当前Session
	//		session.update(result.(map[string]interface {}))
	//	}
	//}
	return
}

func (session *sessionagent) Get(key string) (result string) {
	if session.session.Settings == nil {
		return
	}
	result = session.session.Settings[key]
	return
}

func (session *sessionagent) Remove(key string) (err string) {
	if session.app == nil {
		err = fmt.Sprintf("Module.App is nil")
		return
	}
	if session.session.Settings == nil {
		session.session.Settings=map[string]string{}
	}
	delete(session.session.Settings, key)
	//server,e:=session.app.GetServersById(session.Serverid)
	//if e!=nil{
	//	err=fmt.Sprintf("Service not found id(%s)",session.Serverid)
	//	return
	//}
	//result,err:=server.Call("Remove",session.Sessionid,key)
	//if err==""{
	//	if result!=nil{
	//		//绑定成功,重新更新当前Session
	//		session.update(result.(map[string]interface {}))
	//	}
	//}
	return
}
func (session *sessionagent) Send(topic string, body []byte) (err string) {
	if session.app == nil {
		err = fmt.Sprintf("Module.App is nil")
		return
	}
	server, e := session.app.GetServersById(session.session.Serverid)
	if e != nil {
		err = fmt.Sprintf("Service not found id(%s)", session.session.Serverid)
		return
	}
	_, err = server.Call("Send", session.session.Sessionid, topic, body)
	return
}

func (session *sessionagent) SendNR(topic string, body []byte) (err string) {
	if session.app == nil {
		err = fmt.Sprintf("Module.App is nil")
		return
	}
	server, e := session.app.GetServersById(session.session.Serverid)
	if e != nil {
		err = fmt.Sprintf("Service not found id(%s)", session.session.Serverid)
		return
	}
	e = server.CallNR("Send", session.session.Sessionid, topic, body)
	if e != nil {
		err = e.Error()
	}
	return ""
}

func (session *sessionagent) Close() (err string) {
	if session.app == nil {
		err = fmt.Sprintf("Module.App is nil")
		return
	}
	server, e := session.app.GetServersById(session.session.Serverid)
	if e != nil {
		err = fmt.Sprintf("Service not found id(%s)", session.session.Serverid)
		return
	}
	_, err = server.Call("Close", session.session.Sessionid)
	return
}
<|endoftext|>