<commit_before>package shell

import (
	"context"
	"errors"
	"fmt"
	"io"
	"os"
	"os/exec"
	"reflect"
	"strings"
	"sync"
	"syscall"

	"github.com/zetamatta/go-findfile"

	"github.com/zetamatta/nyagos/defined"
	"github.com/zetamatta/nyagos/dos"
)

var WildCardExpansionAlways = false

type CommandNotFound struct {
	Name string
	Err  error
}

// from "TDM-GCC-64/x86_64-w64-mingw32/include/winbase.h"
const (
	CREATE_NEW_CONSOLE       = 0x10
	CREATE_NEW_PROCESS_GROUP = 0x200
)

func (this CommandNotFound) Stringer() string {
	return fmt.Sprintf("'%s' is not recognized as an internal or external command,\noperable program or batch file", this.Name)
}

func (this CommandNotFound) Error() string {
	return this.Stringer()
}

func isElevationRequired(err error) bool {
	e, ok := err.(*os.PathError)
	return ok && e.Err == syscall.Errno(0x2e4)
}

type session struct {
	unreadline []string
}

type Cmd struct {
	*session
	Stdout       *os.File
	Stderr       *os.File
	Stdin        *os.File
	Args         []string
	HookCount    int
	Tag          interface{}
	PipeSeq      [2]uint
	IsBackGround bool
	RawArgs      []string

	OnFork          func(*Cmd) error
	OffFork         func(*Cmd) error
	Closers         []io.Closer
	fullPath        string
	UseShellExecute bool
}

func (this *Cmd) FullPath() string {
	if this.Args == nil || len(this.Args) <= 0 {
		return ""
	}
	if this.fullPath == "" {
		this.fullPath = dos.LookPath(this.Args[0], "NYAGOSPATH")
	}
	return this.fullPath
}

func (this *Cmd) GetRawArgs() []string {
	return this.RawArgs
}

func (this *Cmd) Close() {
	if this.Closers != nil {
		for _, c := range this.Closers {
			c.Close()
		}
		this.Closers = nil
	}
}

func New() *Cmd {
	this := Cmd{
		Stdin:  os.Stdin,
		Stdout: os.Stdout,
		Stderr: os.Stderr,
	}
	this.PipeSeq[0] = pipeSeq
	this.PipeSeq[1] = 0
	this.session = &session{}
	return &this
}

func (this *Cmd) Clone() (*Cmd, error) {
	rv := new(Cmd)
	rv.Args = this.Args
	rv.RawArgs = this.RawArgs
	rv.Stdin = this.Stdin
	rv.Stdout = this.Stdout
	rv.Stderr = this.Stderr
	rv.HookCount = this.HookCount
	rv.Tag = this.Tag
	rv.PipeSeq = this.PipeSeq
	rv.Closers = nil
	rv.OnFork = this.OnFork
	rv.OffFork = this.OffFork
	if this.session != nil {
		rv.session = this.session
	} else {
		rv.session = &session{}
	}
	return rv, nil
}

type ArgsHookT func(it *Cmd, args []string) ([]string, error)

var argsHook = func(it *Cmd, args []string) ([]string, error) {
	return args, nil
}

func SetArgsHook(argsHook_ ArgsHookT) (rv ArgsHookT) {
	rv, argsHook = argsHook, argsHook_
	return
}

type HookT func(context.Context, *Cmd) (int, bool, error)

var hook = func(context.Context, *Cmd) (int, bool, error) {
	return 0, false, nil
}

func SetHook(hook_ HookT) (rv HookT) {
	rv, hook = hook, hook_
	return
}

var OnCommandNotFound = func(this *Cmd, err error) error {
	err = &CommandNotFound{this.Args[0], err}
	return err
}

var LastErrorLevel int

func nvl(a *os.File, b *os.File) *os.File {
	if a != nil {
		return a
	} else {
		return b
	}
}

func makeCmdline(args, rawargs []string) string {
	var buffer strings.Builder
	for i, s := range args {
		if i > 0 {
			buffer.WriteRune(' ')
		}
		if (len(rawargs) > i && len(rawargs[i]) > 0 && rawargs[i][0] == '"') || strings.ContainsAny(s, " &|<>\t\"") {
			fmt.Fprintf(&buffer, `"%s"`, strings.Replace(s, `"`, `\"`, -1))
		} else {
			buffer.WriteString(s)
		}
	}
	return buffer.String()
}

func (this *Cmd) spawnvp_noerrmsg(ctx context.Context) (int, error) {
	// command is empty.
	if len(this.Args) <= 0 {
		return 0, nil
	}
	if defined.DBG {
		print("spawnvp_noerrmsg('", this.Args[0], "')\n")
	}

	// aliases and lua-commands
	if errorlevel, done, err := hook(ctx, this); done || err != nil {
		return errorlevel, err
	}

	// command not found hook
	var err error
	path1 := this.FullPath()
	if path1 == "" {
		return 255, OnCommandNotFound(this, os.ErrNotExist)
	}
	this.Args[0] = path1

	if defined.DBG {
		print("exec.LookPath(", this.Args[0], ")==", path1, "\n")
	}
	if WildCardExpansionAlways {
		this.Args = findfile.Globs(this.Args)
	}
	if this.UseShellExecute {
		cmdline := makeCmdline(this.Args[1:], this.RawArgs[1:])
		err = dos.ShellExecute("open", dos.TruePath(this.Args[0]), cmdline, "")
		return 0, err
	} else {
		cmd1 := exec.Command(this.Args[0], this.Args[1:]...)
		cmd1.Stdin = this.Stdin
		cmd1.Stdout = this.Stdout
		cmd1.Stderr = this.Stderr

		if cmd1.SysProcAttr == nil {
			cmd1.SysProcAttr = new(syscall.SysProcAttr)
		}
		cmdline := makeCmdline(cmd1.Args, this.RawArgs)
		if defined.DBG {
			println(cmdline)
		}
		cmd1.SysProcAttr.CmdLine = cmdline
		err = cmd1.Run()
		if isElevationRequired(err) {
			cmdline := ""
			if len(cmd1.Args) >= 2 {
				cmdline = makeCmdline(cmd1.Args[1:], this.RawArgs[1:])
			}
			if defined.DBG {
				println("ShellExecute:Path=" + cmd1.Args[0])
				println("Args=" + cmdline)
			}
			err = dos.ShellExecute("open", dos.TruePath(cmd1.Args[0]), cmdline, "")
			return 0, err
		} else {
			errorlevel, errorlevelOk := dos.GetErrorLevel(cmd1)
			if errorlevelOk {
				return errorlevel, err
			} else {
				return 255, err
			}
		}
	}
}

type AlreadyReportedError struct {
	Err error
}

func (this AlreadyReportedError) Error() string {
	return ""
}

func IsAlreadyReported(err error) bool {
	_, ok := err.(AlreadyReportedError)
	return ok
}

func (this *Cmd) Spawnvp() (int, error) {
	return this.SpawnvpContext(context.Background())
}

func (this *Cmd) SpawnvpContext(ctx context.Context) (int, error) {
	errorlevel, err := this.spawnvp_noerrmsg(ctx)
	if err != nil && err != io.EOF && !IsAlreadyReported(err) {
		if defined.DBG {
			val := reflect.ValueOf(err)
			fmt.Fprintf(this.Stderr, "error-type=%s\n", val.Type())
		}
		fmt.Fprintln(this.Stderr, err.Error())
		err = AlreadyReportedError{err}
	}
	return errorlevel, err
}

var pipeSeq uint = 0

func (this *Cmd) Interpret(text string) (int, error) {
	return this.InterpretContext(context.Background(), text)
}

func (this *Cmd) InterpretContext(ctx context.Context, text string) (errorlevel int, finalerr error) {
	if defined.DBG {
		print("Interpret('", text, "')\n")
	}
	if this == nil {
		return 255, errors.New("Fatal Error: Interpret: instance is nil")
	}
	errorlevel = 0
	finalerr = nil

	statements, statementsErr := Parse(text)
	if statementsErr != nil {
		if defined.DBG {
			print("Parse Error:", statementsErr.Error(), "\n")
		}
		return 0, statementsErr
	}
	if argsHook != nil {
		if defined.DBG {
			print("call argsHook\n")
		}
		for _, pipeline := range statements {
			for _, state := range pipeline {
				var err error
				state.Args, err = argsHook(this, state.Args)
				if err != nil {
					return 255, err
				}
			}
		}
		if defined.DBG {
			print("done argsHook\n")
		}
	}
	for _, pipeline := range statements {
		for i, state := range pipeline {
			if state.Term == "|" && (i+1 >= len(pipeline) || len(pipeline[i+1].Args) <= 0) {
				return 255, errors.New("The syntax of the command is incorrect.")
			}
		}
	}

	for _, pipeline := range statements {

		var pipeIn *os.File = nil
		pipeSeq++
		isBackGround := this.IsBackGround
		for _, state := range pipeline {
			if state.Term == "&" {
				isBackGround = true
				break
			}
		}
		var wg sync.WaitGroup
		shutdown_immediately := false
		for i, state := range pipeline {
			if defined.DBG {
				print(i, ": pipeline loop(", state.Args[0], ")\n")
			}
			cmd, err := this.Clone()
			if err != nil {
				return 255, err
			}
			cmd.PipeSeq[0] = pipeSeq
			cmd.PipeSeq[1] = uint(1 + i)
			cmd.IsBackGround = isBackGround

			if pipeIn != nil {
				cmd.Stdin = pipeIn
				cmd.Closers = append(cmd.Closers, pipeIn)
				pipeIn = nil
			}

			if state.Term[0] == '|' {
				var pipeOut *os.File
				pipeIn, pipeOut, err = os.Pipe()
				cmd.Stdout = pipeOut
				if state.Term == "|&" {
					cmd.Stderr = pipeOut
				}
				cmd.Closers = append(cmd.Closers, pipeOut)
			}

			for _, red := range state.Redirect {
				var fd *os.File
				fd, err = red.OpenOn(cmd)
				if err != nil {
					return 0, err
				}
				defer fd.Close()
			}

			cmd.Args = state.Args
			cmd.RawArgs = state.RawArgs
			if i > 0 {
				cmd.IsBackGround = true
			}
			if len(pipeline) == 1 && dos.IsGui(cmd.FullPath()) {
				cmd.UseShellExecute = true
			}
			if i == len(pipeline)-1 && state.Term != "&" {
				// foreground execution.
				errorlevel, finalerr = cmd.SpawnvpContext(ctx)
				LastErrorLevel = errorlevel
				cmd.Close()
			} else {
				// background
				if !isBackGround {
					wg.Add(1)
				}
				if cmd.OnFork != nil {
					if err := cmd.OnFork(cmd); err != nil {
						fmt.Fprintln(cmd.Stderr, err.Error())
						return -1, err
					}
				}
				go func(cmd1 *Cmd) {
					if !isBackGround {
						defer wg.Done()
					}
					cmd1.SpawnvpContext(ctx)
					if cmd1.OffFork != nil {
						if err := cmd1.OffFork(cmd1); err != nil {
							fmt.Fprintln(cmd1.Stderr, err.Error())
							goto exit
						}
					}
				exit:
					cmd1.Close()
				}(cmd)
			}
		}
		if !isBackGround {
			wg.Wait()
			if shutdown_immediately {
				return errorlevel, nil
			}
			if len(pipeline) > 0 {
				switch pipeline[len(pipeline)-1].Term {
				case "&&":
					if errorlevel != 0 {
						return errorlevel, nil
					}
				case "||":
					if errorlevel == 0 {
						return errorlevel, nil
					}
				}
			}
		}
	}
	return
}
<commit_msg>Remove the check code that the error that elevation is required<commit_after>package shell

