<commit_before>// Copyright 2013 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.

package main

import (
	"fmt"
	"go/ast"
	"go/token"
	"go/types"
	"sort"

	"golang.org/x/tools/cmd/guru/serial"
	"golang.org/x/tools/go/loader"
	"golang.org/x/tools/go/pointer"
	"golang.org/x/tools/go/ssa"
	"golang.org/x/tools/go/ssa/ssautil"
)

// Callees reports the possible callees of the function call site
// identified by the specified source location.
func callees(q *Query) error {
	lconf := loader.Config{Build: q.Build}

	if err := setPTAScope(&lconf, q.Scope); err != nil {
		return err
	}

	// Load/parse/type-check the program.
	lprog, err := loadWithSoftErrors(&lconf)
	if err != nil {
		return err
	}

	qpos, err := parseQueryPos(lprog, q.Pos, true) // needs exact pos
	if err != nil {
		return err
	}

	// Determine the enclosing call for the specified position.
	var e *ast.CallExpr
	for _, n := range qpos.path {
		if e, _ = n.(*ast.CallExpr); e != nil {
			break
		}
	}
	if e == nil {
		return fmt.Errorf("there is no function call here")
	}
	// TODO(adonovan): issue an error if the call is "too far
	// away" from the current selection, as this most likely is
	// not what the user intended.

	// Reject type conversions.
	if qpos.info.Types[e.Fun].IsType() {
		return fmt.Errorf("this is a type conversion, not a function call")
	}

	// Deal with obviously static calls before constructing SSA form.
	// Some static calls may yet require SSA construction,
	// e.g.  f := func(){}; f().
	switch funexpr := unparen(e.Fun).(type) {
	case *ast.Ident:
		switch obj := qpos.info.Uses[funexpr].(type) {
		case *types.Builtin:
			// Reject calls to built-ins.
			return fmt.Errorf("this is a call to the built-in '%s' operator", obj.Name())
		case *types.Func:
			// This is a static function call
			q.Output(lprog.Fset, &calleesTypesResult{
				site:   e,
				callee: obj,
			})
			return nil
		}
	case *ast.SelectorExpr:
		sel := qpos.info.Selections[funexpr]
		if sel == nil {
			// qualified identifier.
			// May refer to top level function variable
			// or to top level function.
			callee := qpos.info.Uses[funexpr.Sel]
			if obj, ok := callee.(*types.Func); ok {
				q.Output(lprog.Fset, &calleesTypesResult{
					site:   e,
					callee: obj,
				})
				return nil
			}
		} else if sel.Kind() == types.MethodVal {
			// Inspect the receiver type of the selected method.
			// If it is concrete, the call is statically dispatched.
			// (Due to implicit field selections, it is not enough to look
			// at sel.Recv(), the type of the actual receiver expression.)
			method := sel.Obj().(*types.Func)
			recvtype := method.Type().(*types.Signature).Recv().Type()
			if !types.IsInterface(recvtype) {
				// static method call
				q.Output(lprog.Fset, &calleesTypesResult{
					site:   e,
					callee: method,
				})
				return nil
			}
		}
	}

	prog := ssautil.CreateProgram(lprog, ssa.GlobalDebug)

	ptaConfig, err := setupPTA(prog, lprog, q.PTALog, q.Reflection)
	if err != nil {
		return err
	}

	pkg := prog.Package(qpos.info.Pkg)
	if pkg == nil {
		return fmt.Errorf("no SSA package")
	}

	// Defer SSA construction till after errors are reported.
	prog.Build()

	// Ascertain calling function and call site.
	callerFn := ssa.EnclosingFunction(pkg, qpos.path)
	if callerFn == nil {
		return fmt.Errorf("no SSA function built for this location (dead code?)")
	}

	// Find the call site.
	site, err := findCallSite(callerFn, e)
	if err != nil {
		return err
	}

	funcs, err := findCallees(ptaConfig, site)
	if err != nil {
		return err
	}

	q.Output(lprog.Fset, &calleesSSAResult{
		site:  site,
		funcs: funcs,
	})
	return nil
}

func findCallSite(fn *ssa.Function, call *ast.CallExpr) (ssa.CallInstruction, error) {
	instr, _ := fn.ValueForExpr(call)
	callInstr, _ := instr.(ssa.CallInstruction)
	if instr == nil {
		return nil, fmt.Errorf("this call site is unreachable in this analysis")
	}
	return callInstr, nil
}

func findCallees(conf *pointer.Config, site ssa.CallInstruction) ([]*ssa.Function, error) {
	// Avoid running the pointer analysis for static calls.
	if callee := site.Common().StaticCallee(); callee != nil {
		switch callee.String() {
		case "runtime.SetFinalizer", "(reflect.Value).Call":
			// The PTA treats calls to these intrinsics as dynamic.
			// TODO(adonovan): avoid reliance on PTA internals.

		default:
			return []*ssa.Function{callee}, nil // singleton
		}
	}

	// Dynamic call: use pointer analysis.
	conf.BuildCallGraph = true
	cg := ptrAnalysis(conf).CallGraph
	cg.DeleteSyntheticNodes()

	// Find all call edges from the site.
	n := cg.Nodes[site.Parent()]
	if n == nil {
		return nil, fmt.Errorf("this call site is unreachable in this analysis")
	}
	calleesMap := make(map[*ssa.Function]bool)
	for _, edge := range n.Out {
		if edge.Site == site {
			calleesMap[edge.Callee.Func] = true
		}
	}

	// De-duplicate and sort.
	funcs := make([]*ssa.Function, 0, len(calleesMap))
	for f := range calleesMap {
		funcs = append(funcs, f)
	}
	sort.Sort(byFuncPos(funcs))
	return funcs, nil
}

type calleesSSAResult struct {
	site  ssa.CallInstruction
	funcs []*ssa.Function
}

type calleesTypesResult struct {
	site   *ast.CallExpr
	callee *types.Func
}

func (r *calleesSSAResult) PrintPlain(printf printfFunc) {
	if len(r.funcs) == 0 {
		// dynamic call on a provably nil func/interface
		printf(r.site, "%s on nil value", r.site.Common().Description())
	} else {
		printf(r.site, "this %s dispatches to:", r.site.Common().Description())
		for _, callee := range r.funcs {
			printf(callee, "\t%s", callee)
		}
	}
}

func (r *calleesSSAResult) JSON(fset *token.FileSet) []byte {
	j := &serial.Callees{
		Pos:  fset.Position(r.site.Pos()).String(),
		Desc: r.site.Common().Description(),
	}
	for _, callee := range r.funcs {
		j.Callees = append(j.Callees, &serial.Callee{
			Name: callee.String(),
			Pos:  fset.Position(callee.Pos()).String(),
		})
	}
	return toJSON(j)
}

func (r *calleesTypesResult) PrintPlain(printf printfFunc) {
	printf(r.site, "this static function call dispatches to:")
	printf(r.callee, "\t%s", r.callee.FullName())
}

func (r *calleesTypesResult) JSON(fset *token.FileSet) []byte {
	j := &serial.Callees{
		Pos:  fset.Position(r.site.Pos()).String(),
		Desc: "static function call",
	}
	j.Callees = []*serial.Callee{
		&serial.Callee{
			Name: r.callee.FullName(),
			Pos:  fset.Position(r.callee.Pos()).String(),
		},
	}
	return toJSON(j)
}

// NB: byFuncPos is not deterministic across packages since it depends on load order.
// Use lessPos if the tests need it.
type byFuncPos []*ssa.Function

func (a byFuncPos) Len() int           { return len(a) }
func (a byFuncPos) Less(i, j int) bool { return a[i].Pos() < a[j].Pos() }
func (a byFuncPos) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
<commit_msg>x/tools/cmd/guru: gofmt -s -w<commit_after>// Copyright 2013 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.

package main

import (
	"fmt"
	"go/ast"
	"go/token"
	"go/types"
	"sort"

	"golang.org/x/tools/cmd/guru/serial"
	"golang.org/x/tools/go/loader"
	"golang.org/x/tools/go/pointer"
	"golang.org/x/tools/go/ssa"
	"golang.org/x/tools/go/ssa/ssautil"
)

// Callees reports the possible callees of the function call site
// identified by the specified source location.
func callees(q *Query) error {
	lconf := loader.Config{Build: q.Build}

	if err := setPTAScope(&lconf, q.Scope); err != nil {
		return err
	}

	// Load/parse/type-check the program.
	lprog, err := loadWithSoftErrors(&lconf)
	if err != nil {
		return err
	}

	qpos, err := parseQueryPos(lprog, q.Pos, true) // needs exact pos
	if err != nil {
		return err
	}

	// Determine the enclosing call for the specified position.
	var e *ast.CallExpr
	for _, n := range qpos.path {
		if e, _ = n.(*ast.CallExpr); e != nil {
			break
		}
	}
	if e == nil {
		return fmt.Errorf("there is no function call here")
	}
	// TODO(adonovan): issue an error if the call is "too far
	// away" from the current selection, as this most likely is
	// not what the user intended.

	// Reject type conversions.
	if qpos.info.Types[e.Fun].IsType() {
		return fmt.Errorf("this is a type conversion, not a function call")
	}

	// Deal with obviously static calls before constructing SSA form.
	// Some static calls may yet require SSA construction,
	// e.g.  f := func(){}; f().
	switch funexpr := unparen(e.Fun).(type) {
	case *ast.Ident:
		switch obj := qpos.info.Uses[funexpr].(type) {
		case *types.Builtin:
			// Reject calls to built-ins.
			return fmt.Errorf("this is a call to the built-in '%s' operator", obj.Name())
		case *types.Func:
			// This is a static function call
			q.Output(lprog.Fset, &calleesTypesResult{
				site:   e,
				callee: obj,
			})
			return nil
		}
	case *ast.SelectorExpr:
		sel := qpos.info.Selections[funexpr]
		if sel == nil {
			// qualified identifier.
			// May refer to top level function variable
			// or to top level function.
			callee := qpos.info.Uses[funexpr.Sel]
			if obj, ok := callee.(*types.Func); ok {
				q.Output(lprog.Fset, &calleesTypesResult{
					site:   e,
					callee: obj,
				})
				return nil
			}
		} else if sel.Kind() == types.MethodVal {
			// Inspect the receiver type of the selected method.
			// If it is concrete, the call is statically dispatched.
			// (Due to implicit field selections, it is not enough to look
			// at sel.Recv(), the type of the actual receiver expression.)
			method := sel.Obj().(*types.Func)
			recvtype := method.Type().(*types.Signature).Recv().Type()
			if !types.IsInterface(recvtype) {
				// static method call
				q.Output(lprog.Fset, &calleesTypesResult{
					site:   e,
					callee: method,
				})
				return nil
			}
		}
	}

	prog := ssautil.CreateProgram(lprog, ssa.GlobalDebug)

	ptaConfig, err := setupPTA(prog, lprog, q.PTALog, q.Reflection)
	if err != nil {
		return err
	}

	pkg := prog.Package(qpos.info.Pkg)
	if pkg == nil {
		return fmt.Errorf("no SSA package")
	}

	// Defer SSA construction till after errors are reported.
	prog.Build()

	// Ascertain calling function and call site.
	callerFn := ssa.EnclosingFunction(pkg, qpos.path)
	if callerFn == nil {
		return fmt.Errorf("no SSA function built for this location (dead code?)")
	}

	// Find the call site.
	site, err := findCallSite(callerFn, e)
	if err != nil {
		return err
	}

	funcs, err := findCallees(ptaConfig, site)
	if err != nil {
		return err
	}

	q.Output(lprog.Fset, &calleesSSAResult{
		site:  site,
		funcs: funcs,
	})
	return nil
}

func findCallSite(fn *ssa.Function, call *ast.CallExpr) (ssa.CallInstruction, error) {
	instr, _ := fn.ValueForExpr(call)
	callInstr, _ := instr.(ssa.CallInstruction)
	if instr == nil {
		return nil, fmt.Errorf("this call site is unreachable in this analysis")
	}
	return callInstr, nil
}

func findCallees(conf *pointer.Config, site ssa.CallInstruction) ([]*ssa.Function, error) {
	// Avoid running the pointer analysis for static calls.
	if callee := site.Common().StaticCallee(); callee != nil {
		switch callee.String() {
		case "runtime.SetFinalizer", "(reflect.Value).Call":
			// The PTA treats calls to these intrinsics as dynamic.
			// TODO(adonovan): avoid reliance on PTA internals.

		default:
			return []*ssa.Function{callee}, nil // singleton
		}
	}

	// Dynamic call: use pointer analysis.
	conf.BuildCallGraph = true
	cg := ptrAnalysis(conf).CallGraph
	cg.DeleteSyntheticNodes()

	// Find all call edges from the site.
	n := cg.Nodes[site.Parent()]
	if n == nil {
		return nil, fmt.Errorf("this call site is unreachable in this analysis")
	}
	calleesMap := make(map[*ssa.Function]bool)
	for _, edge := range n.Out {
		if edge.Site == site {
			calleesMap[edge.Callee.Func] = true
		}
	}

	// De-duplicate and sort.
	funcs := make([]*ssa.Function, 0, len(calleesMap))
	for f := range calleesMap {
		funcs = append(funcs, f)
	}
	sort.Sort(byFuncPos(funcs))
	return funcs, nil
}

type calleesSSAResult struct {
	site  ssa.CallInstruction
	funcs []*ssa.Function
}

type calleesTypesResult struct {
	site   *ast.CallExpr
	callee *types.Func
}

func (r *calleesSSAResult) PrintPlain(printf printfFunc) {
	if len(r.funcs) == 0 {
		// dynamic call on a provably nil func/interface
		printf(r.site, "%s on nil value", r.site.Common().Description())
	} else {
		printf(r.site, "this %s dispatches to:", r.site.Common().Description())
		for _, callee := range r.funcs {
			printf(callee, "\t%s", callee)
		}
	}
}

func (r *calleesSSAResult) JSON(fset *token.FileSet) []byte {
	j := &serial.Callees{
		Pos:  fset.Position(r.site.Pos()).String(),
		Desc: r.site.Common().Description(),
	}
	for _, callee := range r.funcs {
		j.Callees = append(j.Callees, &serial.Callee{
			Name: callee.String(),
			Pos:  fset.Position(callee.Pos()).String(),
		})
	}
	return toJSON(j)
}