import (
	"context"
	"errors"
	"fmt"
	"io"
	"os"
	"os/exec"
	"reflect"
	"strings"
	"sync"
	"syscall"

	"github.com/zetamatta/go-findfile"

	"github.com/zetamatta/nyagos/defined"
	"github.com/zetamatta/nyagos/dos"
)

var WildCardExpansionAlways = false

type CommandNotFound struct {
	Name string
	Err  error
}

// from "TDM-GCC-64/x86_64-w64-mingw32/include/winbase.h"
const (
	CREATE_NEW_CONSOLE       = 0x10
	CREATE_NEW_PROCESS_GROUP = 0x200
)

func (this CommandNotFound) Stringer() string {
	return fmt.Sprintf("'%s' is not recognized as an internal or external command,\noperable program or batch file", this.Name)
}

func (this CommandNotFound) Error() string {
	return this.Stringer()
}

type session struct {
	unreadline []string
}

type Cmd struct {
	*session
	Stdout       *os.File
	Stderr       *os.File
	Stdin        *os.File
	Args         []string
	HookCount    int
	Tag          interface{}
	PipeSeq      [2]uint
	IsBackGround bool
	RawArgs      []string

	OnFork          func(*Cmd) error
	OffFork         func(*Cmd) error
	Closers         []io.Closer
	fullPath        string
	UseShellExecute bool
}

func (this *Cmd) FullPath() string {
	if this.Args == nil || len(this.Args) <= 0 {
		return ""
	}
	if this.fullPath == "" {
		this.fullPath = dos.LookPath(this.Args[0], "NYAGOSPATH")
	}
	return this.fullPath
}

func (this *Cmd) GetRawArgs() []string {
	return this.RawArgs
}

func (this *Cmd) Close() {
	if this.Closers != nil {
		for _, c := range this.Closers {
			c.Close()
		}
		this.Closers = nil
	}
}

func New() *Cmd {
	this := Cmd{
		Stdin:  os.Stdin,
		Stdout: os.Stdout,
		Stderr: os.Stderr,
	}
	this.PipeSeq[0] = pipeSeq
	this.PipeSeq[1] = 0
	this.session = &session{}
	return &this
}

func (this *Cmd) Clone() (*Cmd, error) {
	rv := new(Cmd)
	rv.Args = this.Args
	rv.RawArgs = this.RawArgs
	rv.Stdin = this.Stdin
	rv.Stdout = this.Stdout
	rv.Stderr = this.Stderr
	rv.HookCount = this.HookCount
	rv.Tag = this.Tag
	rv.PipeSeq = this.PipeSeq
	rv.Closers = nil
	rv.OnFork = this.OnFork
	rv.OffFork = this.OffFork
	if this.session != nil {
		rv.session = this.session
	} else {
		rv.session = &session{}
	}
	return rv, nil
}

type ArgsHookT func(it *Cmd, args []string) ([]string, error)

var argsHook = func(it *Cmd, args []string) ([]string, error) {
	return args, nil
}

func SetArgsHook(argsHook_ ArgsHookT) (rv ArgsHookT) {
	rv, argsHook = argsHook, argsHook_
	return
}

type HookT func(context.Context, *Cmd) (int, bool, error)

var hook = func(context.Context, *Cmd) (int, bool, error) {
	return 0, false, nil
}

func SetHook(hook_ HookT) (rv HookT) {
	rv, hook = hook, hook_
	return
}

var OnCommandNotFound = func(this *Cmd, err error) error {
	err = &CommandNotFound{this.Args[0], err}
	return err
}

var LastErrorLevel int

func nvl(a *os.File, b *os.File) *os.File {
	if a != nil {
		return a
	} else {
		return b
	}
}

func makeCmdline(args, rawargs []string) string {
	var buffer strings.Builder
	for i, s := range args {
		if i > 0 {
			buffer.WriteRune(' ')
		}
		if (len(rawargs) > i && len(rawargs[i]) > 0 && rawargs[i][0] == '"') || strings.ContainsAny(s, " &|<>\t\"") {
			fmt.Fprintf(&buffer, `"%s"`, strings.Replace(s, `"`, `\"`, -1))
		} else {
			buffer.WriteString(s)
		}
	}
	return buffer.String()
}

func (this *Cmd) spawnvp_noerrmsg(ctx context.Context) (int, error) {
	// command is empty.
	if len(this.Args) <= 0 {
		return 0, nil
	}
	if defined.DBG {
		print("spawnvp_noerrmsg('", this.Args[0], "')\n")
	}

	// aliases and lua-commands
	if errorlevel, done, err := hook(ctx, this); done || err != nil {
		return errorlevel, err
	}

	// command not found hook
	var err error
	path1 := this.FullPath()
	if path1 == "" {
		return 255, OnCommandNotFound(this, os.ErrNotExist)
	}
	this.Args[0] = path1

	if defined.DBG {
		print("exec.LookPath(", this.Args[0], ")==", path1, "\n")
	}
	if WildCardExpansionAlways {
		this.Args = findfile.Globs(this.Args)
	}
	if this.UseShellExecute {
		cmdline := makeCmdline(this.Args[1:], this.RawArgs[1:])
		err = dos.ShellExecute("open", path1, cmdline, "")
		return 0, err
	} else {
		cmd1 := exec.Command(this.Args[0], this.Args[1:]...)
		cmd1.Stdin = this.Stdin
		cmd1.Stdout = this.Stdout
		cmd1.Stderr = this.Stderr

		if cmd1.SysProcAttr == nil {
			cmd1.SysProcAttr = new(syscall.SysProcAttr)
		}
		cmdline := makeCmdline(cmd1.Args, this.RawArgs)
		if defined.DBG {
			println(cmdline)
		}
		cmd1.SysProcAttr.CmdLine = cmdline
		err = cmd1.Run()
		errorlevel, errorlevelOk := dos.GetErrorLevel(cmd1)
		if errorlevelOk {
			return errorlevel, err
		} else {
			return 255, err
		}
	}
}

type AlreadyReportedError struct {
	Err error
}

func (this AlreadyReportedError) Error() string {
	return ""
}

func IsAlreadyReported(err error) bool {
	_, ok := err.(AlreadyReportedError)
	return ok
}

func (this *Cmd) Spawnvp() (int, error) {
	return this.SpawnvpContext(context.Background())
}

func (this *Cmd) SpawnvpContext(ctx context.Context) (int, error) {
	errorlevel, err := this.spawnvp_noerrmsg(ctx)
	if err != nil && err != io.EOF && !IsAlreadyReported(err) {
		if defined.DBG {
			val := reflect.ValueOf(err)
			fmt.Fprintf(this.Stderr, "error-type=%s\n", val.Type())
		}
		fmt.Fprintln(this.Stderr, err.Error())
		err = AlreadyReportedError{err}
	}
	return errorlevel, err
}

var pipeSeq uint = 0

func (this *Cmd) Interpret(text string) (int, error) {
	return this.InterpretContext(context.Background(), text)
}

func (this *Cmd) InterpretContext(ctx context.Context, text string) (errorlevel int, finalerr error) {
	if defined.DBG {
		print("Interpret('", text, "')\n")
	}
	if this == nil {
		return 255, errors.New("Fatal Error: Interpret: instance is nil")
	}
	errorlevel = 0
	finalerr = nil

	statements, statementsErr := Parse(text)
	if statementsErr != nil {
		if defined.DBG {
			print("Parse Error:", statementsErr.Error(), "\n")
		}
		return 0, statementsErr
	}
	if argsHook != nil {
		if defined.DBG {
			print("call argsHook\n")
		}
		for _, pipeline := range statements {
			for _, state := range pipeline {
				var err error
				state.Args, err = argsHook(this, state.Args)
				if err != nil {
					return 255, err
				}
			}
		}
		if defined.DBG {
			print("done argsHook\n")
		}
	}
	for _, pipeline := range statements {
		for i, state := range pipeline {
			if state.Term == "|" && (i+1 >= len(pipeline) || len(pipeline[i+1].Args) <= 0) {
				return 255, errors.New("The syntax of the command is incorrect.")
			}
		}
	}

	for _, pipeline := range statements {

		var pipeIn *os.File = nil
		pipeSeq++
		isBackGround := this.IsBackGround
		for _, state := range pipeline {
			if state.Term == "&" {
				isBackGround = true
				break
			}
		}
		var wg sync.WaitGroup
		shutdown_immediately := false
		for i, state := range pipeline {
			if defined.DBG {
				print(i, ": pipeline loop(", state.Args[0], ")\n")
			}
			cmd, err := this.Clone()
			if err != nil {
				return 255, err
			}
			cmd.PipeSeq[0] = pipeSeq
			cmd.PipeSeq[1] = uint(1 + i)
			cmd.IsBackGround = isBackGround

			if pipeIn != nil {
				cmd.Stdin = pipeIn
				cmd.Closers = append(cmd.Closers, pipeIn)
				pipeIn = nil
			}

			if state.Term[0] == '|' {
				var pipeOut *os.File
				pipeIn, pipeOut, err = os.Pipe()
				cmd.Stdout = pipeOut
				if state.Term == "|&" {
					cmd.Stderr = pipeOut
				}
				cmd.Closers = append(cmd.Closers, pipeOut)
			}

			for _, red := range state.Redirect {
				var fd *os.File
				fd, err = red.OpenOn(cmd)
				if err != nil {
					return 0, err
				}
				defer fd.Close()
			}

			cmd.Args = state.Args
			cmd.RawArgs = state.RawArgs
			if i > 0 {
				cmd.IsBackGround = true
			}
			if len(pipeline) == 1 && dos.IsGui(cmd.FullPath()) {
				cmd.UseShellExecute = true
			}
			if i == len(pipeline)-1 && state.Term != "&" {
				// foreground execution.
				errorlevel, finalerr = cmd.SpawnvpContext(ctx)
				LastErrorLevel = errorlevel
				cmd.Close()
			} else {
				// background
				if !isBackGround {
					wg.Add(1)
				}
				if cmd.OnFork != nil {
					if err := cmd.OnFork(cmd); err != nil {
						fmt.Fprintln(cmd.Stderr, err.Error())
						return -1, err
					}
				}
				go func(cmd1 *Cmd) {
					if !isBackGround {
						defer wg.Done()
					}
					cmd1.SpawnvpContext(ctx)
					if cmd1.OffFork != nil {
						if err := cmd1.OffFork(cmd1); err != nil {
							fmt.Fprintln(cmd1.Stderr, err.Error())
							goto exit
						}
					}
				exit:
					cmd1.Close()
				}(cmd)
			}
		}
		if !isBackGround {
			wg.Wait()
			if shutdown_immediately {
				return errorlevel, nil
			}
			if len(pipeline) > 0 {
				switch pipeline[len(pipeline)-1].Term {
				case "&&":
					if errorlevel != 0 {
						return errorlevel, nil
					}
				case "||":
					if errorlevel == 0 {
						return errorlevel, nil
					}
				}
			}
		}
	}
	return
}
<|endoftext|>


<commit_before>package drivers

import (
	"sync"

	"github.com/go-ui/ui/events"
)

type Window interface {
	Title() string
	SetTitle(string)

	Size() (int, int)
	SetSize(int, int)

	Position() (int, int)
	SetPosition(int, int)

	Close()
}

// Driver defines an interface for the drivers to implement.
type Driver interface {
	CreateWindow(string, int, int, func(events.Event)) Window
	Release() error
}

var (
	m       sync.Mutex
	drivers map[string]func() Driver
)

// Set sets the driver factory function for the given name/ID
func Set(name string, f func() Driver) {
	m.Lock()
	drivers[name] = f
	m.Unlock()
}

// Get returns the driver for the given name/ID
func Get(name string) Driver {
	m.Lock()
	f, ok := drivers[name]
	m.Unlock()
	if ok {
		return f()
	}
	return nil
}

// List returns a list of available drivers
func List() (l []string) {
	m.Lock()
	l = make([]string, 0, len(drivers))
	for name := range drivers {
		l = append(l, name)
	}
	m.Unlock()
	return
}
<commit_msg>Added init of the drivers map<commit_after>package drivers

import (
	"sync"

	"github.com/go-ui/ui/events"
)

type Window interface {
	Title() string
	SetTitle(string)

	Size() (int, int)
	SetSize(int, int)

	Position() (int, int)
	SetPosition(int, int)

	Close()
}

// Driver defines an interface for the drivers to implement.
type Driver interface {
	CreateWindow(string, int, int, func(events.Event)) Window
	Release() error
}

var (
	m       sync.Mutex
	drivers = make(map[string]func() Driver)
)

// Set sets the driver factory function for the given name/ID
func Set(name string, f func() Driver) {
	m.Lock()
	drivers[name] = f
	m.Unlock()
}

// Get returns the driver for the given name/ID
func Get(name string) Driver {
	m.Lock()
	f, ok := drivers[name]
	m.Unlock()
	if ok {
		return f()
	}
	return nil
}

// List returns a list of available drivers
func List() (l []string) {
	m.Lock()
	l = make([]string, 0, len(drivers))
	for name := range drivers {
		l = append(l, name)
	}
	m.Unlock()
	return
}
<|endoftext|>


<commit_before>// Copyright © 2017 National Library of Norway
// 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 cmd

import (
	"log"

	bp "broprox"
	"broproxctl/util"
	"golang.org/x/net/context"

	"github.com/spf13/cobra"
)

// runCmd represents the run command
var runCmd = &cobra.Command{
	Use:   "run jobId [seedId]",
	Short: "Immediately run a crawl",
	Long: `Run a crawl. If seedId is submitted only this seed will be run using the configuration
from the submitted jobId. This will run even if the seed is not configured to use the jobId.
If seedId is not submitted then all the seeds wich are configured to use the submitted jobId will be crawled.`,

	Run: func(cmd *cobra.Command, args []string) {
		if len(args) > 0 {
			client, conn := util.NewControllerClient()
			defer conn.Close()

			switch len(args) {
			case 1:
				// One argument (only jobId)
				request := bp.RunCrawlRequest{JobId: args[0]}
				r, err := client.RunCrawl(context.Background(), &request)
				if err != nil {
					log.Fatalf("could not run job: %v", err)
				}

				println(r.GetSeedExecutionId())
			case 2:
				// Two arguments (jobId and seedId)
				request := bp.RunCrawlRequest{JobId: args[0], SeedId: args[1]}
				r, err := client.RunCrawl(context.Background(), &request)
				if err != nil {
					log.Fatalf("could not run job: %v", err)
				}

				println(r.GetSeedExecutionId())
			}
		} else {
			cmd.Usage()
		}
	},
}

func init() {
	RootCmd.AddCommand(runCmd)
}
<commit_msg>Fixed output of run command<commit_after>// Copyright © 2017 National Library of Norway
// 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 cmd

import (
	"log"

	bp "broprox"
	"broproxctl/util"
	"golang.org/x/net/context"

	"github.com/spf13/cobra"
	"fmt"
)

// runCmd represents the run command
var runCmd = &cobra.Command{
	Use:   "run jobId [seedId]",
	Short: "Immediately run a crawl",
	Long: `Run a crawl. If seedId is submitted only this seed will be run using the configuration
from the submitted jobId. This will run even if the seed is not configured to use the jobId.
If seedId is not submitted then all the seeds wich are configured to use the submitted jobId will be crawled.`,

	Run: func(cmd *cobra.Command, args []string) {
		if len(args) > 0 {
			client, conn := util.NewControllerClient()
			defer conn.Close()

			switch len(args) {
			case 1:
				// One argument (only jobId)
				request := bp.RunCrawlRequest{JobId: args[0]}
				r, err := client.RunCrawl(context.Background(), &request)
				if err != nil {
					log.Fatalf("could not run job: %v", err)
				}

				println(r.GetSeedExecutionId())
			case 2:
				// Two arguments (jobId and seedId)
				request := bp.RunCrawlRequest{JobId: args[0], SeedId: args[1]}
				r, err := client.RunCrawl(context.Background(), &request)
				if err != nil {
					log.Fatalf("could not run job: %v", err)
				}

				fmt.Println("Started executions: ")
				for _, eid := range r.GetSeedExecutionId() {
					fmt.Printf("  %s\n", eid)
				}
			}
		} else {
			cmd.Usage()
		}
	},
}

func init() {
	RootCmd.AddCommand(runCmd)
}
<|endoftext|>


<commit_before>package virtio_test

import (
	"bytes"
	"os"
	"testing"
	"unsafe"

	"github.com/bobuhiro11/gokvm/virtio"
)

func TestBlkGetDeviceHeader(t *testing.T) {
	t.Parallel()

	v, err := virtio.NewBlk("/dev/zero", 9, &mockInjector{}, []byte{})
	if err != nil {
		t.Fatalf("err: %v\n", err)
	}

	expected := uint16(0x1001)
	actual := v.GetDeviceHeader().DeviceID

	if actual != expected {
		t.Fatalf("expected: %v, actual: %v", expected, actual)
	}
}

func TestBlkGetIORange(t *testing.T) {
	t.Parallel()

	v, err := virtio.NewBlk("/dev/zero", 9, &mockInjector{}, []byte{})
	if err != nil {
		t.Fatalf("err: %v\n", err)
	}

	s, e := v.GetIORange()
	actual := e - s
	expected := uint64(virtio.BlkIOPortSize)

	if actual != expected {
		t.Fatalf("expected: %v, actual: %v", expected, actual)
	}
}

func TestBlkIOInHandler(t *testing.T) {
	t.Parallel()

	v, err := virtio.NewBlk("/dev/zero", 9, &mockInjector{}, []byte{})
	if err != nil {
		t.Fatalf("err: %v\n", err)
	}

	expected := []byte{0x20, 0x00}
	actual := make([]byte, 2)
	_ = v.IOInHandler(virtio.BlkIOPortStart+12, actual)

	if !bytes.Equal(expected, actual) {
		t.Fatalf("expected: %v, actual: %v", expected, actual)
	}
}

func TestIO(t *testing.T) {
	t.Parallel()

	mem := make([]byte, 0x1000000)

	v, err := virtio.NewBlk("../vda.img", 10, &mockInjector{}, mem)
	if err != nil {
		if os.IsNotExist(err) {
			t.Skipf("../vda.img does not exist, skipping this test")
		}

		t.Fatalf("err: %v\n", err)
	}

	// Init virt queue
	vq := virtio.VirtQueue{}
	vq.AvailRing.Idx = 1

	// for blk request
	vq.DescTable[0].Addr = 0
	vq.DescTable[0].Len = 1
	vq.DescTable[0].Next = 1

	blkReq := (*virtio.BlkReq)(unsafe.Pointer(&mem[0]))
	blkReq.Type = 0
	blkReq.Sector = 2

	// for data
	vq.DescTable[1].Addr = 0x400
	vq.DescTable[1].Len = 0x200
	vq.DescTable[1].Next = 2

	v.VirtQueue[0] = &vq

	if err := v.IO(); err != nil {
		t.Fatalf("err: %v\n", err)
	}

	if !v.IRQInjector.(*mockInjector).called {
		t.Fatalf("irqInjected = false\n")
	}

	expected := []byte{0x53, 0xef}
	actual := mem[0x438:0x43a]

	if !bytes.Equal(expected, actual) {
		t.Fatalf("expected: %v, actual: %v", expected, actual)
	}
}
<commit_msg>virtio: reduce nested blocks<commit_after>package virtio_test

import (
	"bytes"
	"os"
	"testing"
	"unsafe"

	"github.com/bobuhiro11/gokvm/virtio"
)

func TestBlkGetDeviceHeader(t *testing.T) {
	t.Parallel()

	v, err := virtio.NewBlk("/dev/zero", 9, &mockInjector{}, []byte{})
	if err != nil {
		t.Fatalf("err: %v\n", err)
	}

	expected := uint16(0x1001)
	actual := v.GetDeviceHeader().DeviceID

	if actual != expected {
		t.Fatalf("expected: %v, actual: %v", expected, actual)
	}
}

func TestBlkGetIORange(t *testing.T) {
	t.Parallel()

	v, err := virtio.NewBlk("/dev/zero", 9, &mockInjector{}, []byte{})
	if err != nil {
		t.Fatalf("err: %v\n", err)
	}

	s, e := v.GetIORange()
	actual := e - s
	expected := uint64(virtio.BlkIOPortSize)

	if actual != expected {
		t.Fatalf("expected: %v, actual: %v", expected, actual)
	}
}

func TestBlkIOInHandler(t *testing.T) {
	t.Parallel()

	v, err := virtio.NewBlk("/dev/zero", 9, &mockInjector{}, []byte{})
	if err != nil {
		t.Fatalf("err: %v\n", err)
	}

	expected := []byte{0x20, 0x00}
	actual := make([]byte, 2)
	_ = v.IOInHandler(virtio.BlkIOPortStart+12, actual)

	if !bytes.Equal(expected, actual) {
		t.Fatalf("expected: %v, actual: %v", expected, actual)
	}
}

func TestIO(t *testing.T) {
	t.Parallel()

	mem := make([]byte, 0x1000000)

	v, err := virtio.NewBlk("../vda.img", 10, &mockInjector{}, mem)

	if os.IsNotExist(err) {
		t.Skipf("../vda.img does not exist, skipping this test")
	}

	if err != nil {
		t.Fatalf("err: %v\n", err)
	}

	// Init virt queue
	vq := virtio.VirtQueue{}
	vq.AvailRing.Idx = 1

	// for blk request
	vq.DescTable[0].Addr = 0
	vq.DescTable[0].Len = 1
	vq.DescTable[0].Next = 1

	blkReq := (*virtio.BlkReq)(unsafe.Pointer(&mem[0]))
	blkReq.Type = 0
	blkReq.Sector = 2

	// for data
	vq.DescTable[1].Addr = 0x400
	vq.DescTable[1].Len = 0x200
	vq.DescTable[1].Next = 2

	v.VirtQueue[0] = &vq

	if err := v.IO(); err != nil {
		t.Fatalf("err: %v\n", err)
	}

	if !v.IRQInjector.(*mockInjector).called {
		t.Fatalf("irqInjected = false\n")
	}

	expected := []byte{0x53, 0xef}
	actual := mem[0x438:0x43a]

	if !bytes.Equal(expected, actual) {
		t.Fatalf("expected: %v, actual: %v", expected, actual)
	}
}
<|endoftext|>