func (r *calleesTypesResult) PrintPlain(printf printfFunc) {
	printf(r.site, "this static function call dispatches to:")
	printf(r.callee, "\t%s", r.callee.FullName())
}

func (r *calleesTypesResult) JSON(fset *token.FileSet) []byte {
	j := &serial.Callees{
		Pos:  fset.Position(r.site.Pos()).String(),
		Desc: "static function call",
	}
	j.Callees = []*serial.Callee{
		{
			Name: r.callee.FullName(),
			Pos:  fset.Position(r.callee.Pos()).String(),
		},
	}
	return toJSON(j)
}

// NB: byFuncPos is not deterministic across packages since it depends on load order.
// Use lessPos if the tests need it.
type byFuncPos []*ssa.Function

func (a byFuncPos) Len() int           { return len(a) }
func (a byFuncPos) Less(i, j int) bool { return a[i].Pos() < a[j].Pos() }
func (a byFuncPos) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
<|endoftext|>


<commit_before>// Copyright © 2016 Govinda Fichtner <govinda.fichtner@googlemail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package cmd

import (
	"fmt"
	"github.com/spf13/cobra"
	"io/ioutil"
	"os/exec"
	"strings"
)

// setCmd represents the set command
var setHostnameCmd = &cobra.Command{
	Use:   "set [hostname]",
	Short: "Set a hostname",
	Long:  ``,
	Run: func(cmd *cobra.Command, args []string) {
		if len(args) > 0 {
			set_hostname(args[0])
		} else {
			cmd.Help()
		}
	},
}

func init() {
	hostnameCmd.AddCommand(setHostnameCmd)
}

func set_hostname(args ...string) {
	hostname := ""

	// if we have hostname in config file use that
	if config.IsSet("hostname") {
		hostname = config.GetString("hostname")
	}

	// if we have a hostname as command line arg use that
	if len(args) > 0 {
		hostname = args[0]
	}

	if hostname == "" && cfgFile == "" {
		fmt.Println("missing hostname argument")
		return
	}

	if hostname != "" {
		err := ioutil.WriteFile("/etc/hostname", []byte(hostname), 0644)
		if err != nil {
			panic(err)
		}

		input, err := ioutil.ReadFile("/etc/hosts")
		if err != nil {
			panic(err)
		}

		lines := strings.Split(string(input), "\n")

		for i, line := range lines {
			if strings.Contains(line, "127.0.0.1	localhost") {
				lines[i] = fmt.Sprintf("127.0.0.1	localhost	%s", hostname)
			}
		}
		output := strings.Join(lines, "\n")
		err = ioutil.WriteFile("/etc/hosts", []byte(output), 0644)
		if err != nil {
			panic(err)
		}

		set_hostname_cmd := exec.Command("hostname", hostname)
		err = set_hostname_cmd.Run()
		if err != nil {
			panic(err)
		}

		fmt.Printf("Set hostname: %s\n", hostname)
	}
}
<commit_msg>improve setting of hostname<commit_after>// Copyright © 2016 Govinda Fichtner <govinda.fichtner@googlemail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package cmd

import (
	"fmt"
	"github.com/spf13/cobra"
	"io/ioutil"
	"os/exec"
	"regexp"
	"strings"
)

// setCmd represents the set command
var setHostnameCmd = &cobra.Command{
	Use:   "set [hostname]",
	Short: "Set a hostname",
	Long:  ``,
	Run: func(cmd *cobra.Command, args []string) {
		if len(args) > 0 {
			set_hostname(args[0])
		} else {
			cmd.Help()
		}
	},
}

func init() {
	hostnameCmd.AddCommand(setHostnameCmd)
}

func set_hostname(args ...string) {
	hostname := ""

	// if we have hostname in config file use that
	if config.IsSet("hostname") {
		hostname = config.GetString("hostname")
	}

	// if we have a hostname as command line arg use that
	if len(args) > 0 {
		hostname = args[0]
	}

	if hostname == "" && cfgFile == "" {
		fmt.Println("missing hostname argument")
		return
	}

	if hostname != "" {
		err := ioutil.WriteFile("/etc/hostname", []byte(hostname), 0644)
		if err != nil {
			panic(err)
		}

		input, err := ioutil.ReadFile("/etc/hosts")
		if err != nil {
			panic(err)
		}

		lines := strings.Split(string(input), "\n")

		for i, line := range lines {
			if strings.Contains(line, "127.0.0.1	localhost") {
				lines[i] = fmt.Sprintf("127.0.0.1	localhost	%s", hostname)
			}
		}
		output := strings.Join(lines, "\n")
		err = ioutil.WriteFile("/etc/hosts", []byte(output), 0644)
		if err != nil {
			panic(err)
		}

		err = exec.Command("hostname", hostname).Run()
		if err != nil {
			fmt.Println("Unable to set hostname: ", err)
		}

		// ensure that dhcp server and avahi daemon are aware of new hostname
		for _, interfaceName := range activeInterfaces() {
			err = exec.Command("/sbin/ifdown", interfaceName).Run()
			if err != nil {
				fmt.Println("Unable to bring interface down: ", interfaceName, err)
			}

			err = exec.Command("/sbin/ifup", interfaceName).Run()
			if err != nil {
				fmt.Println("Unable to bring interface up: ", interfaceName, err)
			}
		}

		err = exec.Command("/bin/systemctl", "restart", "avahi-daemon").Run()
		if err != nil {
			fmt.Println("Unable to set hostname: ", err)
		}

		fmt.Printf("Set hostname: %s\n", hostname)
	}
}

func activeInterfaces() []string {
	var result []string
	output, err := exec.Command("ip", "link").Output()
	if err != nil {
		fmt.Println("Could not run 'ip link'", err)
	}
	lines := strings.Split(string(output), "\n")
	for _, line := range lines {
		interfaceIsUp, _ := regexp.MatchString("state UP", line)
		if interfaceIsUp {
			re := regexp.MustCompile(`^\d*:\s([a-z0-9@]*):`)
			result = append(result, re.FindStringSubmatch(line)[1])
		}
	}
	return result
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"runtime/debug"
	"runtime/trace"
	"strings"
	"syscall"
	"time"

	"github.com/funkygao/gafka"
	"github.com/funkygao/gafka/cmd/kateway/gateway"
	"github.com/funkygao/gafka/ctx"
	"github.com/funkygao/golib/color"
	"github.com/funkygao/golib/signal"
	glog "github.com/funkygao/log4go"
)

func init() {
	gateway.ParseFlags()
	gateway.ValidateFlags()
}

func main() {
	defer func() {
		if err := recover(); err != nil {
			fmt.Println(err)
			debug.PrintStack()
		}
	}()

	if gateway.Options.Debug {
		log.SetFlags(log.LstdFlags | log.Llongfile) // TODO zk sdk uses this
		log.SetPrefix(color.Magenta("[log]"))
	} else {
		log.SetOutput(ioutil.Discard)
	}

	if gateway.Options.KillFile != "" {
		if err := signal.SignalProcessByPidFile(gateway.Options.KillFile, syscall.SIGUSR2); err != nil {
			panic(err)
		}

		fmt.Println("kateway killed")
		os.Exit(0)
	}

	if gateway.Options.GolangTrace {
		// go tool trace kateway xxx.pprof
		f, err := os.Create(time.Now().Format("2006-01-02T150405.pprof"))
		if err != nil {
			panic(err)
		}
		defer f.Close()

		if err = trace.Start(f); err != nil {
			panic(err)
		}
		defer trace.Stop()
	}

	fmt.Fprintln(os.Stderr, strings.TrimSpace(logo))

	if gateway.Options.PidFile != "" {
		pid := os.Getpid()
		if err := ioutil.WriteFile(gateway.Options.PidFile, []byte(fmt.Sprintf("%d", pid)), 0644); err != nil {
			panic(err)
		}
	}

	gateway.SetupLogging(gateway.Options.LogFile, gateway.Options.LogLevel, gateway.Options.CrashLogFile)

	// load config
	if gateway.Options.ConfigFile == "" {
		ctx.LoadFromHome()
	} else {
		_, err := os.Stat(gateway.Options.ConfigFile)
		if err != nil {
			panic(err)
		}
		ctx.LoadConfig(gateway.Options.ConfigFile)
	}

	gateway.EnsureValidUlimit()
	debug.SetGCPercent(800) // same env GOGC TODO

	gw := gateway.New(gateway.Options.Id)
	if err := gw.Start(); err != nil {
		glog.Error(err.Error())
		glog.Info("kateway[%s@%s] bye!", gafka.BuildId, gafka.BuiltAt)
		glog.Close()
		os.Exit(1)
	}

	gw.ServeForever()
	glog.Info("kateway[%s@%s] bye!", gafka.BuildId, gafka.BuiltAt)
	glog.Close()

	if gateway.Options.PidFile != "" {
		syscall.Unlink(gateway.Options.PidFile)
	}
}
<commit_msg>before die, report how long kateway runs<commit_after>package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"runtime/debug"
	"runtime/trace"
	"strings"
	"syscall"
	"time"

	"github.com/funkygao/gafka"
	"github.com/funkygao/gafka/cmd/kateway/gateway"
	"github.com/funkygao/gafka/ctx"
	"github.com/funkygao/golib/color"
	"github.com/funkygao/golib/signal"
	glog "github.com/funkygao/log4go"
)

func init() {
	gateway.ParseFlags()
	gateway.ValidateFlags()
}

func main() {
	defer func() {
		if err := recover(); err != nil {
			fmt.Println(err)
			debug.PrintStack()
		}
	}()

	if gateway.Options.Debug {
		log.SetFlags(log.LstdFlags | log.Llongfile) // TODO zk sdk uses this
		log.SetPrefix(color.Magenta("[log]"))
	} else {
		log.SetOutput(ioutil.Discard)
	}

	if gateway.Options.KillFile != "" {
		if err := signal.SignalProcessByPidFile(gateway.Options.KillFile, syscall.SIGUSR2); err != nil {
			panic(err)
		}

		fmt.Println("kateway killed")
		os.Exit(0)
	}

	if gateway.Options.GolangTrace {
		// go tool trace kateway xxx.pprof
		f, err := os.Create(time.Now().Format("2006-01-02T150405.pprof"))
		if err != nil {
			panic(err)
		}
		defer f.Close()

		if err = trace.Start(f); err != nil {
			panic(err)
		}
		defer trace.Stop()
	}

	fmt.Fprintln(os.Stderr, strings.TrimSpace(logo))

	if gateway.Options.PidFile != "" {
		pid := os.Getpid()
		if err := ioutil.WriteFile(gateway.Options.PidFile, []byte(fmt.Sprintf("%d", pid)), 0644); err != nil {
			panic(err)
		}
	}

	gateway.SetupLogging(gateway.Options.LogFile, gateway.Options.LogLevel, gateway.Options.CrashLogFile)

	// load config
	if gateway.Options.ConfigFile == "" {
		ctx.LoadFromHome()
	} else {
		_, err := os.Stat(gateway.Options.ConfigFile)
		if err != nil {
			panic(err)
		}
		ctx.LoadConfig(gateway.Options.ConfigFile)
	}

	gateway.EnsureValidUlimit()
	debug.SetGCPercent(800) // same env GOGC TODO

	gw := gateway.New(gateway.Options.Id)
	if err := gw.Start(); err != nil {
		glog.Error(err.Error())
		glog.Info("kateway[%s@%s] bye!", gafka.BuildId, gafka.BuiltAt)
		glog.Close()
		os.Exit(1)
	}

	t0 := time.Now()
	gw.ServeForever()
	glog.Info("kateway[%s@%s] %s, bye!", gafka.BuildId, gafka.BuiltAt, time.Since(t0))
	glog.Close()

	if gateway.Options.PidFile != "" {
		syscall.Unlink(gateway.Options.PidFile)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"os"
	"os/signal"
	"strings"
	"syscall"

	"github.com/emicklei/melrose"
	"github.com/emicklei/melrose/dsl"
	"github.com/emicklei/melrose/notify"
	"github.com/emicklei/melrose/server"
	"github.com/peterh/liner"
)

var (
	version   = "dev"
	verbose   = flag.Bool("v", false, "verbose logging")
	inputFile = flag.String("i", "", "read expressions from a file")
	httpPort  = flag.String("http", ":8118", "address on which to listen for HTTP requests")

	history                         = ".melrose.history"
	globalStore dsl.VariableStorage = dsl.NewVariableStore()
)

func main() {
	welcome()
	flag.Parse()

	// set audio
	currentDevice := setupAudio("midi")
	defer currentDevice.Close()
	melrose.Context().SetCurrentDevice(currentDevice)

	// process file if given
	if len(*inputFile) > 0 {
		processInputFile(globalStore, *inputFile)
	}

	loopControl := melrose.Context().LoopControl

	if len(*httpPort) > 0 {
		// start DSL server
		go server.NewLanguageServer(globalStore, loopControl, *httpPort).Start()
	}

	// start REPL
	line := liner.NewLiner()
	defer line.Close()
	defer tearDown(line, globalStore, loopControl)
	// TODO liner catches control+c
	//setupCloseHandler(line)
	setup(line)
	repl(line, globalStore, loopControl)
}

func welcome() {
	fmt.Println("\033[1;34mmelrōse\033[0m" + " - program your melodies")
}

var functionNames = []string{"play"}

func tearDown(line *liner.State, store dsl.VariableStorage, control melrose.LoopController) {
	dsl.StopAllLoops(store)
	control.Stop()
	if f, err := os.Create(history); err != nil {
		notify.Print(notify.Errorf("error writing history file:%v", err))
	} else {
		line.WriteHistory(f)
		f.Close()
	}
	fmt.Println("\033[1;34mmelrose\033[0m" + " sings bye!")
}

func setup(line *liner.State) {
	line.SetCtrlCAborts(true)
	line.SetWordCompleter(completeMe)
	if f, err := os.Open(history); err == nil {
		line.ReadHistory(f)
		f.Close()
	}
}

func repl(line *liner.State, store dsl.VariableStorage, control melrose.LoopController) {
	eval := dsl.NewEvaluator(store, control)
	control.Start()
	for {
		entry, err := line.Prompt("𝄞 ")
		if err != nil {
			notify.Print(notify.Error(err))
			continue
		}
		entry = strings.TrimSpace(entry)
		if strings.HasPrefix(entry, ":") {
			// special case
			if entry == ":q" || entry == ":Q" {
				goto exit
			}
			args := strings.Split(entry, " ")
			if cmd, ok := lookupCommand(args[0]); ok {
				if msg := cmd.Func(args[1:]); msg != nil {
					notify.Print(msg)
				}
				continue
			}
		}
		if result, err := eval.EvaluateStatement(entry); err != nil {
			notify.Print(notify.Error(err))
			// even on error, add entry to history so we can edit/fix it
		} else {
			if result != nil {
				melrose.PrintValue(result)
			}
		}
		line.AppendHistory(entry)
	}
exit:
}

func processInputFile(store dsl.VariableStorage, inputFile string) {
	data, err := ioutil.ReadFile(inputFile)
	if err != nil {
		notify.Print(notify.Errorf("unable to read file:%v", err))
		return
	}
	eval := dsl.NewEvaluator(store, melrose.NoLooper)
	for line, each := range strings.Split(string(data), "\n") {
		entry := strings.TrimSpace(each)
		if _, err := eval.EvaluateStatement(entry); err != nil {
			notify.Print(notify.Errorf("line %d:%v", line, err))
		}
	}
}

// setupCloseHandler creates a 'listener' on a new goroutine which will notify the
// program if it receives an interrupt from the OS. We then handle this by calling
// our clean up procedure and exiting the program.
func setupCloseHandler(line *liner.State, control melrose.LoopController) {
	c := make(chan os.Signal)
	signal.Notify(c, os.Interrupt, syscall.SIGTERM)
	go func() {
		<-c
		fmt.Println("\r- Ctrl+C pressed in Terminal")
		tearDown(line, globalStore, control)
		os.Exit(0)
	}()
}
<commit_msg>work on process input file<commit_after>package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"os"
	"os/signal"
	"strings"
	"syscall"

	"github.com/emicklei/melrose"
	"github.com/emicklei/melrose/dsl"
	"github.com/emicklei/melrose/notify"
	"github.com/emicklei/melrose/server"
	"github.com/peterh/liner"
)