<commit_before>package vollocal

import (
	"code.cloudfoundry.org/clock"
	"code.cloudfoundry.org/lager"
	"code.cloudfoundry.org/volman"
	"github.com/tedsuo/ifrit"
	"os"
	"time"
)

type Syncer struct {
	logger       lager.Logger
	registry     volman.PluginRegistry
	scanInterval time.Duration
	clock        clock.Clock
	discoverer   []volman.Discoverer
}

func NewSyncer(logger lager.Logger, registry volman.PluginRegistry, discoverer []volman.Discoverer, scanInterval time.Duration, clock clock.Clock) *Syncer {
	return &Syncer{
		logger:       logger,
		registry:     registry,
		scanInterval: scanInterval,
		clock:        clock,
		discoverer:   discoverer,
	}
}

func NewSyncerWithShims(logger lager.Logger, registry volman.PluginRegistry, discoverer []volman.Discoverer, scanInterval time.Duration, clock clock.Clock) *Syncer {
	return &Syncer{
		logger:       logger,
		registry:     registry,
		scanInterval: scanInterval,
		clock:        clock,
		discoverer:   discoverer,
	}
}

func (p *Syncer) Runner() ifrit.Runner {
	return p
}

func (p *Syncer) Run(signals <-chan os.Signal, ready chan<- struct{}) error {
	logger := p.logger.Session("sync-plugin")
	logger.Info("start")
	defer logger.Info("end")

	logger.Info("running-discovery")
	allPlugins := map[string]volman.Plugin{}
	for _, discoverer := range p.discoverer {
		plugins, err := discoverer.Discover(logger)
		if err != nil {
			logger.Error("failed-discover", err)
			return err
		}
		for k, v := range plugins {
			allPlugins[k] = v
		}
	}
	p.registry.Set(allPlugins)

	timer := p.clock.NewTimer(p.scanInterval)
	defer timer.Stop()

	close(ready)

	for {
		select {
		case <-timer.C():
			go func() {
				logger.Info("running-re-discovery")
				allPlugins := map[string]volman.Plugin{}
				for _, discoverer := range p.discoverer {
					plugins, err := discoverer.Discover(logger)
					if err != nil {
						logger.Error("failed-discover", err)
					}
					for k, v := range plugins {
						allPlugins[k] = v
					}
				}
				p.registry.Set(allPlugins)
				timer.Reset(p.scanInterval)
			}()
		case signal := <-signals:
			logger.Info("received-signal", lager.Data{"signal": signal.String()})
			return nil
		}
	}
	return nil
}
<commit_msg>extract the plugins discover process to a function<commit_after>package vollocal

import (
	"fmt"
	"os"
	"time"

	"code.cloudfoundry.org/clock"
	"code.cloudfoundry.org/lager"
	"code.cloudfoundry.org/volman"
	"github.com/tedsuo/ifrit"
)

type Syncer struct {
	logger       lager.Logger
	registry     volman.PluginRegistry
	scanInterval time.Duration
	clock        clock.Clock
	discoverer   []volman.Discoverer
}

func NewSyncer(logger lager.Logger, registry volman.PluginRegistry, discoverer []volman.Discoverer, scanInterval time.Duration, clock clock.Clock) *Syncer {
	return &Syncer{
		logger:       logger,
		registry:     registry,
		scanInterval: scanInterval,
		clock:        clock,
		discoverer:   discoverer,
	}
}

func NewSyncerWithShims(logger lager.Logger, registry volman.PluginRegistry, discoverer []volman.Discoverer, scanInterval time.Duration, clock clock.Clock) *Syncer {
	return &Syncer{
		logger:       logger,
		registry:     registry,
		scanInterval: scanInterval,
		clock:        clock,
		discoverer:   discoverer,
	}
}

func (p *Syncer) Runner() ifrit.Runner {
	return p
}

func (p *Syncer) Run(signals <-chan os.Signal, ready chan<- struct{}) error {
	logger := p.logger.Session("sync-plugin")
	logger.Info("start")
	defer logger.Info("end")

	logger.Info("running-discovery")
	allPlugins, err := discoverAllplugins(logger, p.discoverer)
	if err != nil {
		return err
	}

	p.registry.Set(allPlugins)

	timer := p.clock.NewTimer(p.scanInterval)
	defer timer.Stop()

	close(ready)

	for {
		select {
		case <-timer.C():
			go func() {
				logger.Info("running-re-discovery")
				allPlugins, err := discoverAllplugins(logger, p.discoverer)
				if err != nil {
					logger.Error("failed-discover", err)
				}
				p.registry.Set(allPlugins)
				timer.Reset(p.scanInterval)
			}()
		case signal := <-signals:
			logger.Info("received-signal", lager.Data{"signal": signal.String()})
			return nil
		}
	}
}

func discoverAllplugins(logger lager.Logger, discoverers []volman.Discoverer) (map[string]volman.Plugin, error) {
	allPlugins := map[string]volman.Plugin{}
	for _, discoverer := range discoverers {
		plugins, err := discoverer.Discover(logger)
		logger.Debug(fmt.Sprintf("plugins found: %#v", plugins))
		if err != nil {
			logger.Error("failed-discover", err)
			return map[string]volman.Plugin{}, err
		}
		for k, v := range plugins {
			allPlugins[k] = v
		}
	}
	return allPlugins, nil
}
<|endoftext|>


<commit_before>package permission

import (
	"strings"
	"testing"
)

const (
	testUsersJson = `
{
  "agon":{
    "groups":["admin"],
    "permissions":["server.web.*", "admin.*", "server.status"]
  },
  "huin":{
    "groups":["admin"],
    "permissions":["server.*", "admin.*"]
  }
}
`
	testGroupsJson = `
{
  "default":{
    "default":true,
    "permissions":["user.commands.help", "user.commands.kill", "user.commands.me", "world.build"]
  },
  "admin":{
    "inheritance":["default"],
    "permissions":["admin.commands.give", "world.*"]
  }
}
`
)

func TestJsonPermission(t *testing.T) {
	usersReader := strings.NewReader(testUsersJson)
	groupsReader := strings.NewReader(testGroupsJson)

	perm, err := LoadJsonPermission(usersReader, groupsReader)
	if err != nil {
		t.Fatalf("Error while loading JsonPermission: %s", err)
	}
	// Check User permissions
	if perm.UserPermissions("agon").Has("server.status") == false {
		t.Error("User agon should have node server.status.")
	}
	// Check User permissions from groups
	if perm.UserPermissions("agon").Has("admin.commands.give") == false {
		t.Error("User agon should have node admin.commands.give through the admin group.")
	}
	// Check if User has no permission
	if perm.UserPermissions("huin").Has("this.node.does.not.exist.tm") {
		t.Error("User huin should not have this.node.does.not.exist.tm as a permission node.")
	}
	// Wildcard check
	if perm.UserPermissions("huin").Has("server.stop") == false { // huin has "server.*", means he has permission for "server.stop"
		t.Error("User huin should have permission for server.stop.")
	}
}
<commit_msg>Permissions unit tests now use a slice of structs.<commit_after>package permission

import (
	"strings"
	"testing"
)

const (
	testUsersJson  = `
{
  "agon":{
    "groups":["admin"],
    "permissions":["server.web.*", "admin.*", "server.status"]
  },
  "huin":{
    "groups":["admin"],
    "permissions":["server.*", "admin.*"]
  }
}
`
	testGroupsJson = `
{
  "default":{
    "default":true,
    "permissions":["user.commands.help", "user.commands.kill", "user.commands.me", "world.build"]
  },
  "admin":{
    "inheritance":["default"],
    "permissions":["admin.commands.give", "world.*"]
  }
}
`
)

func TestJsonPermission(t *testing.T) {
	usersReader := strings.NewReader(testUsersJson)
	groupsReader := strings.NewReader(testGroupsJson)

	perm, err := LoadJsonPermission(usersReader, groupsReader)
	if err != nil {
		t.Fatalf("Error while loading JsonPermission: %s", err)
	}

	type Test struct {
		username    string
		permission  string
		expectedHas bool
	}

	tests := []Test{
		// Check User permissions
		{"agon", "server.status", true},
		// Check User permissions from groups
		{"agon", "admin.commands.give", true},
		// Check if User has no permission
		{"huin", "this.node.does.not.exist.tm", false},
		// Wildcard check
		{"huin", "server.stop", true},
	}

	for i := range tests {
		test := &tests[i]
		result := perm.UserPermissions(test.username).Has(test.permission)
		if test.expectedHas != result {
			if test.expectedHas {
				t.Error("User %s should have node %s", test.username, test.permission)
			} else {
				t.Error("User %s should *not* have node %s", test.username, test.permission)
			}
		}
	}
}
<|endoftext|>