var (
	version   = "dev"
	verbose   = flag.Bool("v", false, "verbose logging")
	inputFile = flag.String("i", "", "read expressions from a file")
	httpPort  = flag.String("http", ":8118", "address on which to listen for HTTP requests")

	history                         = ".melrose.history"
	globalStore dsl.VariableStorage = dsl.NewVariableStore()
)

func main() {
	welcome()
	flag.Parse()

	// set audio
	currentDevice := setupAudio("midi")
	defer currentDevice.Close()
	melrose.Context().SetCurrentDevice(currentDevice)

	// process file if given
	if len(*inputFile) > 0 {
		if err := processInputFile(globalStore, *inputFile); err != nil {
			notify.Print(notify.Error(err))
			os.Exit(0)
		}
	}

	loopControl := melrose.Context().LoopControl

	if len(*httpPort) > 0 {
		// start DSL server
		go server.NewLanguageServer(globalStore, loopControl, *httpPort).Start()
	}

	// start REPL
	line := liner.NewLiner()
	defer line.Close()
	defer tearDown(line, globalStore, loopControl)
	// TODO liner catches control+c
	//setupCloseHandler(line)
	setup(line)
	repl(line, globalStore, loopControl)
}

func welcome() {
	fmt.Println("\033[1;34mmelrōse\033[0m" + " - program your melodies")
}

func tearDown(line *liner.State, store dsl.VariableStorage, control melrose.LoopController) {
	dsl.StopAllLoops(store)
	control.Stop()
	if f, err := os.Create(history); err != nil {
		notify.Print(notify.Errorf("error writing history file:%v", err))
	} else {
		line.WriteHistory(f)
		f.Close()
	}
	fmt.Println("\033[1;34mmelrose\033[0m" + " sings bye!")
}

func setup(line *liner.State) {
	line.SetCtrlCAborts(true)
	line.SetWordCompleter(completeMe)
	if f, err := os.Open(history); err == nil {
		line.ReadHistory(f)
		f.Close()
	}
}

func repl(line *liner.State, store dsl.VariableStorage, control melrose.LoopController) {
	eval := dsl.NewEvaluator(store, control)
	control.Start()
	for {
		entry, err := line.Prompt("𝄞 ")
		if err != nil {
			notify.Print(notify.Error(err))
			continue
		}
		entry = strings.TrimSpace(entry)
		if strings.HasPrefix(entry, ":") {
			// special case
			if entry == ":q" || entry == ":Q" {
				goto exit
			}
			args := strings.Split(entry, " ")
			if cmd, ok := lookupCommand(args[0]); ok {
				if msg := cmd.Func(args[1:]); msg != nil {
					notify.Print(msg)
				}
				continue
			}
		}
		if result, err := eval.EvaluateStatement(entry); err != nil {
			notify.Print(notify.Error(err))
			// even on error, add entry to history so we can edit/fix it
		} else {
			if result != nil {
				melrose.PrintValue(result)
			}
		}
		line.AppendHistory(entry)
	}
exit:
}

func processInputFile(store dsl.VariableStorage, inputFile string) error {
	data, err := ioutil.ReadFile(inputFile)
	if err != nil {
		notify.Print(notify.Errorf("unable to read file:%v", err))
		return nil
	}
	eval := dsl.NewEvaluator(store, melrose.NoLooper)
	_, err = eval.EvaluateProgram(string(data))
	return err
}

// setupCloseHandler creates a 'listener' on a new goroutine which will notify the
// program if it receives an interrupt from the OS. We then handle this by calling
// our clean up procedure and exiting the program.
func setupCloseHandler(line *liner.State, control melrose.LoopController) {
	c := make(chan os.Signal)
	signal.Notify(c, os.Interrupt, syscall.SIGTERM)
	go func() {
		<-c
		fmt.Println("\r- Ctrl+C pressed in Terminal")
		tearDown(line, globalStore, control)
		os.Exit(0)
	}()
}
<|endoftext|>


<commit_before>// Copyright (c) 2016, Ben Morgan. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.

package main

import (
	"errors"
	"fmt"
	"os"
	"os/exec"

	"github.com/cassava/repoctl"
	"github.com/cassava/repoctl/conf"
	"github.com/goulash/color"
	"github.com/spf13/cobra"
)

// Repo lets us use the repoctl library to do the most of the work.
var Repo *repoctl.Repo

// Conf loads and stores the configuration (apart from command line
// configuration) of this program, including where the repository is.
var Conf = conf.Default()

// col lets us print in colors.
var col = color.New()

type UsageError struct {
	Cmd   string
	Msg   string
	Usage func() error
}

func (e *UsageError) Error() string {
	return fmt.Sprintf("%s", e.Msg)
}

type ExecError struct {
	Err     error
	Output  string
	Command string
}

func (err *ExecError) Error() string { return err.Err.Error() }

// runShellCommand runs the cmd in a shell and returns whether an error occurred.
// If an error is returned, it is of type *ExecError, which contains the field
// `Output` that contains the commands stdout and stderr output.
func runShellCommand(cmd string) error {
	bs, err := exec.Command("sh", "-c", cmd).CombinedOutput()
	if err != nil {
		return &ExecError{
			Err:     err,
			Output:  string(bs),
			Command: cmd,
		}
	}
	return nil
}

var MainCmd = &cobra.Command{
	Use:   "repoctl",
	Short: "manage local Pacman repositories",
	Long: `Repoctl helps manage local Pacman repositories, and acts in particular as
a supplement to the repo-add and repo-remove tools that come with Pacman.

Whether compiling and installing from AUR every time is not what you want,
or if you want to host your own repository, repoctl is right for you.

Note that in all of these commands, the following terminology is used:

    pkgname: is the name of the package, e.g. pacman
    pkgfile: is the path to a package file, e.g. pacman-3.5.3-i686.pkg.tar.xz
`,
	PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
		// This function can be overriden if it's not necessary for a command.
		cmd.SilenceErrors = true
		cmd.SilenceUsage = true
		if Conf.Unconfigured {
			return errors.New("repoctl is unconfigured, please create configuration")
		} else if Conf.Repository == "" {
			return conf.ErrRepoUnset
		}
		Repo = Conf.Repo()

		if Conf.PreAction != "" {
			return runShellCommand(Conf.PreAction)
		}
		return nil
	},
	PersistentPostRunE: func(cmd *cobra.Command, args []string) error {
		// If PersistentPreRunE was overridden, then don't execute this step.
		// We can determine this by looking to see if Repo was set.
		if Conf.PostAction != "" && Repo != nil {
			return runShellCommand(Conf.PostAction)
		}
		return nil
	},
}

func addConfFlags(cmd *cobra.Command) {
	cmd.PersistentFlags().BoolVarP(&Conf.Backup, "backup", "b", Conf.Backup, "backup obsolete files instead of deleting")
	cmd.PersistentFlags().StringVarP(&Conf.BackupDir, "backup-dir", "B", Conf.BackupDir, "backup directory relative to repository path")
	cmd.PersistentFlags().BoolVarP(&Conf.Columnate, "columns", "s", Conf.Columnate, "show items in columns rather than lines")
	cmd.PersistentFlags().BoolVarP(&Conf.Quiet, "quiet", "q", Conf.Quiet, "show minimal amount of information")
	cmd.PersistentFlags().BoolVar(&Conf.Debug, "debug", Conf.Debug, "show unnecessary debugging information")
	col.Set(Conf.Color) // set default, which will be auto if Conf.Color is empty or invalid
	cmd.PersistentFlags().Var(col, "color", "when to use color (auto|never|always)")
}

// main loads the configuration and executes the primary command.
func main() {
	err := Conf.MergeAll()
	if err != nil {
		// We didn't manage to load any configuration, which means that repoctl
		// is unconfigured. There are some commands that work nonetheless, so
		// we can't stop now -- which is why we don't os.Exit(1).
		fmt.Fprintf(os.Stderr, "Error: %s\n", err)
	}

	// Arguments from the command line override the configuration file,
	// so we have to add the flags after loading the configuration.
	//
	// TODO: Maybe in the future we will make it possible to specify the
	// configuration file via the command line; right now it is not a priority.
	addConfFlags(MainCmd)

	err = MainCmd.Execute()
	if err != nil {
		// If this is an ExecError, we deal with it specially:
		if e, ok := err.(*ExecError); ok {
			fmt.Fprintf(os.Stderr, "Error: command %q failed: %s\n", e.Command, e.Err)
			fmt.Fprintf(os.Stderr, "Command output:\n%s", e.Output)
			os.Exit(1)
		}

		// All other errors:
		fmt.Fprintf(os.Stderr, "Error: %s\n", err)
		if e, ok := err.(*UsageError); ok {
			e.Usage()
		}
		os.Exit(1)
	}
}
<commit_msg>Toning down the hype in the help message<commit_after>// Copyright (c) 2016, Ben Morgan. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.

package main

import (
	"errors"
	"fmt"
	"os"
	"os/exec"

	"github.com/cassava/repoctl"
	"github.com/cassava/repoctl/conf"
	"github.com/goulash/color"
	"github.com/spf13/cobra"
)

// Repo lets us use the repoctl library to do the most of the work.
var Repo *repoctl.Repo

// Conf loads and stores the configuration (apart from command line
// configuration) of this program, including where the repository is.
var Conf = conf.Default()

// col lets us print in colors.
var col = color.New()

type UsageError struct {
	Cmd   string
	Msg   string
	Usage func() error
}

func (e *UsageError) Error() string {
	return fmt.Sprintf("%s", e.Msg)
}

type ExecError struct {
	Err     error
	Output  string
	Command string
}

func (err *ExecError) Error() string { return err.Err.Error() }

// runShellCommand runs the cmd in a shell and returns whether an error occurred.
// If an error is returned, it is of type *ExecError, which contains the field
// `Output` that contains the commands stdout and stderr output.
func runShellCommand(cmd string) error {
	bs, err := exec.Command("sh", "-c", cmd).CombinedOutput()
	if err != nil {
		return &ExecError{
			Err:     err,
			Output:  string(bs),
			Command: cmd,
		}
	}
	return nil
}

var MainCmd = &cobra.Command{
	Use:   "repoctl",
	Short: "manage local Pacman repositories",
	Long: `Repoctl helps manage local Pacman repositories, and acts in particular as
a supplement to the repo-add and repo-remove tools that come with Pacman.

If compiling and installing from AUR every time is not what you want,
or if you want to host your own repository, then repoctl might be for you.

Note that in all of these commands, the following terminology is used:

    pkgname: is the name of the package, e.g. pacman
    pkgfile: is the path to a package file, e.g. pacman-3.5.3-i686.pkg.tar.xz
`,
	PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
		// This function can be overriden if it's not necessary for a command.
		cmd.SilenceErrors = true
		cmd.SilenceUsage = true
		if Conf.Unconfigured {
			return errors.New("repoctl is unconfigured, please create configuration")
		} else if Conf.Repository == "" {
			return conf.ErrRepoUnset
		}
		Repo = Conf.Repo()

		if Conf.PreAction != "" {
			return runShellCommand(Conf.PreAction)
		}
		return nil
	},
	PersistentPostRunE: func(cmd *cobra.Command, args []string) error {
		// If PersistentPreRunE was overridden, then don't execute this step.
		// We can determine this by looking to see if Repo was set.
		if Conf.PostAction != "" && Repo != nil {
			return runShellCommand(Conf.PostAction)
		}
		return nil
	},
}