<commit_before>/*
Copyright IBM Corp 2016 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 main

import (
	"encoding/json"
	"errors"
	"fmt"

	"github.com/hyperledger/fabric/core/chaincode/shim"
)

type isval []byte

type MarketerStruct struct {
	EId                   string `json:"EId"`
	TaxId                 string `json:"TaxId"`
	BeginDate             string `json:"BeginDate"`
	MarketerTypeFlag      string `json:"MarketerTypeFlag"`
	MarketerType          string `json:"MarketerType"`
	MarketerRole          string `json:"MarketerRole"`
	MarketerStatus        string `json:"MarketerStatus"`
	LegalName             string `json:"LegalName"`
	Gender                string `json:"Gender"`
	DoB                   string `json:"DoB"`
	RegStateName          string `json:"RegStateName"`
	MarketerEffectiveDate string `json:"MarketerEffectiveDate"`
	MarketerEndDate       string `json:"MarketerEndDate"`
	FirstName             string `json:"FirstName"`
	LastName              string `json:"LastName"`
	BusinessAddress       string `json:"BusinessAddress"`
	City                  string `json:"City"`
	State                 string `json:"State"`
	PostalCode            string `json:"PostalCode"`
	PhoneNumber           string `json:"PhoneNumber"`
	EMail                 string `json:"EMail"`
	MarketerEaRole        string `json:"“MarketerEaRole”"`
	OwnerRole             string `json:"OwnerRole"`
	OrgName               string `json:"OrgName"`
}

type AccountStruct struct {
	policyPrefix               string `json:"policyPrefix"`
	accountNumber              string `json:"accountNumber"`
	internalAccountName        string `json:"internalAccountName"`
	accountStatus              string `json:"accountStatus"`
	accountStatusEffectiveDate string `json:"accountStatusEffectiveDate"`
	validationStatus           string `json:"validationStatus"`
	accountEffectiveDate       string `json:"accountEffectiveDate"`
	marketerProduct            string `json:"marketerProduct"`
	disclosureStatus           string `json:"disclosureStatus"`
	disclosureEffectiveDate    string `json:"disclosureEffectiveDate"`
}

type AssignmentStruct struct {
	AssignmentId            string `json:"AssignmentRoleType"`
	AssignmentRoleType      string `json:"AssignmentRoleType"`
	SplitPercentage         string `json:"SplitPercentage"`
	AssignmentEffectiveDate string `json:"AssignmentEffectiveDate"`
	AssignmentStatus        string `json:"AssignmentStatus"`
	AssignmentEndDate       string `json:"AssignmentEndDate"`
	SplitEffectiveDate      string `json:"SplitEffectiveDate"`
	OwnerEId                string `json:"OwnerEId"`
	OwnerRole               string `json:"OwnerRole"`
	OrgName                 string `json:"OrgName"`
	policyPrefix            string `json:"policyPrefix"`
	accountNumber           string `json:"accountNumber"`
	EId                     string `json:"EId"`
	TaxId                   string `json:"TaxId"`
	BeginDate               string `json:"BeginDate"`
	MarketerTypeFlag        string `json:"MarketerTypeFlag"`
	MarketerType            string `json:"MarketerType"`
	MarketerRole            string `json:"MarketerRole"`
	MarketerStatus          string `json:"MarketerStatus"`
	LegalName               string `json:"LegalName"`
	Gender                  string `json:"Gender"`
	DoB                     string `json:"DoB"`
	RegStateName            string `json:"RegStateName"`
	MarketerEffectiveDate   string `json:"MarketerEffectiveDate"`
	MarketerEndDate         string `json:"MarketerEndDate"`
	FirstName               string `json:"FirstName"`
	LastName                string `json:"LastName"`
	EMail                   string `json:"EMail"`
	MarketerEaRole          string `json:"“MarketerEaRole”"`
}

// SimpleChaincode example simple Chaincode implementation
type SimpleChaincode struct {
}

func main() {
	err := shim.Start(new(SimpleChaincode))

	fmt.Println("****** Starting to send information to my ledger")

	if err != nil {
		fmt.Printf("Error starting Simple chaincode: %s", err)
	}
}

// Init resets all the things
func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	if len(args) != 1 {
		return nil, errors.New("Incorrect number of arguments. Expecting 1")
	}

	err := stub.PutState("hello_world", []byte(args[0]))

	if err != nil {
		return nil, err
	}

	return nil, nil
}

// Invoke isur entry point to invoke a chaincode function
func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	fmt.Println("invoke is running " + function)

	// Handle different functions
	if function == "init" {
		return t.Init(stub, "init", args)
	} else if function == "write" {
		return t.write(stub, args)
	} else if function == "writeAcc" {
		return t.writeAcc(stub, args)
	} else if function == "assign" {
		return t.assign(stub, args)
	}
	fmt.Println("invoke did not find func: " + function)

	return nil, errors.New("Received unknown function invocation: " + function)
}

// Query is our entry point for queries
func (t *SimpleChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	fmt.Println("query is running " + function)

	// Handle different functions
	if function == "read" { //read a variable
		return t.read(stub, args)
	}

	fmt.Println("query did not find func: " + function)

	return nil, errors.New("Received unknown function query: " + function)
}

// write - invoke function to write key/value pair
func (t *SimpleChaincode) write(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {

	var key string
	var err error

	mktrStruct := MarketerStruct{
		EId:                   args[0],
		TaxId:                 args[1],
		BeginDate:             args[2],
		MarketerTypeFlag:      args[3],
		MarketerType:          args[4],
		MarketerRole:          args[5],
		MarketerStatus:        args[6],
		LegalName:             args[7],
		Gender:                args[8],
		DoB:                   args[9],
		RegStateName:          args[10],
		MarketerEffectiveDate: args[11],
		MarketerEndDate:       args[12],
		FirstName:             args[13],
		LastName:              args[14],
		BusinessAddress:       args[15],
		City:                  args[16],
		State:                 args[17],
		PostalCode:            args[18],
		PhoneNumber:           args[19],
		EMail:                 args[20],
		MarketerEaRole:        args[21],
		OwnerRole:             args[22],
		OrgName:               args[23],
	}

	mktrStructBytes, err := json.Marshal(mktrStruct)
	_ = err //ignore errors
	key = args[0]
	//t.read(stub, args)
	isval, err := t.read(stub, args)
	if isval == nil {
		stub.PutState(key, mktrStructBytes)
		fmt.Println("*** successfully wrote marketer to state")
	} else {
		fmt.Println("****duplicate entry")
		dupMktrArr := []byte("Marketer exists!")
		return dupMktrArr, errors.New("duplicate entry")
	}

	successMsgArr := []byte("Marketer added succesfully!")

	return successMsgArr, nil
}

func (t *SimpleChaincode) writeAcc(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {

	var key string
	var err error

	accStruct := AccountStruct{
		accountNumber:              args[0],
		policyPrefix:               args[1],
		internalAccountName:        args[2],
		accountStatus:              args[3],
		accountStatusEffectiveDate: args[4],
		validationStatus:           args[5],
		accountEffectiveDate:       args[6],
		marketerProduct:            args[7],
		disclosureStatus:           args[8],
		disclosureEffectiveDate:    args[9],
	}

	accStructBytes, err := json.Marshal(accStruct)
	_ = err //ignore errors
	key = args[0]
	stub.PutState(key, accStructBytes)
	fmt.Println("*** successfully wrote account to state")

	successMsgArr := []byte("Account added succesfully!")

	return successMsgArr, nil
}

func (t *SimpleChaincode) assign(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {

	var key string
	var err error

	assignStruct := AssignmentStruct{
		AssignmentId:            args[0],
		AssignmentRoleType:      args[1],
		SplitPercentage:         args[2],
		AssignmentEffectiveDate: args[3],
		AssignmentStatus:        args[4],
		AssignmentEndDate:       args[5],
		SplitEffectiveDate:      args[6],
		OwnerEId:                args[7],
		OwnerRole:               args[8],
		OrgName:                 args[9],
		policyPrefix:            args[10],
		accountNumber:           args[11],
		EId:                     args[12],
		TaxId:                   args[13],
		BeginDate:               args[14],
		MarketerTypeFlag:        args[15],
		MarketerType:            args[16],
		MarketerRole:            args[17],
		MarketerStatus:          args[18],
		LegalName:               args[19],
		Gender:                  args[20],
		DoB:                     args[21],
		RegStateName:            args[22],
		MarketerEffectiveDate:   args[23],
		MarketerEndDate:         args[24],
		FirstName:               args[25],
		LastName:                args[26],
		EMail:                   args[27],
		MarketerEaRole:          args[28],
	}

	assignStructBytes, err := json.Marshal(assignStruct)
	_ = err //ignore errors
	key = args[0]

	stub.PutState(key, assignStructBytes)
	fmt.Println("*** successfully wrote assignemt to state")

	successMsgArr := []byte("Assignment added succesfully!")

	return successMsgArr, nil
}

// read - query function to read key/value pair
func (t *SimpleChaincode) read(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
	var key, jsonResp string
	var err error

	var retrievedStruct MarketerStruct
	key = args[0]
	retrievedBytes, err := stub.GetState(key)
	json.Unmarshal(retrievedBytes, retrievedStruct)

	fmt.Println("Retrieved struct: ", retrievedStruct)

	if err != nil {
		jsonResp = "{\"Error\":\"Failed to get state for " + key + "\"}"
		return nil, errors.New(jsonResp)
	}

	return retrievedBytes, nil
}
<commit_msg>Changed account struct variables<commit_after>/*
Copyright IBM Corp 2016 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 main

import (
	"encoding/json"
	"errors"
	"fmt"

	"github.com/hyperledger/fabric/core/chaincode/shim"
)

type isval []byte

type MarketerStruct struct {
	EId                   string `json:"EId"`
	TaxId                 string `json:"TaxId"`
	BeginDate             string `json:"BeginDate"`
	MarketerTypeFlag      string `json:"MarketerTypeFlag"`
	MarketerType          string `json:"MarketerType"`
	MarketerRole          string `json:"MarketerRole"`
	MarketerStatus        string `json:"MarketerStatus"`
	LegalName             string `json:"LegalName"`
	Gender                string `json:"Gender"`
	DoB                   string `json:"DoB"`
	RegStateName          string `json:"RegStateName"`
	MarketerEffectiveDate string `json:"MarketerEffectiveDate"`
	MarketerEndDate       string `json:"MarketerEndDate"`
	FirstName             string `json:"FirstName"`
	LastName              string `json:"LastName"`
	BusinessAddress       string `json:"BusinessAddress"`
	City                  string `json:"City"`
	State                 string `json:"State"`
	PostalCode            string `json:"PostalCode"`
	PhoneNumber           string `json:"PhoneNumber"`
	EMail                 string `json:"EMail"`
	MarketerEaRole        string `json:"“MarketerEaRole”"`
	OwnerRole             string `json:"OwnerRole"`
	OrgName               string `json:"OrgName"`
}

type AccountStruct struct {
	AccountNumber              string `json:"AccountNumber"`
	PolicyPrefix               string `json:"PolicyPrefix"`
	InternalAccountName        string `json:"InternalAccountName"`
	AccountStatus              string `json:"AccountStatus"`
	AccountStatusEffectiveDate string `json:"AccountStatusEffectiveDate"`
	ValidationStatus           string `json:"ValidationStatus"`
	AccountEffectiveDate       string `json:"AccountEffectiveDate"`
	MarketerProduct            string `json:"MarketerProduct"`
	DisclosureStatus           string `json:"DisclosureStatus"`
	DisclosureEffectiveDate    string `json:"DisclosureEffectiveDate"`
}

type AssignmentStruct struct {
	AssignmentId            string `json:"AssignmentId"`
	AssignmentRoleType      string `json:"AssignmentRoleType"`
	SplitPercentage         string `json:"SplitPercentage"`
	AssignmentEffectiveDate string `json:"AssignmentEffectiveDate"`
	AssignmentStatus        string `json:"AssignmentStatus"`
	AssignmentEndDate       string `json:"AssignmentEndDate"`
	SplitEffectiveDate      string `json:"SplitEffectiveDate"`
	OwnerEId                string `json:"OwnerEId"`
	OwnerRole               string `json:"OwnerRole"`
	OrgName                 string `json:"OrgName"`
	policyPrefix            string `json:"policyPrefix"`
	accountNumber           string `json:"accountNumber"`
	EId                     string `json:"EId"`
	TaxId                   string `json:"TaxId"`
	BeginDate               string `json:"BeginDate"`
	MarketerTypeFlag        string `json:"MarketerTypeFlag"`
	MarketerType            string `json:"MarketerType"`
	MarketerRole            string `json:"MarketerRole"`
	MarketerStatus          string `json:"MarketerStatus"`
	LegalName               string `json:"LegalName"`
	Gender                  string `json:"Gender"`
	DoB                     string `json:"DoB"`
	RegStateName            string `json:"RegStateName"`
	MarketerEffectiveDate   string `json:"MarketerEffectiveDate"`
	MarketerEndDate         string `json:"MarketerEndDate"`
	FirstName               string `json:"FirstName"`
	LastName                string `json:"LastName"`
	EMail                   string `json:"EMail"`
	MarketerEaRole          string `json:"“MarketerEaRole”"`
}

// SimpleChaincode example simple Chaincode implementation
type SimpleChaincode struct {
}

func main() {
	err := shim.Start(new(SimpleChaincode))

	fmt.Println("****** Starting to send information to my ledger")

	if err != nil {
		fmt.Printf("Error starting Simple chaincode: %s", err)
	}
}

// Init resets all the things
func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	if len(args) != 1 {
		return nil, errors.New("Incorrect number of arguments. Expecting 1")
	}

	err := stub.PutState("hello_world", []byte(args[0]))

	if err != nil {
		return nil, err
	}

	return nil, nil
}

// Invoke isur entry point to invoke a chaincode function
func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	fmt.Println("invoke is running " + function)

	// Handle different functions
	if function == "init" {
		return t.Init(stub, "init", args)
	} else if function == "write" {
		return t.write(stub, args)
	} else if function == "account" {
		return t.account(stub, args)
	} else if function == "assign" {
		return t.assign(stub, args)
	}
	fmt.Println("invoke did not find func: " + function)

	return nil, errors.New("Received unknown function invocation: " + function)
}

// Query is our entry point for queries
func (t *SimpleChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	fmt.Println("query is running " + function)

	// Handle different functions
	if function == "read" { //read a variable
		return t.read(stub, args)
	}

	fmt.Println("query did not find func: " + function)

	return nil, errors.New("Received unknown function query: " + function)
}

// write - invoke function to write key/value pair
func (t *SimpleChaincode) write(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {

	var key string
	var err error

	mktrStruct := MarketerStruct{
		EId:                   args[0],
		TaxId:                 args[1],
		BeginDate:             args[2],
		MarketerTypeFlag:      args[3],
		MarketerType:          args[4],
		MarketerRole:          args[5],
		MarketerStatus:        args[6],
		LegalName:             args[7],
		Gender:                args[8],
		DoB:                   args[9],
		RegStateName:          args[10],
		MarketerEffectiveDate: args[11],
		MarketerEndDate:       args[12],
		FirstName:             args[13],
		LastName:              args[14],
		BusinessAddress:       args[15],
		City:                  args[16],
		State:                 args[17],
		PostalCode:            args[18],
		PhoneNumber:           args[19],
		EMail:                 args[20],
		MarketerEaRole:        args[21],
		OwnerRole:             args[22],
		OrgName:               args[23],
	}

	mktrStructBytes, err := json.Marshal(mktrStruct)
	_ = err //ignore errors
	key = args[0]
	//t.read(stub, args)
	isval, err := t.read(stub, args)
	if isval == nil {
		stub.PutState(key, mktrStructBytes)
		fmt.Println("*** successfully wrote marketer to state")
	} else {
		fmt.Println("****duplicate entry")
		dupMktrArr := []byte("Marketer exists!")
		return dupMktrArr, errors.New("duplicate entry")
	}

	successMsgArr := []byte("Marketer added succesfully!")

	return successMsgArr, nil
}

func (t *SimpleChaincode) account(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {

	var key string
	var err error

	accStruct := AccountStruct{
		AccountNumber:              args[0],
		PolicyPrefix:               args[1],
		InternalAccountName:        args[2],
		AccountStatus:              args[3],
		AccountStatusEffectiveDate: args[4],
		ValidationStatus:           args[5],
		AccountEffectiveDate:       args[6],
		MarketerProduct:            args[7],
		DisclosureStatus:           args[8],
		DisclosureEffectiveDate:    args[9],
	}

	accStructBytes, err := json.Marshal(accStruct)
	_ = err //ignore errors
	key = args[0]
	stub.PutState(key, accStructBytes)
	fmt.Println("*** successfully wrote account to state")

	successMsgArr := []byte("Account added succesfully!")

	return successMsgArr, nil
}

func (t *SimpleChaincode) assign(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {

	var key string
	var err error

	assignStruct := AssignmentStruct{
		AssignmentId:            args[0],
		AssignmentRoleType:      args[1],
		SplitPercentage:         args[2],
		AssignmentEffectiveDate: args[3],
		AssignmentStatus:        args[4],
		AssignmentEndDate:       args[5],
		SplitEffectiveDate:      args[6],
		OwnerEId:                args[7],
		OwnerRole:               args[8],
		OrgName:                 args[9],
		policyPrefix:            args[10],
		accountNumber:           args[11],
		EId:                     args[12],
		TaxId:                   args[13],
		BeginDate:               args[14],
		MarketerTypeFlag:        args[15],
		MarketerType:            args[16],
		MarketerRole:            args[17],
		MarketerStatus:          args[18],
		LegalName:               args[19],
		Gender:                  args[20],
		DoB:                     args[21],
		RegStateName:            args[22],
		MarketerEffectiveDate:   args[23],
		MarketerEndDate:         args[24],
		FirstName:               args[25],
		LastName:                args[26],
		EMail:                   args[27],
		MarketerEaRole:          args[28],
	}

	assignStructBytes, err := json.Marshal(assignStruct)
	_ = err //ignore errors
	key = args[0]

	stub.PutState(key, assignStructBytes)
	fmt.Println("*** successfully wrote assignemt to state")

	successMsgArr := []byte("Assignment added succesfully!")

	return successMsgArr, nil
}

// read - query function to read key/value pair
func (t *SimpleChaincode) read(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
	var key, jsonResp string
	var err error

	var retrievedStruct MarketerStruct
	key = args[0]
	retrievedBytes, err := stub.GetState(key)
	json.Unmarshal(retrievedBytes, retrievedStruct)

	fmt.Println("Retrieved struct: ", retrievedStruct)

	if err != nil {
		jsonResp = "{\"Error\":\"Failed to get state for " + key + "\"}"
		return nil, errors.New(jsonResp)
	}

	return retrievedBytes, nil
}
<|endoftext|>


<commit_before>package checkmasterha

import (
	"bytes"
	"os"
	"os/exec"
	"strings"

	"github.com/jessevdk/go-flags"
	"github.com/mackerelio/checkers"
)

// Do the plugin
func Do() {
	var opts options
	parser := flags.NewParser(&opts, flags.Default)
	if _, err := parser.Parse(); err != nil {
		os.Exit(1)
	}
}

type options struct {
	Status statusChecker `command:"status" description:"check to masterha_check_status"`
	Repl   replChecker   `command:"repl"   description:"check to masterha_check_repl"`
	SSH    sshChecker    `command:"ssh"    description:"check to masterha_check_ssh"`
}

type executer interface {
	MakeCommandName() string
	MakeCommandArgs() []string
	Parse(string) (checkers.Status, string)
}

type subcommand struct {
	Config    string `short:"c" long:"conf" description:"target config file"`
	ConfigDir string `long:"confdir" default:"/usr/local/masterha/conf" description:"config directory"`
	All       bool   `short:"a" long:"all" description:"use all config file for target"`
	Executer  executer
}

func (c subcommand) ConfigFiles() ([]string, error) {
	if c.All {
		files, err := os.ReadDir("/service")
		if err != nil {
			return nil, err
		}

		configFiles := make([]string, 0, len(files))
		for _, file := range files {
			if strings.HasPrefix(file.Name(), "masterha_") {
				configFile := c.ConfigDir + "/" + file.Name()[9:] + ".cnf"
				configFiles = append(configFiles, configFile)
			}
		}
		return configFiles, nil
	}

	configFiles := []string{c.Config}
	return configFiles, nil
}

func (c subcommand) MakeCommandName() string {
	return c.Executer.MakeCommandName()
}

func (c subcommand) MakeCommandArgs() []string {
	args := c.Executer.MakeCommandArgs()
	args = append(args, "--conf", c.Config)
	return args
}

func (c subcommand) Parse(result string) (checkers.Status, string) {
	return c.Executer.Parse(result)
}

func (c subcommand) executeAll() *checkers.Checker {
	var err error
	checker := checkers.NewChecker(checkers.UNKNOWN, "No target")

	configFiles, err := c.ConfigFiles()
	if err != nil {
		checker.Status  = checkers.UNKNOWN
		checker.Message = err.Error()
		return checker
	}

	for _, config := range configFiles {
		checker = c.execute(config)
		if checker.Status != checkers.OK {
			return checker
		}
	}

	return checker
}

func (c subcommand) execute(config string) *checkers.Checker {
	c.Config = config
	name := c.MakeCommandName()
	args := c.MakeCommandArgs()

	cmd := exec.Command(name, args...)

	var buf bytes.Buffer
	cmd.Stdout = &buf
	cmd.Stderr = &buf

	var failure bool
	err := cmd.Run()
	if _, ok := err.(*exec.ExitError); ok {
		failure = true
	} else if err != nil {
		checker := checkers.NewChecker(checkers.UNKNOWN, err.Error())
		return checker
	}

	result, msg := c.Parse(buf.String())
	if failure && result == checkers.UNKNOWN {
		result = checkers.WARNING
	}
	checker := checkers.NewChecker(result, msg)
	return checker
}

func extractNonEmptyLines(lines []string) []string {
	result := make([]string, 0, len(lines))
	for _, line := range lines {
		if line != "" {
			result = append(result, line)
		}
	}
	return result
}

func extractErrorMsg(msg string) string {
	var errors []string
	for _, line := range strings.Split(msg, "\n") {
		if strings.Contains(line, "[error]") {
			errors = append(errors, line)
		}
	}

	if len(errors) == 0 {
		return msg
	}

	return strings.Join(errors, "\n")
}
<commit_msg>go fmt<commit_after>package checkmasterha

import (
	"bytes"
	"os"
	"os/exec"
	"strings"

	"github.com/jessevdk/go-flags"
	"github.com/mackerelio/checkers"
)

// Do the plugin
func Do() {
	var opts options
	parser := flags.NewParser(&opts, flags.Default)
	if _, err := parser.Parse(); err != nil {
		os.Exit(1)
	}
}

type options struct {
	Status statusChecker `command:"status" description:"check to masterha_check_status"`
	Repl   replChecker   `command:"repl"   description:"check to masterha_check_repl"`
	SSH    sshChecker    `command:"ssh"    description:"check to masterha_check_ssh"`
}

type executer interface {
	MakeCommandName() string
	MakeCommandArgs() []string
	Parse(string) (checkers.Status, string)
}

type subcommand struct {
	Config    string `short:"c" long:"conf" description:"target config file"`
	ConfigDir string `long:"confdir" default:"/usr/local/masterha/conf" description:"config directory"`
	All       bool   `short:"a" long:"all" description:"use all config file for target"`
	Executer  executer
}

func (c subcommand) ConfigFiles() ([]string, error) {
	if c.All {
		files, err := os.ReadDir("/service")
		if err != nil {
			return nil, err
		}

		configFiles := make([]string, 0, len(files))
		for _, file := range files {
			if strings.HasPrefix(file.Name(), "masterha_") {
				configFile := c.ConfigDir + "/" + file.Name()[9:] + ".cnf"
				configFiles = append(configFiles, configFile)
			}
		}
		return configFiles, nil
	}

	configFiles := []string{c.Config}
	return configFiles, nil
}

func (c subcommand) MakeCommandName() string {
	return c.Executer.MakeCommandName()
}

func (c subcommand) MakeCommandArgs() []string {
	args := c.Executer.MakeCommandArgs()
	args = append(args, "--conf", c.Config)
	return args
}

func (c subcommand) Parse(result string) (checkers.Status, string) {
	return c.Executer.Parse(result)
}

func (c subcommand) executeAll() *checkers.Checker {
	var err error
	checker := checkers.NewChecker(checkers.UNKNOWN, "No target")

	configFiles, err := c.ConfigFiles()
	if err != nil {
		checker.Status = checkers.UNKNOWN
		checker.Message = err.Error()
		return checker
	}

	for _, config := range configFiles {
		checker = c.execute(config)
		if checker.Status != checkers.OK {
			return checker
		}
	}

	return checker
}

func (c subcommand) execute(config string) *checkers.Checker {
	c.Config = config
	name := c.MakeCommandName()
	args := c.MakeCommandArgs()

	cmd := exec.Command(name, args...)

	var buf bytes.Buffer
	cmd.Stdout = &buf
	cmd.Stderr = &buf

	var failure bool
	err := cmd.Run()
	if _, ok := err.(*exec.ExitError); ok {
		failure = true
	} else if err != nil {
		checker := checkers.NewChecker(checkers.UNKNOWN, err.Error())
		return checker
	}

	result, msg := c.Parse(buf.String())
	if failure && result == checkers.UNKNOWN {
		result = checkers.WARNING
	}
	checker := checkers.NewChecker(result, msg)
	return checker
}

func extractNonEmptyLines(lines []string) []string {
	result := make([]string, 0, len(lines))
	for _, line := range lines {
		if line != "" {
			result = append(result, line)
		}
	}
	return result
}

func extractErrorMsg(msg string) string {
	var errors []string
	for _, line := range strings.Split(msg, "\n") {
		if strings.Contains(line, "[error]") {
			errors = append(errors, line)
		}
	}

	if len(errors) == 0 {
		return msg
	}

	return strings.Join(errors, "\n")
}
<|endoftext|>


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

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

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

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

package nginx

// IngressConfig describes an NGINX configuration
type IngressConfig struct {
	Upstreams    []*Upstream
	Servers      []*Server
	TCPUpstreams []*Location
	UDPUpstreams []*Location
}

// Upstream describes an NGINX upstream
type Upstream struct {
	Name     string
	Backends []UpstreamServer
}

// UpstreamByNameServers sorts upstreams by name
type UpstreamByNameServers []*Upstream

func (c UpstreamByNameServers) Len() int      { return len(c) }
func (c UpstreamByNameServers) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
func (c UpstreamByNameServers) Less(i, j int) bool {
	return c[i].Name < c[j].Name
}

// UpstreamServer describes a server in an NGINX upstream
type UpstreamServer struct {
	Address string
	Port    string
}

// UpstreamServerByAddrPort sorts upstream servers by address and port
type UpstreamServerByAddrPort []UpstreamServer

func (c UpstreamServerByAddrPort) Len() int      { return len(c) }
func (c UpstreamServerByAddrPort) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
func (c UpstreamServerByAddrPort) Less(i, j int) bool {
	iName := c[i].Address
	jName := c[j].Address
	if iName != jName {
		return iName < jName
	}

	iU := c[i].Port
	jU := c[j].Port
	return iU < jU
}

// Server describes an NGINX server
type Server struct {
	Name              string
	Locations         []*Location
	SSL               bool
	SSLCertificate    string
	SSLCertificateKey string
}

// ServerByName sorts server by name
type ServerByName []*Server

func (c ServerByName) Len() int      { return len(c) }
func (c ServerByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
func (c ServerByName) Less(i, j int) bool {
	return c[i].Name < c[j].Name
}

// Location describes an NGINX location
type Location struct {
	Path         string
	IsDefBackend bool
	Upstream     Upstream
}

// LocationByPath sorts location by path
type LocationByPath []*Location

func (c LocationByPath) Len() int      { return len(c) }
func (c LocationByPath) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
func (c LocationByPath) Less(i, j int) bool {
	return c[i].Path < c[j].Path
}

// NewDefaultServer return an UpstreamServer to be use as default server that returns 503.
func NewDefaultServer() UpstreamServer {
	return UpstreamServer{Address: "127.0.0.1", Port: "8181"}
}

// NewUpstream creates an upstream without servers.
func NewUpstream(name string) *Upstream {
	return &Upstream{
		Name:     name,
		Backends: []UpstreamServer{},
	}
}
<commit_msg>Location / must be the last one<commit_after>/*
Copyright 2015 The Kubernetes Authors All rights reserved.

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

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

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

package nginx

// IngressConfig describes an NGINX configuration
type IngressConfig struct {
	Upstreams    []*Upstream
	Servers      []*Server
	TCPUpstreams []*Location
	UDPUpstreams []*Location
}

// Upstream describes an NGINX upstream
type Upstream struct {
	Name     string
	Backends []UpstreamServer
}

// UpstreamByNameServers sorts upstreams by name
type UpstreamByNameServers []*Upstream

func (c UpstreamByNameServers) Len() int      { return len(c) }
func (c UpstreamByNameServers) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
func (c UpstreamByNameServers) Less(i, j int) bool {
	return c[i].Name < c[j].Name
}

// UpstreamServer describes a server in an NGINX upstream
type UpstreamServer struct {
	Address string
	Port    string
}

// UpstreamServerByAddrPort sorts upstream servers by address and port
type UpstreamServerByAddrPort []UpstreamServer

func (c UpstreamServerByAddrPort) Len() int      { return len(c) }
func (c UpstreamServerByAddrPort) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
func (c UpstreamServerByAddrPort) Less(i, j int) bool {
	iName := c[i].Address
	jName := c[j].Address
	if iName != jName {
		return iName < jName
	}

	iU := c[i].Port
	jU := c[j].Port
	return iU < jU
}

// Server describes an NGINX server
type Server struct {
	Name              string
	Locations         []*Location
	SSL               bool
	SSLCertificate    string
	SSLCertificateKey string
}

// ServerByName sorts server by name
type ServerByName []*Server

func (c ServerByName) Len() int      { return len(c) }
func (c ServerByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
func (c ServerByName) Less(i, j int) bool {
	return c[i].Name < c[j].Name
}

// Location describes an NGINX location
type Location struct {
	Path         string
	IsDefBackend bool
	Upstream     Upstream
}

// LocationByPath sorts location by path
// Location / is the last one
type LocationByPath []*Location

func (c LocationByPath) Len() int      { return len(c) }
func (c LocationByPath) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
func (c LocationByPath) Less(i, j int) bool {
	return c[i].Path > c[j].Path
}

// NewDefaultServer return an UpstreamServer to be use as default server that returns 503.
func NewDefaultServer() UpstreamServer {
	return UpstreamServer{Address: "127.0.0.1", Port: "8181"}
}

// NewUpstream creates an upstream without servers.
func NewUpstream(name string) *Upstream {
	return &Upstream{
		Name:     name,
		Backends: []UpstreamServer{},
	}
}
<|endoftext|>


<commit_before>/*
Copyright 2020 Google LLC

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

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

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

package e2e

import (
	"context"
	"fmt"
	"regexp"
	"testing"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

	"github.com/GoogleCloudPlatform/gke-managed-certs/e2e/utils"
	"github.com/GoogleCloudPlatform/gke-managed-certs/pkg/utils/errors"
)

// This test creates more certificates than the quota allows and checks
// if there is at least one with an event communicating the Created event,
// and at least one with an event communicating TooManyCertificates. Normally
// every certificate should either receive Created or TooManyCertificates,
// however rarely BackendError can be reported as well, and events are reported
// on a best-effort basis, so the test does not require every event to be present.
func TestEvents_ManagedCertificate(t *testing.T) {
	ctx := context.Background()
	numCerts := 400 // Should be bigger than allowed quota.

	for i := 0; i < numCerts; i++ {
		i := i
		go func() {
			name := fmt.Sprintf("quota-%d", i)
			if err := errors.IgnoreNotFound(clients.ManagedCertificate.Delete(ctx, name)); err != nil {
				t.Fatal(err)
			}
			domains := []string{fmt.Sprintf("quota%d.example.com", i)}
			if err := clients.ManagedCertificate.Create(ctx, name, domains); err != nil {
				t.Fatal(err)
			}
			t.Cleanup(func() {
				clients.ManagedCertificate.Delete(ctx, name)
			})
		}()
	}

	if err := utils.Retry(func() error {
		foundCreated := false
		foundTooManyCertificates := false

		eventList, err := clients.Event.List(ctx, metav1.ListOptions{})
		if err != nil {
			return err
		}

		for _, event := range eventList.Items {
			nameMatched, err := regexp.MatchString("quota-[0-9]+", event.InvolvedObject.Name)
			if err != nil {
				return err
			}

			if event.InvolvedObject.Kind == "ManagedCertificate" && nameMatched {
				if event.Reason == "Create" {
					foundCreated = true
				}
				if event.Reason == "TooManyCertificates" {
					foundTooManyCertificates = true
				}
			}

			if foundCreated && foundTooManyCertificates {
				break
			}
		}

		if !foundCreated || !foundTooManyCertificates {
			return fmt.Errorf("Create event found: %t, TooManyCertificates event found: %t; want both found", foundCreated, foundTooManyCertificates)
		}

		return nil
	}); err != nil {
		t.Fatal(err)
	}
}

func TestEvents_Ingress(t *testing.T) {
	t.Parallel()

	ctx := context.Background()
	ingressName := "test-events-ingress"

	if err := createIngress(t, ctx, ingressName, 8081, "non-existing-certificate"); err != nil {
		t.Fatalf("createIngress(ingressName=%s): %v", ingressName, err)
	}

	if err := utils.Retry(func() error {
		eventList, err := clients.Event.List(ctx, metav1.ListOptions{})
		if err != nil {
			return err
		}

		for _, event := range eventList.Items {
			if event.InvolvedObject.Kind == "Ingress" && event.InvolvedObject.Name == ingressName && event.Reason == "MissingCertificate" {
				return nil
			}
		}

		return fmt.Errorf("MissingCertificate event not found")
	}); err != nil {
		t.Fatal(err)
	}
}
<commit_msg>Change domain name from example.com to quota-test.com so that certficates provisioning is attempted with Tarsier/GTS instead of Let's Encrypt.<commit_after>/*
Copyright 2020 Google LLC

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

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

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

package e2e

import (
	"context"
	"fmt"
	"regexp"
	"testing"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

	"github.com/GoogleCloudPlatform/gke-managed-certs/e2e/utils"
	"github.com/GoogleCloudPlatform/gke-managed-certs/pkg/utils/errors"
)

// This test creates more certificates than the quota allows and checks
// if there is at least one with an event communicating the Created event,
// and at least one with an event communicating TooManyCertificates. Normally
// every certificate should either receive Created or TooManyCertificates,
// however rarely BackendError can be reported as well, and events are reported
// on a best-effort basis, so the test does not require every event to be present.
func TestEvents_ManagedCertificate(t *testing.T) {
	ctx := context.Background()
	numCerts := 400 // Should be bigger than allowed quota.

	for i := 0; i < numCerts; i++ {
		i := i
		go func() {
			name := fmt.Sprintf("quota-%d", i)
			if err := errors.IgnoreNotFound(clients.ManagedCertificate.Delete(ctx, name)); err != nil {
				t.Fatal(err)
			}
			domains := []string{fmt.Sprintf("quota%d.quota-test.com", i)}
			if err := clients.ManagedCertificate.Create(ctx, name, domains); err != nil {
				t.Fatal(err)
			}
			t.Cleanup(func() {
				clients.ManagedCertificate.Delete(ctx, name)
			})
		}()
	}

	if err := utils.Retry(func() error {
		foundCreated := false
		foundTooManyCertificates := false

		eventList, err := clients.Event.List(ctx, metav1.ListOptions{})
		if err != nil {
			return err
		}

		for _, event := range eventList.Items {
			nameMatched, err := regexp.MatchString("quota-[0-9]+", event.InvolvedObject.Name)
			if err != nil {
				return err
			}

			if event.InvolvedObject.Kind == "ManagedCertificate" && nameMatched {
				if event.Reason == "Create" {
					foundCreated = true
				}
				if event.Reason == "TooManyCertificates" {
					foundTooManyCertificates = true
				}
			}

			if foundCreated && foundTooManyCertificates {
				break
			}
		}

		if !foundCreated || !foundTooManyCertificates {
			return fmt.Errorf("Create event found: %t, TooManyCertificates event found: %t; want both found", foundCreated, foundTooManyCertificates)
		}

		return nil
	}); err != nil {
		t.Fatal(err)
	}
}

func TestEvents_Ingress(t *testing.T) {
	t.Parallel()

	ctx := context.Background()
	ingressName := "test-events-ingress"

	if err := createIngress(t, ctx, ingressName, 8081, "non-existing-certificate"); err != nil {
		t.Fatalf("createIngress(ingressName=%s): %v", ingressName, err)
	}

	if err := utils.Retry(func() error {
		eventList, err := clients.Event.List(ctx, metav1.ListOptions{})
		if err != nil {
			return err
		}

		for _, event := range eventList.Items {
			if event.InvolvedObject.Kind == "Ingress" && event.InvolvedObject.Name == ingressName && event.Reason == "MissingCertificate" {
				return nil
			}
		}

		return fmt.Errorf("MissingCertificate event not found")
	}); err != nil {
		t.Fatal(err)
	}
}
<|endoftext|>


<commit_before>package edit

import (
	"fmt"
	"io/ioutil"
	"os"
	"path"
	"strings"

	"github.com/elves/elvish/eval"
	"github.com/elves/elvish/parse"
)

// A completer takes the current node
type completer func(parse.Node, *Editor) []*candidate

var completers = []struct {
	name string
	completer
}{
	{"variable", complVariable},
	{"command name", complNewForm},
	{"command name", makeCompoundCompleter(complFormHead)},
	{"argument", complNewArg},
	{"argument", makeCompoundCompleter(complArg)},
}

func complVariable(n parse.Node, ed *Editor) []*candidate {
	primary, ok := n.(*parse.Primary)
	if !ok || primary.Type != parse.Variable {
		return nil
	}

	head := primary.Value[1:]
	cands := []*candidate{}
	for variable := range ed.evaler.Global() {
		if strings.HasPrefix(variable, head) {
			cands = append(cands, &candidate{
				source: styled{variable[len(head):], styleForType[Variable]},
				menu:   styled{"$" + variable, styleForType[Variable]}})
		}
	}
	return cands
}

func complNewForm(n parse.Node, ed *Editor) []*candidate {
	if _, ok := n.(*parse.Chunk); ok {
		return complFormHeadInner("", ed)
	}
	if _, ok := n.Parent().(*parse.Chunk); ok {
		return complFormHeadInner("", ed)
	}
	return nil
}

func makeCompoundCompleter(
	f func(*parse.Compound, string, *Editor) []*candidate) completer {
	return func(n parse.Node, ed *Editor) []*candidate {
		pn, ok := n.(*parse.Primary)
		if !ok {
			return nil
		}
		cn, head := simpleCompound(pn)
		if cn == nil {
			return nil
		}
		return f(cn, head, ed)
	}
}

func complFormHead(cn *parse.Compound, head string, ed *Editor) []*candidate {
	if isFormHead(cn) {
		return complFormHeadInner(head, ed)
	}
	return nil
}

func complFormHeadInner(head string, ed *Editor) []*candidate {
	if eval.DontSearch(head) {
		return complArgInner(head, ed, true)
	}

	cands := []*candidate{}

	foundCommand := func(s string) {
		if strings.HasPrefix(s, head) {
			cands = append(cands, &candidate{
				source: styled{s[len(head):], styleForGoodCommand},
				menu:   styled{s, ""},
			})
		}
	}
	for special := range isBuiltinSpecial {
		foundCommand(special)
	}
	for variable := range ed.evaler.Global() {
		if strings.HasPrefix(variable, eval.FnPrefix) {
			foundCommand(variable[len(eval.FnPrefix):])
		}
	}
	for command := range ed.isExternal {
		foundCommand(command)
	}
	return cands
}

func complNewArg(n parse.Node, ed *Editor) []*candidate {
	sn, ok := n.(*parse.Sep)
	if !ok {
		return nil
	}
	if _, ok := sn.Parent().(*parse.Form); !ok {
		return nil
	}
	return complArgInner("", ed, false)
}

func complArg(cn *parse.Compound, head string, ed *Editor) []*candidate {
	return complArgInner(head, ed, false)
}

// TODO: getStyle does redundant stats.
func complArgInner(head string, ed *Editor, formHead bool) []*candidate {
	dir, fileprefix := path.Split(head)
	if dir == "" {
		dir = "."
	}

	infos, err := ioutil.ReadDir(dir)
	cands := []*candidate{}

	if err != nil {
		ed.pushTip(fmt.Sprintf("cannot list directory %s: %v", dir, err))
		return cands
	}

	// Make candidates out of elements that match the file component.
	for _, info := range infos {
		name := info.Name()
		// Irrevelant file.
		if !strings.HasPrefix(name, fileprefix) {
			continue
		}
		// Hide dot files unless file starts with a dot.
		if !dotfile(fileprefix) && dotfile(name) {
			continue
		}
		// Only accept searchable directories and executable files if
		// completing head.
		if formHead && !(info.IsDir() || (info.Mode()&0111) != 0) {
			continue
		}

		// Full filename for .getStyle.
		full := head + name[len(fileprefix):]

		if info.IsDir() {
			name += "/"
		}

		cands = append(cands, &candidate{
			source: styled{name[len(fileprefix):], ""},
			menu:   styled{name, defaultLsColor.getStyle(full)},
		})
	}

	return cands
}

func dotfile(fname string) bool {
	return strings.HasPrefix(fname, ".")
}

func isDir(fname string) bool {
	stat, err := os.Stat(fname)
	return err == nil && stat.IsDir()
}
<commit_msg>Fix variable name completion.<commit_after>package edit

import (
	"fmt"
	"io/ioutil"
	"os"
	"path"
	"strings"

	"github.com/elves/elvish/eval"
	"github.com/elves/elvish/parse"
)

// A completer takes the current node
type completer func(parse.Node, *Editor) []*candidate

var completers = []struct {
	name string
	completer
}{
	{"variable", complVariable},
	{"command name", complNewForm},
	{"command name", makeCompoundCompleter(complFormHead)},
	{"argument", complNewArg},
	{"argument", makeCompoundCompleter(complArg)},
}

func complVariable(n parse.Node, ed *Editor) []*candidate {
	primary, ok := n.(*parse.Primary)
	if !ok || primary.Type != parse.Variable {
		return nil
	}

	head := primary.Value
	cands := []*candidate{}
	for variable := range ed.evaler.Global() {
		if strings.HasPrefix(variable, head) {
			cands = append(cands, &candidate{
				source: styled{variable[len(head):], styleForType[Variable]},
				menu:   styled{"$" + variable, styleForType[Variable]}})
		}
	}
	return cands
}

func complNewForm(n parse.Node, ed *Editor) []*candidate {
	if _, ok := n.(*parse.Chunk); ok {
		return complFormHeadInner("", ed)
	}
	if _, ok := n.Parent().(*parse.Chunk); ok {
		return complFormHeadInner("", ed)
	}
	return nil
}

func makeCompoundCompleter(
	f func(*parse.Compound, string, *Editor) []*candidate) completer {
	return func(n parse.Node, ed *Editor) []*candidate {
		pn, ok := n.(*parse.Primary)
		if !ok {
			return nil
		}
		cn, head := simpleCompound(pn)
		if cn == nil {
			return nil
		}
		return f(cn, head, ed)
	}
}

func complFormHead(cn *parse.Compound, head string, ed *Editor) []*candidate {
	if isFormHead(cn) {
		return complFormHeadInner(head, ed)
	}
	return nil
}

func complFormHeadInner(head string, ed *Editor) []*candidate {
	if eval.DontSearch(head) {
		return complArgInner(head, ed, true)
	}

	cands := []*candidate{}

	foundCommand := func(s string) {
		if strings.HasPrefix(s, head) {
			cands = append(cands, &candidate{
				source: styled{s[len(head):], styleForGoodCommand},
				menu:   styled{s, ""},
			})
		}
	}
	for special := range isBuiltinSpecial {
		foundCommand(special)
	}
	for variable := range ed.evaler.Global() {
		if strings.HasPrefix(variable, eval.FnPrefix) {
			foundCommand(variable[len(eval.FnPrefix):])
		}
	}
	for command := range ed.isExternal {
		foundCommand(command)
	}
	return cands
}

func complNewArg(n parse.Node, ed *Editor) []*candidate {
	sn, ok := n.(*parse.Sep)
	if !ok {
		return nil
	}
	if _, ok := sn.Parent().(*parse.Form); !ok {
		return nil
	}
	return complArgInner("", ed, false)
}

func complArg(cn *parse.Compound, head string, ed *Editor) []*candidate {
	return complArgInner(head, ed, false)
}

// TODO: getStyle does redundant stats.
func complArgInner(head string, ed *Editor, formHead bool) []*candidate {
	dir, fileprefix := path.Split(head)
	if dir == "" {
		dir = "."
	}

	infos, err := ioutil.ReadDir(dir)
	cands := []*candidate{}

	if err != nil {
		ed.pushTip(fmt.Sprintf("cannot list directory %s: %v", dir, err))
		return cands
	}

	// Make candidates out of elements that match the file component.
	for _, info := range infos {
		name := info.Name()
		// Irrevelant file.
		if !strings.HasPrefix(name, fileprefix) {
			continue
		}
		// Hide dot files unless file starts with a dot.
		if !dotfile(fileprefix) && dotfile(name) {
			continue
		}
		// Only accept searchable directories and executable files if
		// completing head.
		if formHead && !(info.IsDir() || (info.Mode()&0111) != 0) {
			continue
		}

		// Full filename for .getStyle.
		full := head + name[len(fileprefix):]

		if info.IsDir() {
			name += "/"
		}

		cands = append(cands, &candidate{
			source: styled{name[len(fileprefix):], ""},
			menu:   styled{name, defaultLsColor.getStyle(full)},
		})
	}

	return cands
}

func dotfile(fname string) bool {
	return strings.HasPrefix(fname, ".")
}

func isDir(fname string) bool {
	stat, err := os.Stat(fname)
	return err == nil && stat.IsDir()
}
<|endoftext|>