func addConfFlags(cmd *cobra.Command) {
	cmd.PersistentFlags().BoolVarP(&Conf.Backup, "backup", "b", Conf.Backup, "backup obsolete files instead of deleting")
	cmd.PersistentFlags().StringVarP(&Conf.BackupDir, "backup-dir", "B", Conf.BackupDir, "backup directory relative to repository path")
	cmd.PersistentFlags().BoolVarP(&Conf.Columnate, "columns", "s", Conf.Columnate, "show items in columns rather than lines")
	cmd.PersistentFlags().BoolVarP(&Conf.Quiet, "quiet", "q", Conf.Quiet, "show minimal amount of information")
	cmd.PersistentFlags().BoolVar(&Conf.Debug, "debug", Conf.Debug, "show unnecessary debugging information")
	col.Set(Conf.Color) // set default, which will be auto if Conf.Color is empty or invalid
	cmd.PersistentFlags().Var(col, "color", "when to use color (auto|never|always)")
}

// main loads the configuration and executes the primary command.
func main() {
	err := Conf.MergeAll()
	if err != nil {
		// We didn't manage to load any configuration, which means that repoctl
		// is unconfigured. There are some commands that work nonetheless, so
		// we can't stop now -- which is why we don't os.Exit(1).
		fmt.Fprintf(os.Stderr, "Error: %s\n", err)
	}

	// Arguments from the command line override the configuration file,
	// so we have to add the flags after loading the configuration.
	//
	// TODO: Maybe in the future we will make it possible to specify the
	// configuration file via the command line; right now it is not a priority.
	addConfFlags(MainCmd)

	err = MainCmd.Execute()
	if err != nil {
		// If this is an ExecError, we deal with it specially:
		if e, ok := err.(*ExecError); ok {
			fmt.Fprintf(os.Stderr, "Error: command %q failed: %s\n", e.Command, e.Err)
			fmt.Fprintf(os.Stderr, "Command output:\n%s", e.Output)
			os.Exit(1)
		}

		// All other errors:
		fmt.Fprintf(os.Stderr, "Error: %s\n", err)
		if e, ok := err.(*UsageError); ok {
			e.Usage()
		}
		os.Exit(1)
	}
}
<|endoftext|>


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

import (
	goflag "flag"
	"fmt"
	"regexp"
	"strconv"
	"strings"
	"time"

	"github.com/golang/glog"
	"github.com/miekg/dns"
	"github.com/spf13/pflag"
	"k8s.io/apiserver/pkg/util/flag"
	"k8s.io/kubernetes/pkg/util/logs"

	"k8s.io/dns/pkg/sidecar"
	"k8s.io/dns/pkg/version"
)

const (
	defaultProbeInterval = 5 * time.Second
)

func main() {
	options := sidecar.NewOptions()
	configureFlags(options, pflag.CommandLine)
	flag.InitFlags()
	// Convinces goflags that we have called Parse() to avoid noisy logs.
	// OSS Issue: kubernetes/kubernetes#17162.
	goflag.CommandLine.Parse([]string{})
	logs.InitLogs()
	defer logs.FlushLogs()

	glog.Infof("Version v%s", version.VERSION)

	version.PrintAndExitIfRequested()

	server := sidecar.NewServer()
	server.Run(options)
}

type probeOptions []sidecar.DNSProbeOption

func (po *probeOptions) String() string {
	return fmt.Sprintf("%+v", *po)
}

func (po *probeOptions) Set(value string) error {
	splits := strings.Split(value, ",")
	if !(3 <= len(splits) && len(splits) <= 5) {
		return fmt.Errorf("invalid format to --probe")
	}

	option := sidecar.DNSProbeOption{
		Label:    splits[0],
		Server:   splits[1],
		Name:     splits[2],
		Interval: defaultProbeInterval,
		Type:     dns.TypeANY,
	}

	const labelRegexp = "^[a-zA-Z0-9_]+$"
	if !regexp.MustCompile(labelRegexp).MatchString(option.Label) {
		return fmt.Errorf("label must be of format %v", labelRegexp)
	}

	if !strings.Contains(option.Server, ":") {
		option.Server = option.Server + ":53"
	}

	if !strings.HasSuffix(option.Name, ".") {
		// dns package requires a fully qualified (e.g. terminal '.') name
		option.Name = option.Name + "."
	}

	if len(splits) >= 4 {
		if interval, err := strconv.Atoi(splits[3]); err == nil {
			option.Interval = time.Duration(interval) * time.Second
		} else {
			return err
		}
	}

	if len(splits) >= 5 {
		switch splits[4] {
		case "A":
			option.Type = dns.TypeA
		case "AAAA":
			option.Type = dns.TypeAAAA
		case "ANY":
			option.Type = dns.TypeANY
		case "SRV":
			option.Type = dns.TypeSRV
		default:
			return fmt.Errorf("invalid type for DNS: %v", splits[4])
		}
	}

	*po = append(*po, option)

	return nil
}

func (po *probeOptions) Type() string {
	return "string"
}

var _ pflag.Value = (*probeOptions)(nil)

func configureFlags(opt *sidecar.Options, flagSet *pflag.FlagSet) {
	flagSet.StringVar(
		&opt.DnsMasqAddr, "dnsmasq-addr", opt.DnsMasqAddr,
		"address that the dnsmasq server is listening on")
	flagSet.IntVar(
		&opt.DnsMasqPort, "dnsmasq-port", opt.DnsMasqPort,
		"port that the dnsmasq server is listening on")
	flagSet.IntVar(
		&opt.DnsMasqPollIntervalMs, "dnsmasq-poll-interval-ms", opt.DnsMasqPollIntervalMs,
		"interval with which to poll dnsmasq for stats")
	flagSet.Var(
		(*probeOptions)(&opt.Probes), "probe",
		"probe the given DNS server with the DNS name and export probe"+
			" metrics and healthcheck URI. Specified as"+
			" <label>,<server>,<dns name>[,<interval_seconds>][,<type>]."+
			" Healthcheck url will be exported under /healthcheck/<label>."+
			" interval_seconds is optional."+
			" This option may be specified multiple times to check multiple servers."+
			" <type> is one of ANY, A, AAAA, SRV."+
			" Example: 'mydns,127.0.0.1:53,example.com,10,A'.")
	flagSet.StringVar(
		&opt.PrometheusAddr, "prometheus-addr", opt.PrometheusAddr,
		"http addr to bind metrics server to")
	flagSet.IntVar(
		&opt.PrometheusPort, "prometheus-port", opt.PrometheusPort,
		"http port to use to export prometheus metrics")
	flagSet.StringVar(
		&opt.PrometheusPath, "prometheus-path", opt.PrometheusPath,
		"http path used to export metrics")
	flagSet.StringVar(
		&opt.PrometheusNamespace, "prometheus-namespace", opt.PrometheusNamespace,
		"prometheus metric namespace")
}
<commit_msg>fix parameter description<commit_after>/*
Copyright 2016 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 main

import (
	goflag "flag"
	"fmt"
	"regexp"
	"strconv"
	"strings"
	"time"

	"github.com/golang/glog"
	"github.com/miekg/dns"
	"github.com/spf13/pflag"
	"k8s.io/apiserver/pkg/util/flag"
	"k8s.io/kubernetes/pkg/util/logs"

	"k8s.io/dns/pkg/sidecar"
	"k8s.io/dns/pkg/version"
)

const (
	defaultProbeInterval = 5 * time.Second
)

func main() {
	options := sidecar.NewOptions()
	configureFlags(options, pflag.CommandLine)
	flag.InitFlags()
	// Convinces goflags that we have called Parse() to avoid noisy logs.
	// OSS Issue: kubernetes/kubernetes#17162.
	goflag.CommandLine.Parse([]string{})
	logs.InitLogs()
	defer logs.FlushLogs()

	glog.Infof("Version v%s", version.VERSION)

	version.PrintAndExitIfRequested()

	server := sidecar.NewServer()
	server.Run(options)
}

type probeOptions []sidecar.DNSProbeOption

func (po *probeOptions) String() string {
	return fmt.Sprintf("%+v", *po)
}

func (po *probeOptions) Set(value string) error {
	splits := strings.Split(value, ",")
	if !(3 <= len(splits) && len(splits) <= 5) {
		return fmt.Errorf("invalid format to --probe")
	}

	option := sidecar.DNSProbeOption{
		Label:    splits[0],
		Server:   splits[1],
		Name:     splits[2],
		Interval: defaultProbeInterval,
		Type:     dns.TypeANY,
	}

	const labelRegexp = "^[a-zA-Z0-9_]+$"
	if !regexp.MustCompile(labelRegexp).MatchString(option.Label) {
		return fmt.Errorf("label must be of format %v", labelRegexp)
	}

	if !strings.Contains(option.Server, ":") {
		option.Server = option.Server + ":53"
	}

	if !strings.HasSuffix(option.Name, ".") {
		// dns package requires a fully qualified (e.g. terminal '.') name
		option.Name = option.Name + "."
	}

	if len(splits) >= 4 {
		if interval, err := strconv.Atoi(splits[3]); err == nil {
			option.Interval = time.Duration(interval) * time.Second
		} else {
			return err
		}
	}

	if len(splits) >= 5 {
		switch splits[4] {
		case "A":
			option.Type = dns.TypeA
		case "AAAA":
			option.Type = dns.TypeAAAA
		case "ANY":
			option.Type = dns.TypeANY
		case "SRV":
			option.Type = dns.TypeSRV
		default:
			return fmt.Errorf("invalid type for DNS: %v", splits[4])
		}
	}

	*po = append(*po, option)

	return nil
}

func (po *probeOptions) Type() string {
	return "string"
}

var _ pflag.Value = (*probeOptions)(nil)

func configureFlags(opt *sidecar.Options, flagSet *pflag.FlagSet) {
	flagSet.StringVar(
		&opt.DnsMasqAddr, "dnsmasq-addr", opt.DnsMasqAddr,
		"address that the dnsmasq server is listening on")
	flagSet.IntVar(
		&opt.DnsMasqPort, "dnsmasq-port", opt.DnsMasqPort,
		"port that the dnsmasq server is listening on")
	flagSet.IntVar(
		&opt.DnsMasqPollIntervalMs, "dnsmasq-poll-interval-ms", opt.DnsMasqPollIntervalMs,
		"interval with which to poll dnsmasq for stats")
	flagSet.Var(
		(*probeOptions)(&opt.Probes), "probe",
		"probe the given DNS server with the DNS name and export probe"+
			" metrics and healthcheck URI. Specified as"+
			" <label>,<server>,<dns name>[,<interval_seconds>][,<type>]."+
			" Healthcheck url will be exported under /healthcheck/<label>."+
			" interval_seconds is optional."+
			" This option may be specified multiple times to check multiple servers."+
			" <type> is one of ANY, A, AAAA, SRV."+
			" Example: 'mydns,127.0.0.1:53,example.com,10,A'.")
	flagSet.StringVar(
		&opt.PrometheusAddr, "prometheus-addr", opt.PrometheusAddr,
		"http address to bind metrics server to")
	flagSet.IntVar(
		&opt.PrometheusPort, "prometheus-port", opt.PrometheusPort,
		"http port to use to export prometheus metrics")
	flagSet.StringVar(
		&opt.PrometheusPath, "prometheus-path", opt.PrometheusPath,
		"http path used to export metrics")
	flagSet.StringVar(
		&opt.PrometheusNamespace, "prometheus-namespace", opt.PrometheusNamespace,
		"prometheus metric namespace")
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"
	"os/signal"

	"github.com/coreos/torus"
	"github.com/coreos/torus/block"
	"github.com/coreos/torus/internal/nbd"

	"github.com/spf13/cobra"
)

var (
	nbdCommand = &cobra.Command{
		Use:   "nbd VOLUME [NBD-DEV]",
		Short: "attach a block volume to an NBD device",
		Run:   nbdAction,
	}

	nbdServeCommand = &cobra.Command{
		Use:   "nbdserve",
		Short: "serve a block volume over the NBD protocol",
		Run:   nbdServeAction,
	}

	serveListenAddress string
)

func init() {
	rootCommand.AddCommand(nbdCommand)

	nbdServeCommand.Flags().StringVarP(&serveListenAddress, "listen", "l", "0.0.0.0:10809", "nbd server listen address")
	rootCommand.AddCommand(nbdServeCommand)
}

func nbdAction(cmd *cobra.Command, args []string) {
	if len(args) != 1 && len(args) != 2 {
		cmd.Usage()
		os.Exit(1)
	}

	var knownDev string
	if len(args) == 2 {
		knownDev = args[1]
	}

	srv := createServer()

	signalChan := make(chan os.Signal, 1)
	signal.Notify(signalChan, os.Interrupt)

	closer := make(chan bool)
	go func() {
		for _ = range signalChan {
			fmt.Println("\nReceived an interrupt, disconnecting...")
			close(closer)
		}
	}()
	defer srv.Close()
	blockvol, err := block.OpenBlockVolume(srv, args[0])
	if err != nil {
		fmt.Fprintf(os.Stderr, "server doesn't support block volumes: %s\n", err)
		os.Exit(1)
	}

	f, err := blockvol.OpenBlockFile()
	if err != nil {
		if err == torus.ErrLocked {
			fmt.Fprintf(os.Stderr, "volume %s is already mounted on another host\n", args[0])
		} else {
			fmt.Fprintf(os.Stderr, "can't open block volume: %s\n", err)
		}
		os.Exit(1)
	}
	defer f.Close()
	err = connectNBD(srv, f, knownDev, closer)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%s\n", err)
		os.Exit(1)
	}
}

func connectNBD(srv *torus.Server, f *block.BlockFile, target string, closer chan bool) error {
	defer f.Close()
	size := f.Size()

	gmd, err := srv.MDS.GlobalMetadata()
	if err != nil {
		return err
	}

	handle := nbd.Create(f, int64(size), int64(gmd.BlockSize))

	if target == "" {
		target, err = nbd.FindDevice()
		if err != nil {
			fmt.Println(err)
			return err
		}
	}

	dev, err := handle.OpenDevice(target)
	if err != nil {
		fmt.Println(err)
		return err
	}
	fmt.Println("Connected to", dev)

	go func(n *nbd.NBD) {
		<-closer
		n.Disconnect()
	}(handle)

	err = handle.Serve()
	if err != nil {
		fmt.Fprintf(os.Stderr, "error from nbd server: %s\n", err)
		os.Exit(1)
	}
	return handle.Close()
}

type finder struct {
	srv *torus.Server
}

func (f *finder) FindDevice(name string) (nbd.Device, error) {
	blockvol, err := block.OpenBlockVolume(f.srv, name)
	if err != nil {
		return nil, err
	}

	return blockvol.OpenBlockFile()
}

func (f *finder) ListDevices() ([]string, error) {
	vols, _, err := f.srv.MDS.GetVolumes()
	if err != nil {
		return nil, err
	}

	var volnames []string

	for _, v := range vols {
		volnames = append(volnames, v.Name)
	}

	return volnames, nil
}

func nbdServeAction(cmd *cobra.Command, args []string) {
	if len(args) != 0 {
		cmd.Usage()
		os.Exit(1)
	}

	srv := createServer()
	defer srv.Close()

	signalChan := make(chan os.Signal, 1)
	signal.Notify(signalChan, os.Interrupt)

	devfinder := &finder{srv}
	server, err := nbd.NewNBDServer(serveListenAddress, devfinder)
	if err != nil {
		die("can't start server: %v", err)
	}

	// TODO: sync all conns
	go func() {
		<-signalChan
		server.Close()
		return
	}()

	if err := server.Serve(); err != nil {
		die("server exited: %v", err)
	}
}
<commit_msg>torusblk: tiny: remove duplicated print error<commit_after>package main

import (
	"fmt"
	"os"
	"os/signal"

	"github.com/coreos/torus"
	"github.com/coreos/torus/block"
	"github.com/coreos/torus/internal/nbd"

	"github.com/spf13/cobra"
)

var (
	nbdCommand = &cobra.Command{
		Use:   "nbd VOLUME [NBD-DEV]",
		Short: "attach a block volume to an NBD device",
		Run:   nbdAction,
	}

	nbdServeCommand = &cobra.Command{
		Use:   "nbdserve",
		Short: "serve a block volume over the NBD protocol",
		Run:   nbdServeAction,
	}

	serveListenAddress string
)

func init() {
	rootCommand.AddCommand(nbdCommand)

	nbdServeCommand.Flags().StringVarP(&serveListenAddress, "listen", "l", "0.0.0.0:10809", "nbd server listen address")
	rootCommand.AddCommand(nbdServeCommand)
}

func nbdAction(cmd *cobra.Command, args []string) {
	if len(args) != 1 && len(args) != 2 {
		cmd.Usage()
		os.Exit(1)
	}

	var knownDev string
	if len(args) == 2 {
		knownDev = args[1]
	}

	srv := createServer()

	signalChan := make(chan os.Signal, 1)
	signal.Notify(signalChan, os.Interrupt)

	closer := make(chan bool)
	go func() {
		for _ = range signalChan {
			fmt.Println("\nReceived an interrupt, disconnecting...")
			close(closer)
		}
	}()
	defer srv.Close()
	blockvol, err := block.OpenBlockVolume(srv, args[0])
	if err != nil {
		fmt.Fprintf(os.Stderr, "server doesn't support block volumes: %s\n", err)
		os.Exit(1)
	}

	f, err := blockvol.OpenBlockFile()
	if err != nil {
		if err == torus.ErrLocked {
			fmt.Fprintf(os.Stderr, "volume %s is already mounted on another host\n", args[0])
		} else {
			fmt.Fprintf(os.Stderr, "can't open block volume: %s\n", err)
		}
		os.Exit(1)
	}
	defer f.Close()
	err = connectNBD(srv, f, knownDev, closer)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%s\n", err)
		os.Exit(1)
	}
}

func connectNBD(srv *torus.Server, f *block.BlockFile, target string, closer chan bool) error {
	defer f.Close()
	size := f.Size()

	gmd, err := srv.MDS.GlobalMetadata()
	if err != nil {
		return err
	}

	handle := nbd.Create(f, int64(size), int64(gmd.BlockSize))

	if target == "" {
		target, err = nbd.FindDevice()
		if err != nil {
			return err
		}
	}

	dev, err := handle.OpenDevice(target)
	if err != nil {
		return err
	}
	fmt.Println("Connected to", dev)

	go func(n *nbd.NBD) {
		<-closer
		n.Disconnect()
	}(handle)

	err = handle.Serve()
	if err != nil {
		fmt.Fprintf(os.Stderr, "error from nbd server: %s\n", err)
		os.Exit(1)
	}
	return handle.Close()
}

type finder struct {
	srv *torus.Server
}

func (f *finder) FindDevice(name string) (nbd.Device, error) {
	blockvol, err := block.OpenBlockVolume(f.srv, name)
	if err != nil {
		return nil, err
	}

	return blockvol.OpenBlockFile()
}

func (f *finder) ListDevices() ([]string, error) {
	vols, _, err := f.srv.MDS.GetVolumes()
	if err != nil {
		return nil, err
	}

	var volnames []string

	for _, v := range vols {
		volnames = append(volnames, v.Name)
	}

	return volnames, nil
}

func nbdServeAction(cmd *cobra.Command, args []string) {
	if len(args) != 0 {
		cmd.Usage()
		os.Exit(1)
	}

	srv := createServer()
	defer srv.Close()

	signalChan := make(chan os.Signal, 1)
	signal.Notify(signalChan, os.Interrupt)

	devfinder := &finder{srv}
	server, err := nbd.NewNBDServer(serveListenAddress, devfinder)
	if err != nil {
		die("can't start server: %v", err)
	}

	// TODO: sync all conns
	go func() {
		<-signalChan
		server.Close()
		return
	}()

	if err := server.Serve(); err != nil {
		die("server exited: %v", err)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"bufio"
	"flag"
	"fmt"
	"os"

	"github.com/kechako/zip4win"
	"github.com/pkg/errors"
)

var (
	version  = "1.0"
	revision string
)

// printVersion output a version info.
func printVersion() {
	fmt.Printf("%s %s (%s)\n", os.Args[0], version, revision)
}

// printHelp outputs a help message to STDERR.
func printHelp() {
	fmt.Fprintf(os.Stderr, `Usage: %s [options] zipfile file ...

options:
`, os.Args[0])
	flag.PrintDefaults()
	os.Exit(1)
}

// printError outputs a error message to STDERR.
func printError(err error) {
	fmt.Fprintf(os.Stderr, "Error: %s", err)
	os.Exit(2)
}

// entry point
func main() {
	var nonorm bool
	var includeDSStore bool
	var excludeDotfiles bool
	var useUTC bool
	var printVer bool

	flag.Usage = printHelp
	flag.BoolVar(&nonorm, "nonorm", false, "Disable normalizing a file name with NFC")
	flag.BoolVar(&includeDSStore, "include-dsstore", false, "Include .DSStore in a zip archive.")
	flag.BoolVar(&excludeDotfiles, "exclude-dotfiles", false, "Exclude dotfiles in a zip archive.")
	flag.BoolVar(&useUTC, "utc", false, "Use UTC as mod time. Default use local time.")
	flag.BoolVar(&printVer, "version", false, "Show version info.")

	flag.Parse()

	if printVer {
		printVersion()
		return
	}

	args := flag.Args()
	if len(args) < 2 {
		printHelp()
	}

	zipfile := args[0]
	paths := args[1:]

	fp, err := os.Create(zipfile)
	if err != nil {
		printError(err)
	}
	defer fp.Close()

	w := zip4win.New(fp)
	defer w.Close()

	w.Normalizing = !nonorm
	w.ExcludeDSStore = !includeDSStore
	w.ExcludeDotfiles = excludeDotfiles
	w.UseUTC = useUTC

	if paths[0] == "-" {
		// Input from stdin
		s := bufio.NewScanner(os.Stdin)
		for s.Scan() {
			err = w.WriteEntry(s.Text())
			if err != nil {
				printError(err)
			}
		}
		if err = s.Err(); err != nil {
			printError(errors.Wrap(err, "Could not read from STDIN."))
		}
	} else {
		// Input from parameters
		for _, path := range paths {
			err = w.WriteEntry(path)
			if err != nil {
				printError(err)
			}
		}
	}
}
<commit_msg>Fix help message<commit_after>package main

import (
	"bufio"
	"flag"
	"fmt"
	"os"

	"github.com/kechako/zip4win"
	"github.com/pkg/errors"
)

var (
	version  = "1.0"
	revision string
)

// printVersion output a version info.
func printVersion() {
	fmt.Printf("%s %s (%s)\n", os.Args[0], version, revision)
}

// printHelp outputs a help message to STDERR.
func printHelp() {
	fmt.Fprintf(os.Stderr, `Usage: %s [options] zipfile file ...

options:
`, os.Args[0])
	flag.PrintDefaults()
	os.Exit(1)
}

// printError outputs a error message to STDERR.
func printError(err error) {
	fmt.Fprintf(os.Stderr, "Error: %s", err)
	os.Exit(2)
}

// entry point
func main() {
	var nonorm bool
	var includeDSStore bool
	var excludeDotfiles bool
	var useUTC bool
	var printVer bool

	flag.Usage = printHelp
	flag.BoolVar(&nonorm, "nonorm", false, "Disable normalizing a file name with NFC.")
	flag.BoolVar(&includeDSStore, "include-dsstore", false, "Include .DSStore in a zip archive.")
	flag.BoolVar(&excludeDotfiles, "exclude-dotfiles", false, "Exclude dotfiles in a zip archive.")
	flag.BoolVar(&useUTC, "utc", false, "Use UTC as mod time. Default use local time.")
	flag.BoolVar(&printVer, "version", false, "Show version info.")

	flag.Parse()

	if printVer {
		printVersion()
		return
	}

	args := flag.Args()
	if len(args) < 2 {
		printHelp()
	}

	zipfile := args[0]
	paths := args[1:]

	fp, err := os.Create(zipfile)
	if err != nil {
		printError(err)
	}
	defer fp.Close()

	w := zip4win.New(fp)
	defer w.Close()

	w.Normalizing = !nonorm
	w.ExcludeDSStore = !includeDSStore
	w.ExcludeDotfiles = excludeDotfiles
	w.UseUTC = useUTC

	if paths[0] == "-" {
		// Input from stdin
		s := bufio.NewScanner(os.Stdin)
		for s.Scan() {
			err = w.WriteEntry(s.Text())
			if err != nil {
				printError(err)
			}
		}
		if err = s.Err(); err != nil {
			printError(errors.Wrap(err, "Could not read from STDIN."))
		}
	} else {
		// Input from parameters
		for _, path := range paths {
			err = w.WriteEntry(path)
			if err != nil {
				printError(err)
			}
		}
	}
}
<|endoftext|>


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

package main

import (
	"fmt"
	"io"
	"io/ioutil"
	"math"
	"net"
	"strings"

	"github.com/vishvananda/netlink"
	"golang.org/x/sys/unix"
)

func showLinks(w io.Writer, withAddresses bool) error {
	ifaces, err := netlink.LinkList()
	if err != nil {
		return fmt.Errorf("Can't enumerate interfaces? %v", err)
	}

	for _, v := range ifaces {
		l := v.Attrs()

		fmt.Fprintf(w, "%d: %s: <%s> mtu %d state %s\n", l.Index, l.Name,
			strings.Replace(strings.ToUpper(fmt.Sprintf("%s", l.Flags)), "|", ",", -1),
			l.MTU, strings.ToUpper(l.OperState.String()))

		fmt.Fprintf(w, "    link/%s %s\n", l.EncapType, l.HardwareAddr)

		if withAddresses {
			showLinkAddresses(w, v)
		}
	}
	return nil
}

func showLinkAddresses(w io.Writer, link netlink.Link) error {
	addrs, err := netlink.AddrList(link, netlink.FAMILY_ALL)
	if err != nil {
		return fmt.Errorf("Can't enumerate addresses: %v", err)
	}

	for _, addr := range addrs {

		var inet string
		switch len(addr.IPNet.IP) {
		case 4:
			inet = "inet"
		case 16:
			inet = "inet6"
		default:
			return fmt.Errorf("Can't figure out IP protocol version")
		}

		fmt.Fprintf(w, "    %s %s", inet, addr.IP)
		if addr.Broadcast != nil {
			fmt.Fprintf(w, " brd %s", addr.Broadcast)
		}
		fmt.Fprintf(w, " scope %s %s\n", addrScopes[netlink.Scope(addr.Scope)], addr.Label)

		var validLft, preferredLft string
		// TODO: fix vishnavanda/netlink. *Lft should be uint32, not int.
		if uint32(addr.PreferedLft) == math.MaxUint32 {
			preferredLft = "forever"
		} else {
			preferredLft = fmt.Sprintf("%dsec", addr.PreferedLft)
		}
		if uint32(addr.ValidLft) == math.MaxUint32 {
			validLft = "forever"
		} else {
			validLft = fmt.Sprintf("%dsec", addr.ValidLft)
		}
		fmt.Fprintf(w, "       valid_lft %s preferred_lft %s\n", validLft, preferredLft)
	}
	return nil
}

var neighStates = map[int]string{
	netlink.NUD_NONE:       "NONE",
	netlink.NUD_INCOMPLETE: "INCOMPLETE",
	netlink.NUD_REACHABLE:  "REACHABLE",
	netlink.NUD_STALE:      "STALE",
	netlink.NUD_DELAY:      "DELAY",
	netlink.NUD_PROBE:      "PROBE",
	netlink.NUD_FAILED:     "FAILED",
	netlink.NUD_NOARP:      "NOARP",
	netlink.NUD_PERMANENT:  "PERMANENT",
}

func getState(state int) string {
	ret := make([]string, 0)
	for st, name := range neighStates {
		if state&st != 0 {
			ret = append(ret, name)
		}
	}
	if len(ret) == 0 {
		return "UNKNOWN"
	}
	return strings.Join(ret, ",")
}

func showNeighbours(w io.Writer, withAddresses bool) error {
	ifaces, err := net.Interfaces()
	if err != nil {
		return err
	}
	for _, iface := range ifaces {
		neighs, err := netlink.NeighList(iface.Index, 0)
		if err != nil {
			return fmt.Errorf("Can't list neighbours? %v", err)
		}

		for _, v := range neighs {
			if v.State&netlink.NUD_NOARP != 0 {
				continue
			}
			entry := fmt.Sprintf("%s dev %s", v.IP.String(), iface.Name)
			if v.HardwareAddr != nil {
				entry += fmt.Sprintf(" lladdr %s", v.HardwareAddr)
			}
			if v.Flags&netlink.NTF_ROUTER != 0 {
				entry += " router"
			}
			entry += " " + getState(v.State)
			fmt.Println(entry)
		}
	}
	return nil
}

const (
	defaultFmt = "default via %v dev %s proto %s metric %d\n"
	routeFmt   = "%v dev %s proto %s scope %s src %s metric %d\n"
)

// routing protocol identifier
// specified in Linux Kernel header: include/uapi/linux/rtnetlink.h
// See man IP-ROUTE(8) and RTNETLINK(7)
var rtProto = map[int]string{
	unix.RTPROT_BOOT:   "boot",
	unix.RTPROT_KERNEL: "kernel",
	unix.RTPROT_STATIC: "static",
	unix.RTPROT_DHCP:   "dhcp",
}

func showRoutes(inet6 bool) error {
	var f int
	if inet6 {
		path := "/proc/net/ipv6_route"
		b, err := ioutil.ReadFile(path)
		if err != nil {
			return fmt.Errorf("Route show failed: %v", err)
		}
		log.Printf("%s", string(b))
		return nil
	}
	f = netlink.FAMILY_V4

	routes, err := netlink.RouteList(nil, f)
	if err != nil {
		return err
	}
	for _, route := range routes {
		link, err := netlink.LinkByIndex(route.LinkIndex)
		if err != nil {
			return err
		}
		if route.Gw != nil {
			defaultRoute(route, link)
		} else {
			showRoute(route, link)
		}
	}
	return nil
}

func defaultRoute(r netlink.Route, l netlink.Link) {
	gw := r.Gw
	name := l.Attrs().Name
	proto := rtProto[r.Protocol]
	metric := r.Priority
	fmt.Printf(defaultFmt, gw, name, proto, metric)
}

func showRoute(r netlink.Route, l netlink.Link) {
	dest := r.Dst
	name := l.Attrs().Name
	proto := rtProto[r.Protocol]
	scope := addrScopes[r.Scope]
	src := r.Src
	metric := r.Priority
	fmt.Printf(routeFmt, dest, name, proto, scope, src, metric)
}
<commit_msg>cmd/core/ip: route show IPv6 support<commit_after>// Copyright 2012-2017 the u-root Authors. All rights reserved
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"fmt"
	"io"
	"math"
	"net"
	"strings"

	"github.com/vishvananda/netlink"
	"golang.org/x/sys/unix"
)

func showLinks(w io.Writer, withAddresses bool) error {
	ifaces, err := netlink.LinkList()
	if err != nil {
		return fmt.Errorf("Can't enumerate interfaces? %v", err)
	}

	for _, v := range ifaces {
		l := v.Attrs()

		fmt.Fprintf(w, "%d: %s: <%s> mtu %d state %s\n", l.Index, l.Name,
			strings.Replace(strings.ToUpper(fmt.Sprintf("%s", l.Flags)), "|", ",", -1),
			l.MTU, strings.ToUpper(l.OperState.String()))

		fmt.Fprintf(w, "    link/%s %s\n", l.EncapType, l.HardwareAddr)

		if withAddresses {
			showLinkAddresses(w, v)
		}
	}
	return nil
}

func showLinkAddresses(w io.Writer, link netlink.Link) error {
	addrs, err := netlink.AddrList(link, netlink.FAMILY_ALL)
	if err != nil {
		return fmt.Errorf("Can't enumerate addresses: %v", err)
	}

	for _, addr := range addrs {

		var inet string
		switch len(addr.IPNet.IP) {
		case 4:
			inet = "inet"
		case 16:
			inet = "inet6"
		default:
			return fmt.Errorf("Can't figure out IP protocol version")
		}

		fmt.Fprintf(w, "    %s %s", inet, addr.IP)
		if addr.Broadcast != nil {
			fmt.Fprintf(w, " brd %s", addr.Broadcast)
		}
		fmt.Fprintf(w, " scope %s %s\n", addrScopes[netlink.Scope(addr.Scope)], addr.Label)

		var validLft, preferredLft string
		// TODO: fix vishnavanda/netlink. *Lft should be uint32, not int.
		if uint32(addr.PreferedLft) == math.MaxUint32 {
			preferredLft = "forever"
		} else {
			preferredLft = fmt.Sprintf("%dsec", addr.PreferedLft)
		}
		if uint32(addr.ValidLft) == math.MaxUint32 {
			validLft = "forever"
		} else {
			validLft = fmt.Sprintf("%dsec", addr.ValidLft)
		}
		fmt.Fprintf(w, "       valid_lft %s preferred_lft %s\n", validLft, preferredLft)
	}
	return nil
}

var neighStates = map[int]string{
	netlink.NUD_NONE:       "NONE",
	netlink.NUD_INCOMPLETE: "INCOMPLETE",
	netlink.NUD_REACHABLE:  "REACHABLE",
	netlink.NUD_STALE:      "STALE",
	netlink.NUD_DELAY:      "DELAY",
	netlink.NUD_PROBE:      "PROBE",
	netlink.NUD_FAILED:     "FAILED",
	netlink.NUD_NOARP:      "NOARP",
	netlink.NUD_PERMANENT:  "PERMANENT",
}

func getState(state int) string {
	ret := make([]string, 0)
	for st, name := range neighStates {
		if state&st != 0 {
			ret = append(ret, name)
		}
	}
	if len(ret) == 0 {
		return "UNKNOWN"
	}
	return strings.Join(ret, ",")
}

func showNeighbours(w io.Writer, withAddresses bool) error {
	ifaces, err := net.Interfaces()
	if err != nil {
		return err
	}
	for _, iface := range ifaces {
		neighs, err := netlink.NeighList(iface.Index, 0)
		if err != nil {
			return fmt.Errorf("Can't list neighbours? %v", err)
		}

		for _, v := range neighs {
			if v.State&netlink.NUD_NOARP != 0 {
				continue
			}
			entry := fmt.Sprintf("%s dev %s", v.IP.String(), iface.Name)
			if v.HardwareAddr != nil {
				entry += fmt.Sprintf(" lladdr %s", v.HardwareAddr)
			}
			if v.Flags&netlink.NTF_ROUTER != 0 {
				entry += " router"
			}
			entry += " " + getState(v.State)
			fmt.Println(entry)
		}
	}
	return nil
}

const (
	defaultFmt   = "default via %v dev %s proto %s metric %d\n"
	routeFmt     = "%v dev %s proto %s scope %s src %s metric %d\n"
	route6Fmt    = "%s dev %s proto %s metric %d\n"
	routeVia6Fmt = "%s via %s dev %s proto %s metric %d\n"
)

// routing protocol identifier
// specified in Linux Kernel header: include/uapi/linux/rtnetlink.h
// See man IP-ROUTE(8) and RTNETLINK(7)
var rtProto = map[int]string{
	unix.RTPROT_BABEL:    "babel",
	unix.RTPROT_BGP:      "bgp",
	unix.RTPROT_BIRD:     "bird",
	unix.RTPROT_BOOT:     "boot",
	unix.RTPROT_DHCP:     "dhcp",
	unix.RTPROT_DNROUTED: "dnrouted",
	unix.RTPROT_EIGRP:    "eigrp",
	unix.RTPROT_GATED:    "gated",
	unix.RTPROT_ISIS:     "isis",
	unix.RTPROT_KERNEL:   "kernel",
	unix.RTPROT_MROUTED:  "mrouted",
	unix.RTPROT_MRT:      "mrt",
	unix.RTPROT_NTK:      "ntk",
	unix.RTPROT_OSPF:     "ospf",
	unix.RTPROT_RA:       "ra",
	unix.RTPROT_REDIRECT: "redirect",
	unix.RTPROT_RIP:      "rip",
	unix.RTPROT_STATIC:   "static",
	unix.RTPROT_UNSPEC:   "unspec",
	unix.RTPROT_XORP:     "xorp",
	unix.RTPROT_ZEBRA:    "zebra",
}

func showRoutes(inet6 bool) error {
	var f int
	if inet6 {
		f = netlink.FAMILY_V6
	} else {
		f = netlink.FAMILY_V4
	}

	routes, err := netlink.RouteList(nil, f)
	if err != nil {
		return err
	}
	for _, route := range routes {
		link, err := netlink.LinkByIndex(route.LinkIndex)
		if err != nil {
			return err
		}
		if route.Dst == nil {
			defaultRoute(route, link)
		} else {
			showRoute(route, link, f)
		}
	}
	return nil
}

func defaultRoute(r netlink.Route, l netlink.Link) {
	gw := r.Gw
	name := l.Attrs().Name
	proto := rtProto[r.Protocol]
	metric := r.Priority
	fmt.Printf(defaultFmt, gw, name, proto, metric)
}

func showRoute(r netlink.Route, l netlink.Link, f int) {
	dest := r.Dst
	name := l.Attrs().Name
	proto := rtProto[r.Protocol]
	metric := r.Priority
	switch f {
	case netlink.FAMILY_V4:
		scope := addrScopes[r.Scope]
		src := r.Src
		fmt.Printf(routeFmt, dest, name, proto, scope, src, metric)
	case netlink.FAMILY_V6:
		if r.Gw != nil {
			gw := r.Gw
			fmt.Printf(routeVia6Fmt, dest, gw, name, proto, metric)
		} else {
			fmt.Printf(route6Fmt, dest, name, proto, metric)
		}
	}
}
<|endoftext|>


<commit_before>package task

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

	"github.com/spf13/cobra"
	"github.com/taskcluster/slugid-go/slugid"
	"github.com/taskcluster/taskcluster-cli/config"
	tcclient "github.com/taskcluster/taskcluster-client-go"
	"github.com/taskcluster/taskcluster-client-go/queue"
)

var (
	createCmd = &cobra.Command{
		Use:     "create <image> <command>",
		Short:   "Creates and schedules a task, using the specified taskId if given.",
		PreRunE: checkCreateFlags,
		RunE:    runCreateTask,
	}

	now = time.Now().UTC()

	createPayload = &queue.TaskDefinitionRequest{
		SchedulerID: "taskcluster-cli",

		Created:  tcclient.Time(now),
		Deadline: tcclient.Time(now.Add(24 * time.Hour)),
		Expires:  tcclient.Time(now.Add(24*time.Hour).AddDate(1, 0, 0)),
	}
)

func init() {
	fs := createCmd.Flags()

	fs.String("task-id", "", "taskID of the task, if omitted, a new one will be assigned")
	fs.StringVar(&createPayload.ProvisionerID, "provisioner", "", "ID of the provisioner to use")
	fs.StringVar(&createPayload.WorkerType, "worker-type", "", "worker-type to use within the provisioner")
	fs.StringSliceP("env", "e", []string{}, "Environment variable to add to the task's environment (repeatable) (format: VARIABLE=VALUE)")
	fs.StringVar(&createPayload.Metadata.Name, "name", "", "Human readable name of the task")
	fs.StringVar(&createPayload.Metadata.Description, "description", "", "Human readable description of the task")
	fs.StringVar(&createPayload.Metadata.Owner, "owner", "", "Email of the task's owner")
	fs.StringVar(&createPayload.Metadata.Source, "source", "", "URL pointing to the source of the task")
	fs.StringSliceVar(&createPayload.Dependencies, "dependency", []string{}, "TaskID of a dependency (repeatable)")
	fs.IntVar(&createPayload.Retries, "retries", 5, "Number of retries due to infrastructure issues")

	for _, f := range []string{"provisioner", "worker-type"} {
		createCmd.MarkFlagRequired(f)
	}

	Command.AddCommand(createCmd)
}

func checkCreateFlags(cmd *cobra.Command, args []string) error {
	for _, f := range []string{"provisioner", "worker-type"} {
		if !cmd.Flag(f).Changed {
			return fmt.Errorf("flag '%s' is required", f)
		}
	}
	return nil
}

func runCreateTask(cmd *cobra.Command, args []string) error {
	if len(args) < 2 {
		return errors.New("create requires at least 2 arguments: image and command")
	}

	var creds *tcclient.Credentials
	if config.Credentials != nil {
		creds = config.Credentials.ToClientCredentials()
	}

	var taskID string
	if s := stringFlagHelper(cmd.Flags(), "task-id"); s != "" {
		if slugid.Decode(s) != nil {
			taskID = s
		} else {
			return fmt.Errorf("task id '%s' is not a valid slugid", s)
		}
	} else {
		taskID = slugid.V4()
	}
	createPayload.TaskGroupID = taskID

	env := make(map[string]string)
	envs, err := cmd.Flags().GetStringSlice("env")
	if err != nil {
		return err
	}
	for _, e := range envs {
		p := strings.SplitN(e, "=", 2)
		switch len(p) {
		case 2:
			env[p[0]] = p[1]
		case 1:
			env[p[0]] = ""
		default:
			return fmt.Errorf("invalid environment option: %s", e)
		}
	}

	createPayload.Payload, err = json.Marshal(struct {
		Image       string            `json:"image"`
		Command     []string          `json:"command"`
		Environment map[string]string `json:"env"`
		MaxRunTime  int               `json:"maxRunTime"`
	}{
		Image:       args[0],
		Command:     args[1:],
		Environment: env,
		MaxRunTime:  7200, // 2 hours
	})
	if err != nil {
		return fmt.Errorf("could not marshal execution payload: %v", err)
	}

	if createPayload.Metadata.Source == "" {
		createPayload.Metadata.Source = "http://taskcluster-cli/task/create"
	}

	tags := make(map[string]string)
	tags["misc_info"] = "created by taskcluster-cli"
	createPayload.Tags, err = json.Marshal(tags)
	if err != nil {
		return fmt.Errorf("could not marshal tags: %v", err)
	}

	q := queue.New(creds)
	resp, err := q.CreateTask(taskID, createPayload)
	if err != nil {
		return fmt.Errorf("could not create task: %v", err)
	}

	// If we got no error, that means the task was successfully created
	fmt.Fprintf(cmd.OutOrStdout(), "Task %s created\n", resp.Status.TaskID)

	return nil
}
<commit_msg>Added comments to the task creation<commit_after>package task

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

	"github.com/spf13/cobra"
	"github.com/taskcluster/slugid-go/slugid"
	"github.com/taskcluster/taskcluster-cli/config"
	tcclient "github.com/taskcluster/taskcluster-client-go"
	"github.com/taskcluster/taskcluster-client-go/queue"
)

var (
	createCmd = &cobra.Command{
		Use:     "create <image> <command>",
		Short:   "Creates and schedules a task, using the specified taskId if given.",
		PreRunE: checkCreateFlags,
		RunE:    runCreateTask,
	}

	now = time.Now().UTC()

	createPayload = &queue.TaskDefinitionRequest{
		SchedulerID: "taskcluster-cli",

		Created:  tcclient.Time(now),
		Deadline: tcclient.Time(now.Add(24 * time.Hour)),
		Expires:  tcclient.Time(now.Add(24*time.Hour).AddDate(1, 0, 0)),
	}
)

func init() {
	fs := createCmd.Flags()

	fs.String("task-id", "", "taskID of the task, if omitted, a new one will be assigned")
	fs.StringVar(&createPayload.ProvisionerID, "provisioner", "", "ID of the provisioner to use")
	fs.StringVar(&createPayload.WorkerType, "worker-type", "", "worker-type to use within the provisioner")
	fs.StringSliceP("env", "e", []string{}, "Environment variable to add to the task's environment (repeatable) (format: VARIABLE=VALUE)")
	fs.StringVar(&createPayload.Metadata.Name, "name", "", "Human readable name of the task")
	fs.StringVar(&createPayload.Metadata.Description, "description", "", "Human readable description of the task")
	fs.StringVar(&createPayload.Metadata.Owner, "owner", "", "Email of the task's owner")
	fs.StringVar(&createPayload.Metadata.Source, "source", "", "URL pointing to the source of the task")
	fs.StringSliceVar(&createPayload.Dependencies, "dependency", []string{}, "TaskID of a dependency (repeatable)")
	fs.IntVar(&createPayload.Retries, "retries", 5, "Number of retries due to infrastructure issues")

	for _, f := range []string{"provisioner", "worker-type"} {
		createCmd.MarkFlagRequired(f)
	}

	Command.AddCommand(createCmd)
}

// checkCreateFlags checks that the required flags were specified.
func checkCreateFlags(cmd *cobra.Command, args []string) error {
	for _, f := range []string{"provisioner", "worker-type"} {
		if !cmd.Flag(f).Changed {
			return fmt.Errorf("flag '%s' is required", f)
		}
	}
	return nil
}

// runCreateTask takes the task creation payload and creates the task.
func runCreateTask(cmd *cobra.Command, args []string) error {
	if len(args) < 2 {
		return errors.New("create requires at least 2 arguments: image and command")
	}

	var creds *tcclient.Credentials
	if config.Credentials != nil {
		creds = config.Credentials.ToClientCredentials()
	}

	// Either generates a new taskID or uses the one provided on the CLI.
	var taskID string
	if s := stringFlagHelper(cmd.Flags(), "task-id"); s != "" {
		if slugid.Decode(s) != nil {
			taskID = s
		} else {
			return fmt.Errorf("task id '%s' is not a valid slugid", s)
		}
	} else {
		taskID = slugid.V4()
	}
	createPayload.TaskGroupID = taskID

	// Build the environment variables.
	env := make(map[string]string)
	envs, err := cmd.Flags().GetStringSlice("env")
	if err != nil {
		return err
	}
	for _, e := range envs {
		p := strings.SplitN(e, "=", 2)
		switch len(p) {
		case 2:
			env[p[0]] = p[1]
		case 1:
			env[p[0]] = ""
		default:
			return fmt.Errorf("invalid environment option: %s", e)
		}
	}

	// Build the task payload.
	createPayload.Payload, err = json.Marshal(struct {
		Image       string            `json:"image"`
		Command     []string          `json:"command"`
		Environment map[string]string `json:"env"`
		MaxRunTime  int               `json:"maxRunTime"`
	}{
		Image:       args[0],
		Command:     args[1:],
		Environment: env,
		MaxRunTime:  7200, // 2 hours
	})
	if err != nil {
		return fmt.Errorf("could not marshal execution payload: %v", err)
	}

	// Arbitrary URL to match the metadata spec.
	if createPayload.Metadata.Source == "" {
		createPayload.Metadata.Source = "http://taskcluster-cli/task/create"
	}

	// Adds a tag to indicate that this task was built through tccli.
	tags := make(map[string]string)
	tags["misc_info"] = "created by taskcluster-cli"
	createPayload.Tags, err = json.Marshal(tags)
	if err != nil {
		return fmt.Errorf("could not marshal tags: %v", err)
	}

	q := queue.New(creds)
	resp, err := q.CreateTask(taskID, createPayload)
	if err != nil {
		return fmt.Errorf("could not create task: %v", err)
	}

	// If we got no error, that means the task was successfully created
	fmt.Fprintf(cmd.OutOrStdout(), "Task %s created\n", resp.Status.TaskID)

	return nil
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"time"
)

var (
	tczPackages = []string{
		"aterm",
		"bash",
		"fltk-1.3",
		"flwm",
		"freetype",
		"glib2",
		"harfbuzz",
		"imlib2-bin",
		"imlib2",
		"libffi",
		"libfontenc",
		"libICE",
		"libjpeg-turbo",
		"libpng",
		"libSM",
		"libX11",
		"libXau",
		"libxcb",
		"libXdmcp",
		"libXext",
		"libXfont",
		"libXi",
		"libXmu",
		"libXpm",
		"libXrandr",
		"libXrender",
		"libXt",
		"pcre",
		"wbar",
		"Xfbdev",
		"Xlibs",
		"Xorg-fonts",
		"Xprogs",
		"Xorg-7.7",
		"links",
		"opera-12",
	}
	sshdCommands = []string{
		"Protocol 2",
		"AcceptEnv LANG LC_*",
		"UsePAM no",
		"ChallengeResponseAuthentication no",
		"passwordauthentication no",
		"AuthorizedKeysFile ~/.ssh/authorized_keys",
		"PermitRootLogin without-password",
		"X11Forwarding yes",
		"RSAAuthentication yes",
		"PubkeyAuthentication yes",
		"X11DisplayOffset 10",
		"X11UseLocalhost yes",
	}
	ssh = flag.Bool("ssh", false, "Ssh default set to false")
)

func setup() error {
	var errors error
	if err := os.Symlink("/usr/local/bin/bash", "/bin/bash"); err != nil {
		errors = fmt.Errorf("bash symlink: %v", err)
	}
	if err := os.Symlink("/lib/ld-linux-x86-64.so.2", "/lib64/ld-linux-x86-64.so.2"); err != nil {
		errors = fmt.Errorf("%v. ld-linux symlink: %v", errors, err)
	}
	return errors
}

func sshSetup() error {
	sshdLoc := "/etc/ssh/sshd_config"
	cmd := exec.Command("tcz", "openssh")
	cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
	if err := cmd.Run(); err != nil {
		return err
	}
	//This block of code does cp /etc/ssh/sshd_config /etc/ssh/sshd_config_backup
	if _, err := os.Stat(sshdLoc); err != nil {
		return err
	}
	fileContent, err := ioutil.ReadFile(sshdLoc)
	if err != nil {
		return err
	}
	if err := ioutil.WriteFile(sshdLoc+"_backup", fileContent, 0777); err != nil {
		return nil
	}
	// This writes the new sshd file
	var buffer bytes.Buffer
	byteFile := []byte{}
	for arg := range sshdCommands {
		buffer.WriteString(fmt.Sprintf("%v\n", arg))
	}
	fmt.Printf("SSHD file is : %s", string(byteFile))
	if err := ioutil.WriteFile(sshdLoc, byteFile, 0777); err != nil {
		return nil
	}

	if err := ioutil.WriteFile("/etc/passwd", []byte("root:x:0:0:root:/root:/bin/bash\nnobody::27:27:nobody privsep:/var/empty:/sbin/nologin"), 0777); err != nil {
		return err
	}
	if err := ioutil.WriteFile("/etc/group", []byte("nobody::27:"), 0777); err != nil {
		return err
	}

	//this does scp yourname@iplink:~/.ssh/id_rsa.pub /root/.ssh
	locationKeys := "yourname@iplink:~/.ssh/id_rsa.pub"
	for true {
		fmt.Printf("Where are your public keys located? ex:%s They will be copied to /root/.ssh and be called id_rsa.pub. \n", locationKeys)
		_, err := fmt.Scanf("%s", &locationKeys)
		if err != nil {
			return err
		}
		cmd := exec.Command("scp", locationKeys, "/root/.ssh/id_rsa.pub")
		cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
		if err := cmd.Run(); err != nil {
			fmt.Printf("tried to scp your public key. Failed because error: %v", err)
		}
		break
	}
	//this does cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys
	rsaKey, err := ioutil.ReadFile("/root/.ssh/id_rsa.pub")
	if err != nil {
		return err
	}
	ioutil.WriteFile("/root/.ssh/authorized_keys", rsaKey, os.ModeAppend)

	cmd = exec.Command("usr/sbin/sshd", "-d", "-d", "-d", "-D", "-e")
	cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
	if err := cmd.Run(); err != nil {
		return err
	}
	return nil
}

func tczSetup() error {
	get := []string{"-v", "8.x"}
	get = append(get, tczPackages...)
	cmd := exec.Command("tcz", get...)
	cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
	if err := cmd.Run(); err != nil {
		return err
	}
	return nil
}

func xSetup() error {
	go func() {
		cmd := exec.Command("Xfbdev")
		cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
		if err := cmd.Run(); err != nil {
			log.Fatalf("X11 startup: %v", err)
		}
	}()
	time.Sleep(5 * time.Second)
	for _, f := range []string{"flwm", "opera-12"} {
		log.Printf("Run %v", f)
		go func() {
			cmd := exec.Command(f, "-display", ":0")
			cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
			if err := cmd.Run(); err != nil {
				log.Printf("%v: %v", f, err)
			}
		}()
	}
	cmd := exec.Command("aterm", "-display", ":0")
	cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
	if err := cmd.Run(); err != nil {
		return err
	}
	return nil
}

func main() {
	if err := setup(); err != nil {
		log.Printf("Error is %v", err)
	}
	if err := tczSetup(); err != nil {
		log.Printf("Error is %v", err)
	}
	if false {
		if err := sshSetup(); err != nil {
			log.Printf("Error is %v", err)
		}
	}
	if err := xSetup(); err != nil {
		log.Printf("Error is %v", err)
	}
}
<commit_msg>Fix something lint just found.<commit_after>package main

import (
	"bytes"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"time"
)

var (
	tczPackages = []string{
		"aterm",
		"bash",
		"fltk-1.3",
		"flwm",
		"freetype",
		"glib2",
		"harfbuzz",
		"imlib2-bin",
		"imlib2",
		"libffi",
		"libfontenc",
		"libICE",
		"libjpeg-turbo",
		"libpng",
		"libSM",
		"libX11",
		"libXau",
		"libxcb",
		"libXdmcp",
		"libXext",
		"libXfont",
		"libXi",
		"libXmu",
		"libXpm",
		"libXrandr",
		"libXrender",
		"libXt",
		"pcre",
		"wbar",
		"Xfbdev",
		"Xlibs",
		"Xorg-fonts",
		"Xprogs",
		"Xorg-7.7",
		"links",
		"opera-12",
	}
	sshdCommands = []string{
		"Protocol 2",
		"AcceptEnv LANG LC_*",
		"UsePAM no",
		"ChallengeResponseAuthentication no",
		"passwordauthentication no",
		"AuthorizedKeysFile ~/.ssh/authorized_keys",
		"PermitRootLogin without-password",
		"X11Forwarding yes",
		"RSAAuthentication yes",
		"PubkeyAuthentication yes",
		"X11DisplayOffset 10",
		"X11UseLocalhost yes",
	}
	ssh = flag.Bool("ssh", false, "Ssh default set to false")
)

func setup() error {
	var errors error
	if err := os.Symlink("/usr/local/bin/bash", "/bin/bash"); err != nil {
		errors = fmt.Errorf("bash symlink: %v", err)
	}
	if err := os.Symlink("/lib/ld-linux-x86-64.so.2", "/lib64/ld-linux-x86-64.so.2"); err != nil {
		errors = fmt.Errorf("%v. ld-linux symlink: %v", errors, err)
	}
	return errors
}

func sshSetup() error {
	sshdLoc := "/etc/ssh/sshd_config"
	cmd := exec.Command("tcz", "openssh")
	cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
	if err := cmd.Run(); err != nil {
		return err
	}
	//This block of code does cp /etc/ssh/sshd_config /etc/ssh/sshd_config_backup
	if _, err := os.Stat(sshdLoc); err != nil {
		return err
	}
	fileContent, err := ioutil.ReadFile(sshdLoc)
	if err != nil {
		return err
	}
	if err := ioutil.WriteFile(sshdLoc+"_backup", fileContent, 0777); err != nil {
		return nil
	}
	// This writes the new sshd file
	var buffer bytes.Buffer
	byteFile := []byte{}
	for arg := range sshdCommands {
		buffer.WriteString(fmt.Sprintf("%v\n", arg))
	}
	fmt.Printf("SSHD file is : %s", string(byteFile))
	if err := ioutil.WriteFile(sshdLoc, byteFile, 0777); err != nil {
		return nil
	}

	if err := ioutil.WriteFile("/etc/passwd", []byte("root:x:0:0:root:/root:/bin/bash\nnobody::27:27:nobody privsep:/var/empty:/sbin/nologin"), 0777); err != nil {
		return err
	}
	if err := ioutil.WriteFile("/etc/group", []byte("nobody::27:"), 0777); err != nil {
		return err
	}

	//this does scp yourname@iplink:~/.ssh/id_rsa.pub /root/.ssh
	locationKeys := "yourname@iplink:~/.ssh/id_rsa.pub"
	for true {
		fmt.Printf("Where are your public keys located? ex:%s They will be copied to /root/.ssh and be called id_rsa.pub. \n", locationKeys)
		_, err := fmt.Scanf("%s", &locationKeys)
		if err != nil {
			return err
		}
		cmd := exec.Command("scp", locationKeys, "/root/.ssh/id_rsa.pub")
		cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
		if err := cmd.Run(); err != nil {
			fmt.Printf("tried to scp your public key. Failed because error: %v", err)
		}
		break
	}
	//this does cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys
	rsaKey, err := ioutil.ReadFile("/root/.ssh/id_rsa.pub")
	if err != nil {
		return err
	}
	ioutil.WriteFile("/root/.ssh/authorized_keys", rsaKey, os.ModeAppend)

	cmd = exec.Command("usr/sbin/sshd", "-d", "-d", "-d", "-D", "-e")
	cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
	if err := cmd.Run(); err != nil {
		return err
	}
	return nil
}

func tczSetup() error {
	get := []string{"-v", "8.x"}
	get = append(get, tczPackages...)
	cmd := exec.Command("tcz", get...)
	cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
	if err := cmd.Run(); err != nil {
		return err
	}
	return nil
}

func xSetup() error {
	go func() {
		cmd := exec.Command("Xfbdev")
		cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
		if err := cmd.Run(); err != nil {
			log.Fatalf("X11 startup: %v", err)
		}
	}()
	time.Sleep(5 * time.Second)
	for _, f := range []string{"flwm", "opera-12"} {
		log.Printf("Run %v", f)
		go func(n string) {
			cmd := exec.Command(n, "-display", ":0")
			cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
			if err := cmd.Run(); err != nil {
				log.Printf("%v: %v", n, err)
			}
		}(f)
	}
	cmd := exec.Command("aterm", "-display", ":0")
	cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
	if err := cmd.Run(); err != nil {
		return err
	}
	return nil
}

func main() {
	if err := setup(); err != nil {
		log.Printf("Error is %v", err)
	}
	if err := tczSetup(); err != nil {
		log.Printf("Error is %v", err)
	}
	if false {
		if err := sshSetup(); err != nil {
			log.Printf("Error is %v", err)
		}
	}
	if err := xSetup(); err != nil {
		log.Printf("Error is %v", err)
	}
}
<|endoftext|>


<commit_before>package gobls

import (
	"bufio"
	"bytes"
	"testing"
)

const (
	lineCount          = 100
	shortLineLength    = 100
	avgLineLength      = 1024
	longLineLength     = 4096 - 2
	veryLongLineLength = bufio.MaxScanTokenSize - 2
)

func makeBuffer(lineCount, lineLength int) *bytes.Buffer {
	buf := make([]byte, 0, lineCount*(lineLength+2))
	bb := bytes.NewBuffer(buf)
	for line := 0; line < lineCount; line++ {
		for i := 0; i < lineLength; i++ {
			bb.WriteByte('a')
		}
		bb.WriteString("\r\n")
	}
	return bb
}

func TestNoEOF(t *testing.T) {
	bb := bytes.NewBufferString("")
	s := NewScanner(bb)
	for s.Scan() {
		t.Errorf("Actual: scan returned true; Expected: false")
	}
	if s.Err() != nil {
		t.Errorf("Actual: %#v; Expected: %#v", s.Err(), nil)
	}
}

func TestSequencesThroughEntireBuffer(t *testing.T) {
	bb := bytes.NewBufferString("flubber\nblubber\nfoo")
	s := NewScanner(bb)
	expectedLines := []string{"flubber", "blubber", "foo"}
	actualLines := make([]string, 0)
	for s.Scan() {
		actualLines = append(actualLines, s.String())
	}
	if s.Err() != nil {
		t.Errorf("Actual: %#v; Expected: %#v", s.Err(), nil)
	}
	if len(actualLines) != len(expectedLines) {
		t.Fatalf("Actual: %#v; Expected: %#v", len(actualLines), len(expectedLines))
	}
	for i := 0; i < len(expectedLines); i++ {
		if actualLines[i] != expectedLines[i] {
			t.Errorf("Actual: %#v; Expected: %#v",
				actualLines[i], expectedLines[i])
		}
	}
}

func TestLongLinesRequireSingleInvocation(t *testing.T) {
	r := makeBuffer(1, longLineLength)
	line := r.String()
	line = line[:len(line)-2] // trim CRLF

	s := NewScanner(r)
	lines := make([]string, 0, 1)
	for s.Scan() {
		lines = append(lines, s.String())
	}
	if s.Err() != nil {
		t.Errorf("Actual: %#v; Expected: %#v", s.Err(), nil)
	}
	if len(lines) != 1 {
		t.Fatalf("Actual: %#v; Expected: %#v", len(lines), 1)
	}
	if lines[0] != line {
		t.Errorf("Actual: %#v; Expected: %#v", lines[0], line)
	}
}

func TestVeryLongLinesRequireSingleInvocation(t *testing.T) {
	r := makeBuffer(1, bufio.MaxScanTokenSize+5)
	line := r.String()
	line = line[:len(line)-2] // trim CRLF

	s := NewScanner(r)
	lines := make([]string, 0, 1)
	for s.Scan() {
		lines = append(lines, s.String())
	}
	if s.Err() != nil {
		t.Errorf("Actual: %#v; Expected: %#v", s.Err(), nil)
	}
	if len(lines) != 1 {
		t.Fatalf("Actual: %#v; Expected: %#v", len(lines), 1)
	}
	if lines[0] != line {
		t.Errorf("Actual: %#v; Expected: %#v", lines[0], line)
	}
}

type simpleScanner interface {
	Err() error
	Scan() bool
	Bytes() []byte
}

func benchmarkScanner(b *testing.B, lineLength int, makeScanner func(*bytes.Buffer) simpleScanner) {
	master := makeBuffer(lineCount, lineLength)
	initial := master.Bytes()
	var line []byte
	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		s := makeScanner(bytes.NewBuffer(initial))
		for s.Scan() {
			line = s.Bytes()
		}
		if s.Err() != nil {
			b.Fatal("Actual: %#v; Expected: %#v", s.Err(), nil)
		}
	}
	if len(line) != lineLength {
		b.Errorf("Actual: %#v; Expected: %#v", len(line), lineLength)
	}
}

func BenchmarkBufioScannerAverage(b *testing.B) {
	makeScanner := func(bb *bytes.Buffer) simpleScanner {
		return bufio.NewScanner(bb)
	}
	benchmarkScanner(b, avgLineLength, makeScanner)
}

func BenchmarkGoblsScannerAverage(b *testing.B) {
	makeScanner := func(bb *bytes.Buffer) simpleScanner {
		return NewScanner(bb)
	}
	benchmarkScanner(b, avgLineLength, makeScanner)
}

func BenchmarkBufioScannerShort(b *testing.B) {
	makeScanner := func(bb *bytes.Buffer) simpleScanner {
		return bufio.NewScanner(bb)
	}
	benchmarkScanner(b, shortLineLength, makeScanner)
}

func BenchmarkGoblsScannerShort(b *testing.B) {
	makeScanner := func(bb *bytes.Buffer) simpleScanner {
		return NewScanner(bb)
	}
	benchmarkScanner(b, shortLineLength, makeScanner)
}

func BenchmarkBufioScannerLong(b *testing.B) {
	makeScanner := func(bb *bytes.Buffer) simpleScanner {
		return bufio.NewScanner(bb)
	}
	benchmarkScanner(b, longLineLength, makeScanner)
}

func BenchmarkGoblsScannerLong(b *testing.B) {
	makeScanner := func(bb *bytes.Buffer) simpleScanner {
		return NewScanner(bb)
	}
	benchmarkScanner(b, longLineLength, makeScanner)
}

func BenchmarkBufioScannerVeryLong(b *testing.B) {
	makeScanner := func(bb *bytes.Buffer) simpleScanner {
		return bufio.NewScanner(bb)
	}
	benchmarkScanner(b, veryLongLineLength, makeScanner)
}

func BenchmarkGoblsScannerVeryLong(b *testing.B) {
	makeScanner := func(bb *bytes.Buffer) simpleScanner {
		return NewScanner(bb)
	}
	benchmarkScanner(b, veryLongLineLength, makeScanner)
}

func BenchmarkGoblsScannerVeryLongEx(b *testing.B) {
	makeScanner := func(bb *bytes.Buffer) simpleScanner {
		return NewScannerSize(bb, bufio.MaxScanTokenSize)
	}
	benchmarkScanner(b, veryLongLineLength, makeScanner)
}
<commit_msg>benchmarks only test speed of Scan() rather than NewScanner()<commit_after>package gobls

import (
	"bufio"
	"bytes"
	"testing"
)

const (
	lineCount          = 1000
	shortLineLength    = 100
	avgLineLength      = 1024
	longLineLength     = 4096 - 2
	veryLongLineLength = bufio.MaxScanTokenSize - 2
)

func makeBytes(lineCount, lineLength int) []byte {
	buf := make([]byte, 0, lineCount*(lineLength+2))
	for line := 0; line < lineCount; line++ {
		for i := 0; i < lineLength; i++ {
			buf = append(buf, 'a')
		}
		buf = append(buf, '\r', '\n')
	}
	return buf
}

func TestNoEOF(t *testing.T) {
	bb := bytes.NewBufferString("")
	s := NewScanner(bb)
	for s.Scan() {
		t.Errorf("Actual: scan returned true; Expected: false")
	}
	if s.Err() != nil {
		t.Errorf("Actual: %#v; Expected: %#v", s.Err(), nil)
	}
}

func TestSequencesThroughEntireBuffer(t *testing.T) {
	bb := bytes.NewBufferString("flubber\nblubber\nfoo")
	s := NewScanner(bb)
	expectedLines := []string{"flubber", "blubber", "foo"}
	actualLines := make([]string, 0)
	for s.Scan() {
		actualLines = append(actualLines, s.String())
	}
	if s.Err() != nil {
		t.Errorf("Actual: %#v; Expected: %#v", s.Err(), nil)
	}
	if len(actualLines) != len(expectedLines) {
		t.Fatalf("Actual: %#v; Expected: %#v", len(actualLines), len(expectedLines))
	}
	for i := 0; i < len(expectedLines); i++ {
		if actualLines[i] != expectedLines[i] {
			t.Errorf("Actual: %#v; Expected: %#v",
				actualLines[i], expectedLines[i])
		}
	}
}

func TestLongLinesRequireSingleInvocation(t *testing.T) {
	buf := makeBytes(1, longLineLength)
	line := string(buf)
	line = line[:len(line)-2] // trim CRLF

	s := NewScanner(bytes.NewBuffer(buf))
	lines := make([]string, 0, 1)
	for s.Scan() {
		lines = append(lines, s.String())
	}
	if s.Err() != nil {
		t.Errorf("Actual: %#v; Expected: %#v", s.Err(), nil)
	}
	if len(lines) != 1 {
		t.Fatalf("Actual: %#v; Expected: %#v", len(lines), 1)
	}
	if lines[0] != line {
		t.Errorf("Actual: %#v; Expected: %#v", lines[0], line)
	}
}

func TestVeryLongLinesRequireSingleInvocation(t *testing.T) {
	buf := makeBytes(1, bufio.MaxScanTokenSize+5)
	line := string(buf)
	line = line[:len(line)-2] // trim CRLF

	s := NewScanner(bytes.NewBuffer(buf))
	lines := make([]string, 0, 1)
	for s.Scan() {
		lines = append(lines, s.String())
	}
	if s.Err() != nil {
		t.Errorf("Actual: %#v; Expected: %#v", s.Err(), nil)
	}
	if len(lines) != 1 {
		t.Fatalf("Actual: %#v; Expected: %#v", len(lines), 1)
	}
	if lines[0] != line {
		t.Errorf("Actual: %#v; Expected: %#v", lines[0], line)
	}
}

type simpleScanner interface {
	Err() error
	Scan() bool
	Bytes() []byte
}

func benchmarkScanner(b *testing.B, lineLength int, makeScanner func(*bytes.Buffer) simpleScanner) {
	master := makeBytes(lineCount, lineLength)
	var line []byte
	s := makeScanner(bytes.NewBuffer(master))
	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		for s.Scan() {
			line = s.Bytes()
		}
		if err := s.Err(); err != nil {
			b.Fatal("Actual: %#v; Expected: %#v", err, nil)
		}
	}
	if len(line) != lineLength {
		b.Errorf("Actual: %#v; Expected: %#v", len(line), lineLength)
	}
}

func BenchmarkBufioScannerAverage(b *testing.B) {
	makeScanner := func(bb *bytes.Buffer) simpleScanner {
		return bufio.NewScanner(bb)
	}
	benchmarkScanner(b, avgLineLength, makeScanner)
}

func BenchmarkGoblsScannerAverage(b *testing.B) {
	makeScanner := func(bb *bytes.Buffer) simpleScanner {
		return NewScanner(bb)
	}
	benchmarkScanner(b, avgLineLength, makeScanner)
}

func BenchmarkBufioScannerShort(b *testing.B) {
	makeScanner := func(bb *bytes.Buffer) simpleScanner {
		return bufio.NewScanner(bb)
	}
	benchmarkScanner(b, shortLineLength, makeScanner)
}

func BenchmarkGoblsScannerShort(b *testing.B) {
	makeScanner := func(bb *bytes.Buffer) simpleScanner {
		return NewScanner(bb)
	}
	benchmarkScanner(b, shortLineLength, makeScanner)
}

func BenchmarkBufioScannerLong(b *testing.B) {
	makeScanner := func(bb *bytes.Buffer) simpleScanner {
		return bufio.NewScanner(bb)
	}
	benchmarkScanner(b, longLineLength, makeScanner)
}

func BenchmarkGoblsScannerLong(b *testing.B) {
	makeScanner := func(bb *bytes.Buffer) simpleScanner {
		return NewScanner(bb)
	}
	benchmarkScanner(b, longLineLength, makeScanner)
}

func BenchmarkBufioScannerVeryLong(b *testing.B) {
	makeScanner := func(bb *bytes.Buffer) simpleScanner {
		return bufio.NewScanner(bb)
	}
	benchmarkScanner(b, veryLongLineLength, makeScanner)
}

func BenchmarkGoblsScannerVeryLong(b *testing.B) {
	makeScanner := func(bb *bytes.Buffer) simpleScanner {
		return NewScanner(bb)
	}
	benchmarkScanner(b, veryLongLineLength, makeScanner)
}
<|endoftext|>