<commit_before>// Application infocmp should have the same output as the standard Unix infocmp
// -1 -L output.
package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"sort"
	"strings"
	"unicode"

	"github.com/xo/terminfo"
)

var (
	flagTerm     = flag.String("term", os.Getenv("TERM"), "term name")
	flagExtended = flag.Bool("x", false, "extended options")
)

func main() {
	flag.Parse()

	ti, err := terminfo.Load(*flagTerm)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("#\tReconstructed via %s from file: %s\n", strings.TrimPrefix(os.Args[0], "./"), ti.File)
	fmt.Printf("%s,\n", strings.TrimSpace(strings.Join(ti.Names, "|")))

	process(ti.BoolCaps, ti.ExtBoolCaps, ti.BoolsM, terminfo.BoolCapName, nil)
	process(
		ti.NumCaps, ti.ExtNumCaps, ti.NumsM, terminfo.NumCapName,
		func(v interface{}) string { return fmt.Sprintf("#%d", v) },
	)
	process(
		ti.StringCaps, ti.ExtStringCaps, ti.StringsM, terminfo.StringCapName,
		func(v interface{}) string { return "=" + escape(v.([]byte)) },
	)
}

func process(x, y interface{}, m map[int]bool, name func(int) string, mask func(interface{}) string) {
	printIt(x, m, name, mask)
	if *flagExtended {
		printIt(y, nil, name, mask)
	}
}

// process walks the values in z, adding missing elements in m. a mask func can
// be provided to format the values in z.
func printIt(z interface{}, m map[int]bool, name func(int) string, mask func(interface{}) string) {
	var names []string
	x := make(map[string]string)
	switch v := z.(type) {
	case func() map[string]bool:
		for n, a := range v() {
			if !a {
				continue
			}
			var f string
			if mask != nil {
				f = mask(a)
			}
			x[n], names = f, append(names, n)
		}

	case func() map[string]int:
		for n, a := range v() {
			if a < 0 {
				continue
			}
			var f string
			if mask != nil {
				f = mask(a)
			}
			x[n], names = f, append(names, n)
		}

	case func() map[string][]byte:
		for n, a := range v() {
			if a == nil {
				continue
			}
			var f string
			if mask != nil {
				f = mask(a)
			}
			if n == "acs_chars" && strings.TrimSpace(strings.TrimPrefix(f, "=")) == "" {
				continue
			}
			x[n], names = f, append(names, n)
		}
	}

	// add missing
	for i := range m {
		n := name(i)
		x[n], names = "@", append(names, n)
	}

	// sort and print
	sort.Strings(names)
	for _, n := range names {
		fmt.Printf("\t%s%s,\n", n, x[n])
	}
}

// peek peeks a byte.
func peek(b []byte, pos, length int) byte {
	if pos < length {
		return b[pos]
	}
	return 0
}

func isprint(b byte) bool {
	return unicode.IsPrint(rune(b))
}

func realprint(b byte) bool {
	return b < 127 && isprint(b)
}

func iscntrl(b byte) bool {
	return unicode.IsControl(rune(b))
}

func realctl(b byte) bool {
	return b < 127 && iscntrl(b)
}

func isdigit(b byte) bool {
	return unicode.IsDigit(rune(b))
}

// logic taken from _nc_tic_expand from ncurses-6.0/ncurses/tinfo/comp_expand.c
func escape(buf []byte) string {
	length := len(buf)
	if length == 0 {
		return ""
	}

	var s []byte
	islong := length > 3
	for i := 0; i < length; i++ {
		ch := buf[i]
		switch {
		case ch == '%' && realprint(peek(buf, i+1, length)):
			s = append(s, buf[i], buf[i+1])
			i++

		case ch == 128:
			s = append(s, '\\', '0')

		case ch == '\033':
			s = append(s, '\\', 'E')

		case realprint(ch) && (ch != ',' && ch != ':' && ch != '!' && ch != '^'):
			s = append(s, ch)

		case ch == '\r' && (islong || (i == length-1 && length > 2)):
			s = append(s, '\\', 'r')

		case ch == '\n' && islong:
			s = append(s, '\\', 'n')

		case realctl(ch) && ch != '\\' && (!islong || isdigit(peek(buf, i+1, length))):
			s = append(s, '^', ch+'@')

		default:
			s = append(s, []byte(fmt.Sprintf("\\%03o", ch))...)
		}
	}

	return string(s)
}
<commit_msg>Minor change to infocmp cli util<commit_after>// Application infocmp should have the same output as the standard Unix infocmp
// -1 -L output.
package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"sort"
	"strings"
	"unicode"

	"github.com/xo/terminfo"
)

var (
	flagTerm     = flag.String("term", os.Getenv("TERM"), "term name")
	flagExtended = flag.Bool("x", false, "extended options")
)

func main() {
	flag.Parse()

	ti, err := terminfo.Load(*flagTerm)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("#\tReconstructed via %s from file: %s\n", strings.TrimPrefix(os.Args[0], "./"), ti.File)
	fmt.Printf("%s,\n", strings.TrimSpace(strings.Join(ti.Names, "|")))

	process(ti.BoolCaps, ti.ExtBoolCaps, ti.BoolsM, terminfo.BoolCapName, nil)
	process(
		ti.NumCaps, ti.ExtNumCaps, ti.NumsM, terminfo.NumCapName,
		func(v interface{}) string { return fmt.Sprintf("#%d", v) },
	)
	process(
		ti.StringCaps, ti.ExtStringCaps, ti.StringsM, terminfo.StringCapName,
		func(v interface{}) string { return "=" + escape(v.([]byte)) },
	)
}

func process(x, y interface{}, m map[int]bool, name func(int) string, mask func(interface{}) string) {
	printIt(x, m, name, mask)
	if *flagExtended {
		printIt(y, nil, name, mask)
	}
}

// process walks the values in z, adding missing elements in m. a mask func can
// be provided to format the values in z.
func printIt(z interface{}, m map[int]bool, name func(int) string, mask func(interface{}) string) {
	var names []string
	x := make(map[string]string)
	switch v := z.(type) {
	case func() map[string]bool:
		for n, a := range v() {
			if !a {
				continue
			}
			var f string
			if mask != nil {
				f = mask(a)
			}
			x[n], names = f, append(names, n)
		}

	case func() map[string]int:
		for n, a := range v() {
			if a < 0 {
				continue
			}
			var f string
			if mask != nil {
				f = mask(a)
			}
			x[n], names = f, append(names, n)
		}

	case func() map[string][]byte:
		for n, a := range v() {
			if a == nil {
				continue
			}
			var f string
			if mask != nil {
				f = mask(a)
			}
			if n == "acs_chars" && strings.TrimSpace(strings.TrimPrefix(f, "=")) == "" {
				continue
			}
			x[n], names = f, append(names, n)
		}
	}

	// add missing
	for i := range m {
		n := name(i)
		x[n], names = "@", append(names, n)
	}

	// sort and print
	sort.Strings(names)
	for _, n := range names {
		fmt.Printf("\t%s%s,\n", n, x[n])
	}
}

// peek peeks a byte.
func peek(b []byte, pos, length int) byte {
	if pos < length {
		return b[pos]
	}
	return 0
}

func isprint(b byte) bool {
	return unicode.IsPrint(rune(b))
}

func realprint(b byte) bool {
	return b < 127 && isprint(b)
}

func iscntrl(b byte) bool {
	return unicode.IsControl(rune(b))
}

func realctl(b byte) bool {
	return b < 127 && iscntrl(b)
}

func isdigit(b byte) bool {
	return unicode.IsDigit(rune(b))
}

// logic taken from _nc_tic_expand from ncurses-6.0/ncurses/tinfo/comp_expand.c
func escape(buf []byte) string {
	length := len(buf)
	if length == 0 {
		return ""
	}

	var s []byte
	islong := length > 3
	for i := 0; i < length; i++ {
		ch := buf[i]
		switch {
		case ch == '%' && realprint(peek(buf, i+1, length)):
			s = append(s, buf[i], buf[i+1])
			i++

		case ch == 128:
			s = append(s, '\\', '0')

		case ch == '\033':
			s = append(s, '\\', 'E')

		case realprint(ch) && ch != ',' && ch != ':' && ch != '!' && ch != '^':
			s = append(s, ch)

		case ch == '\r' && (islong || (i == length-1 && length > 2)):
			s = append(s, '\\', 'r')

		case ch == '\n' && islong:
			s = append(s, '\\', 'n')

		case realctl(ch) && ch != '\\' && (!islong || isdigit(peek(buf, i+1, length))):
			s = append(s, '^', ch+'@')

		default:
			s = append(s, []byte(fmt.Sprintf("\\%03o", ch))...)
		}
	}

	return string(s)
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"net/http"
	"net/url"

	"github.com/hellofresh/janus/pkg/api"
	"github.com/hellofresh/janus/pkg/errors"
	"github.com/hellofresh/janus/pkg/loader"
	"github.com/hellofresh/janus/pkg/middleware"
	"github.com/hellofresh/janus/pkg/notifier"
	"github.com/hellofresh/janus/pkg/oauth"
	"github.com/hellofresh/janus/pkg/proxy"
	"github.com/hellofresh/janus/pkg/router"
	"github.com/hellofresh/janus/pkg/web"
	log "github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
	"gopkg.in/mgo.v2"
)

var (
	repo             api.Repository
	oAuthServersRepo oauth.Repository
	server           *http.Server
)

// RunServer is the run command to start Janus
func RunServer(cmd *cobra.Command, args []string) {
	log.WithField("version", version).Info("Janus starting...")

	defer statsClient.Close()
	defer globalConfig.Log.Flush()

	if subscriber, ok := storage.(notifier.Subscriber); ok {
		listener := notifier.NewNotificationListener(subscriber)
		listener.Start(handleEvent)
	}

	dsnURL, err := url.Parse(globalConfig.Database.DSN)
	switch dsnURL.Scheme {
	case "mongodb":
		log.WithField("dsn", globalConfig.Database.DSN).Debug("Trying to connect to DB")
		session, err := mgo.Dial(globalConfig.Database.DSN)
		if err != nil {
			log.Panic(err)
		}

		defer session.Close()

		log.Debug("Connected to mongodb")
		session.SetMode(mgo.Monotonic, true)

		log.Debug("Loading API definitions from Mongo DB")
		repo, err = api.NewMongoAppRepository(session)
		if err != nil {
			log.Panic(err)
		}

		// create the proxy
		log.Debug("Loading OAuth servers definitions from Mongo DB")
		oAuthServersRepo, err = oauth.NewMongoRepository(session)
		if err != nil {
			log.Panic(err)
		}
	case "file":
		var apiPath = dsnURL.Path + "/apis"
		var authPath = dsnURL.Path + "/auth"

		log.WithField("path", apiPath).Debug("Loading API definitions from file system")
		repo, err = api.NewFileSystemRepository(apiPath)
		if err != nil {
			log.Panic(err)
		}

		log.WithField("path", authPath).Debug("Loading OAuth servers definitions from file system")
		oAuthServersRepo, err = oauth.NewFileSystemRepository(authPath)
		if err != nil {
			log.Panic(err)
		}
	default:
		log.WithError(errors.ErrInvalidScheme).Error("No Database selected")
	}

	wp := web.Provider{
		Port:     globalConfig.Web.Port,
		Cred:     globalConfig.Web.Credentials,
		ReadOnly: globalConfig.Web.ReadOnly,
		TLS:      globalConfig.Web.TLS,
		APIRepo:  repo,
		AuthRepo: oAuthServersRepo,
	}

	if publisher, ok := storage.(notifier.Publisher); ok {
		wp.Notifier = notifier.NewPublisherNotifier(publisher, "")
	}

	wp.Provide(version)

	r := createRouter()

	loader.Load(loader.Params{
		Router:      r,
		Storage:     storage,
		APIRepo:     repo,
		OAuthRepo:   oAuthServersRepo,
		StatsClient: statsClient,
		ProxyParams: proxy.Params{
			StatsClient:            statsClient,
			FlushInterval:          globalConfig.BackendFlushInterval,
			IdleConnectionsPerHost: globalConfig.MaxIdleConnsPerHost,
			CloseIdleConnsPeriod:   globalConfig.CloseIdleConnsPeriod,
		},
	})

	log.Fatal(listenAndServe(r))
}

func listenAndServe(handler http.Handler) error {
	address := fmt.Sprintf(":%v", globalConfig.Port)

	log.Info("Janus started")

	if globalConfig.TLS.IsHTTPS() {
		addressTLS := fmt.Sprintf(":%v", globalConfig.TLS.Port)
		if globalConfig.TLS.Redirect {
			go func() {
				log.WithField("address", address).Info("Listening HTTP")
				log.Fatal(http.ListenAndServe(address, web.RedirectHTTPS(globalConfig.TLS.Port)))
			}()
		}

		log.WithField("address", addressTLS).Info("Listening HTTPS")
		return http.ListenAndServeTLS(addressTLS, globalConfig.TLS.CertFile, globalConfig.TLS.KeyFile, handler)
	}

	log.WithField("address", address).Info("Certificate and certificate key were not found, defaulting to HTTP")
	return http.ListenAndServe(address, handler)
}

func createRouter() router.Router {
	// create router with a custom not found handler
	router.DefaultOptions.NotFoundHandler = web.NotFound
	r := router.NewChiRouterWithOptions(router.DefaultOptions)
	r.Use(
		middleware.NewStats(statsClient).Handler,
		middleware.NewLogger().Handler,
		middleware.NewRecovery(web.RecoveryHandler),
		middleware.NewOpenTracing(globalConfig.TLS.IsHTTPS()).Handler,
	)
	return r
}

func handleEvent(notification notifier.Notification) {
	if notifier.RequireReload(notification.Command) {
		newRouter := createRouter()
		loader.Load(loader.Params{
			Router:      newRouter,
			Storage:     storage,
			APIRepo:     repo,
			OAuthRepo:   oAuthServersRepo,
			StatsClient: statsClient,
			ProxyParams: proxy.Params{
				StatsClient:            statsClient,
				FlushInterval:          globalConfig.BackendFlushInterval,
				IdleConnectionsPerHost: globalConfig.MaxIdleConnsPerHost,
				CloseIdleConnsPeriod:   globalConfig.CloseIdleConnsPeriod,
			},
		})
		server.Handler = newRouter
	}
}
<commit_msg>Fixed bug with server<commit_after>package main

import (
	"fmt"
	"net/http"
	"net/url"

	"github.com/hellofresh/janus/pkg/api"
	"github.com/hellofresh/janus/pkg/errors"
	"github.com/hellofresh/janus/pkg/loader"
	"github.com/hellofresh/janus/pkg/middleware"
	"github.com/hellofresh/janus/pkg/notifier"
	"github.com/hellofresh/janus/pkg/oauth"
	"github.com/hellofresh/janus/pkg/proxy"
	"github.com/hellofresh/janus/pkg/router"
	"github.com/hellofresh/janus/pkg/web"
	log "github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
	"gopkg.in/mgo.v2"
)

var (
	repo             api.Repository
	oAuthServersRepo oauth.Repository
	server           *http.Server
)

// RunServer is the run command to start Janus
func RunServer(cmd *cobra.Command, args []string) {
	log.WithField("version", version).Info("Janus starting...")

	defer statsClient.Close()
	defer globalConfig.Log.Flush()

	if subscriber, ok := storage.(notifier.Subscriber); ok {
		listener := notifier.NewNotificationListener(subscriber)
		listener.Start(handleEvent)
	}

	dsnURL, err := url.Parse(globalConfig.Database.DSN)
	switch dsnURL.Scheme {
	case "mongodb":
		log.Debug("MongoDB configuration chosen")

		log.WithField("dsn", globalConfig.Database.DSN).Debug("Trying to connect to MongoDB...")
		session, err := mgo.Dial(globalConfig.Database.DSN)
		if err != nil {
			log.Panic(err)
		}
		defer session.Close()

		log.Debug("Connected to MongoDB")
		session.SetMode(mgo.Monotonic, true)

		repo, err = api.NewMongoAppRepository(session)
		if err != nil {
			log.Panic(err)
		}

		oAuthServersRepo, err = oauth.NewMongoRepository(session)
		if err != nil {
			log.Panic(err)
		}
	case "file":
		log.Debug("File system based configuration chosen")
		var apiPath = dsnURL.Path + "/apis"
		var authPath = dsnURL.Path + "/auth"

		log.WithFields(log.Fields{
			"api_path":  apiPath,
			"auth_path": authPath,
		}).Debug("Trying to load configuration files")
		repo, err = api.NewFileSystemRepository(apiPath)
		if err != nil {
			log.Panic(err)
		}

		oAuthServersRepo, err = oauth.NewFileSystemRepository(authPath)
		if err != nil {
			log.Panic(err)
		}
	default:
		log.WithError(errors.ErrInvalidScheme).Error("No Database selected")
	}

	wp := web.Provider{
		Port:     globalConfig.Web.Port,
		Cred:     globalConfig.Web.Credentials,
		ReadOnly: globalConfig.Web.ReadOnly,
		TLS:      globalConfig.Web.TLS,
		APIRepo:  repo,
		AuthRepo: oAuthServersRepo,
	}

	if publisher, ok := storage.(notifier.Publisher); ok {
		wp.Notifier = notifier.NewPublisherNotifier(publisher, "")
	}

	wp.Provide(version)

	r := createRouter()
	loader.Load(loader.Params{
		Router:      r,
		Storage:     storage,
		APIRepo:     repo,
		OAuthRepo:   oAuthServersRepo,
		StatsClient: statsClient,
		ProxyParams: proxy.Params{
			StatsClient:            statsClient,
			FlushInterval:          globalConfig.BackendFlushInterval,
			IdleConnectionsPerHost: globalConfig.MaxIdleConnsPerHost,
			CloseIdleConnsPeriod:   globalConfig.CloseIdleConnsPeriod,
		},
	})

	log.Fatal(listenAndServe(r))
}

func listenAndServe(handler http.Handler) error {
	address := fmt.Sprintf(":%v", globalConfig.Port)
	server = &http.Server{Addr: address, Handler: handler}

	log.Info("Janus started")
	if globalConfig.TLS.IsHTTPS() {
		server.Addr = fmt.Sprintf(":%v", globalConfig.TLS.Port)

		if globalConfig.TLS.Redirect {
			go func() {
				log.WithField("address", address).Info("Listening HTTP redirects to HTTPS")
				log.Fatal(http.ListenAndServe(address, web.RedirectHTTPS(globalConfig.TLS.Port)))
			}()
		}

		log.WithField("address", server.Addr).Info("Listening HTTPS")
		return server.ListenAndServeTLS(globalConfig.TLS.CertFile, globalConfig.TLS.KeyFile)
	}

	log.WithField("address", address).Info("Certificate and certificate key were not found, defaulting to HTTP")
	return server.ListenAndServe()
}

func createRouter() router.Router {
	// create router with a custom not found handler
	router.DefaultOptions.NotFoundHandler = web.NotFound
	r := router.NewChiRouterWithOptions(router.DefaultOptions)
	r.Use(
		middleware.NewStats(statsClient).Handler,
		middleware.NewLogger().Handler,
		middleware.NewRecovery(web.RecoveryHandler),
		middleware.NewOpenTracing(globalConfig.TLS.IsHTTPS()).Handler,
	)
	return r
}

func handleEvent(notification notifier.Notification) {
	if notifier.RequireReload(notification.Command) {
		newRouter := createRouter()
		loader.Load(loader.Params{
			Router:      newRouter,
			Storage:     storage,
			APIRepo:     repo,
			OAuthRepo:   oAuthServersRepo,
			StatsClient: statsClient,
			ProxyParams: proxy.Params{
				StatsClient:            statsClient,
				FlushInterval:          globalConfig.BackendFlushInterval,
				IdleConnectionsPerHost: globalConfig.MaxIdleConnsPerHost,
				CloseIdleConnsPeriod:   globalConfig.CloseIdleConnsPeriod,
			},
		})
		server.Handler = newRouter
	}
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"
	"testing"

	"github.com/fiatjaf/jiq"
	"github.com/stretchr/testify/assert"
)

var called int = 0

func TestMain(m *testing.M) {
	called = 0
	code := m.Run()
	defer os.Exit(code)
}

func TestjiqRun(t *testing.T) {
	var assert = assert.New(t)

	e := &jiq.Engine{}
	result := run(e, false)
	assert.Zero(result)
	assert.Equal(2, called)

	result = run(e, true)
	assert.Equal(1, called)

	result = run(e, false)
	assert.Zero(result)
}

func TestjiqRunWithError(t *testing.T) {
	called = 0
	var assert = assert.New(t)
	e := &jiq.Engine{}
	result := run(e, false)
	assert.Equal(2, result)
	assert.Equal(0, called)
}

func (e *EngineMock) Run() jiq.EngineResultInterface {
	return &jiq.EngineResult{
		err:     fmt.Errorf(""),
		qs:      ".querystring",
		content: `{"test": "result"}`,
	}
}
<commit_msg>Fix regression in jiq_test.go after 846f592<commit_after>package main

import (
	"fmt"
	"os"
	"testing"

	"github.com/fiatjaf/jiq"
	"github.com/stretchr/testify/assert"
)

var called int = 0

func TestMain(m *testing.M) {
	called = 0
	code := m.Run()
	defer os.Exit(code)
}

func TestjiqRun(t *testing.T) {
	var assert = assert.New(t)

	e := &jiq.Engine{}
	result := run(e, false)
	assert.Zero(result)
	assert.Equal(2, called)

	result = run(e, true)
	assert.Equal(1, called)

	result = run(e, false)
	assert.Zero(result)
}

func TestjiqRunWithError(t *testing.T) {
	called = 0
	var assert = assert.New(t)
	e := &jiq.Engine{}
	result := run(e, false)
	assert.Equal(2, result)
	assert.Equal(0, called)
}

type EngineMock struct{ err error }

func (e *EngineMock) Run() *jiq.EngineResult {
	return &jiq.EngineResult{
		Err:     fmt.Errorf(""),
		Qs:      ".querystring",
		Content: `{"test": "result"}`,
	}
}
<|endoftext|>


<commit_before>/*
 * Minio Cloud Storage, (C) 2018 Minio, Inc.
 *
 * 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 logger

import (
	"fmt"
	"os"
	"regexp"

	"github.com/fatih/color"
	isatty "github.com/mattn/go-isatty"
)

// Global colors.
var (
	// Check if we stderr, stdout are dumb terminals, we do not apply
	// ansi coloring on dumb terminals.
	isTerminal = func() bool {
		return isatty.IsTerminal(os.Stdout.Fd()) && isatty.IsTerminal(os.Stderr.Fd())
	}

	ColorBold = func() func(a ...interface{}) string {
		if isTerminal() {
			return color.New(color.Bold).SprintFunc()
		}
		return fmt.Sprint
	}()
	ColorFgRed = func() func(format string, a ...interface{}) string {
		if isTerminal() {
			return color.New(color.FgRed).SprintfFunc()
		}
		return fmt.Sprintf
	}()
	ColorBgRed = func() func(format string, a ...interface{}) string {
		if isTerminal() {
			return color.New(color.BgRed).SprintfFunc()
		}
		return fmt.Sprintf
	}()
	ColorFgWhite = func() func(format string, a ...interface{}) string {
		if isTerminal() {
			return color.New(color.FgWhite).SprintfFunc()
		}
		return fmt.Sprintf
	}()
)

var ansiRE = regexp.MustCompile("(\x1b[^m]*m)")

// Print ANSI Control escape
func ansiEscape(format string, args ...interface{}) {
	var Esc = "\x1b"
	fmt.Printf("%s%s", Esc, fmt.Sprintf(format, args...))
}

func ansiMoveRight(n int) {
	if isTerminal() {
		ansiEscape("[%dC", n)
	}
}

func ansiSaveAttributes() {
	if isTerminal() {
		ansiEscape("7")
	}
}

func ansiRestoreAttributes() {
	if isTerminal() {
		ansiEscape("8")
	}

}
<commit_msg>logger: do not interpret encoded url as format string (#7110)<commit_after>/*
 * Minio Cloud Storage, (C) 2018 Minio, Inc.
 *
 * 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 logger

import (
	"fmt"
	"os"
	"regexp"

	"github.com/fatih/color"
	isatty "github.com/mattn/go-isatty"
)

// Global colors.
var (
	// Check if we stderr, stdout are dumb terminals, we do not apply
	// ansi coloring on dumb terminals.
	isTerminal = func() bool {
		return isatty.IsTerminal(os.Stdout.Fd()) && isatty.IsTerminal(os.Stderr.Fd())
	}

	ColorBold = func() func(a ...interface{}) string {
		if isTerminal() {
			return color.New(color.Bold).SprintFunc()
		}
		return fmt.Sprint
	}()
	ColorFgRed = func() func(a ...interface{}) string {
		if isTerminal() {
			return color.New(color.FgRed).SprintFunc()
		}
		return fmt.Sprint
	}()
	ColorBgRed = func() func(format string, a ...interface{}) string {
		if isTerminal() {
			return color.New(color.BgRed).SprintfFunc()
		}
		return fmt.Sprintf
	}()
	ColorFgWhite = func() func(format string, a ...interface{}) string {
		if isTerminal() {
			return color.New(color.FgWhite).SprintfFunc()
		}
		return fmt.Sprintf
	}()
)

var ansiRE = regexp.MustCompile("(\x1b[^m]*m)")

// Print ANSI Control escape
func ansiEscape(format string, args ...interface{}) {
	var Esc = "\x1b"
	fmt.Printf("%s%s", Esc, fmt.Sprintf(format, args...))
}

func ansiMoveRight(n int) {
	if isTerminal() {
		ansiEscape("[%dC", n)
	}
}

func ansiSaveAttributes() {
	if isTerminal() {
		ansiEscape("7")
	}
}

func ansiRestoreAttributes() {
	if isTerminal() {
		ansiEscape("8")
	}

}
<|endoftext|>


<commit_before>package cmd_test

import (
	"io/ioutil"
	"launchpad.net/gnuflag"
	. "launchpad.net/gocheck"
	"launchpad.net/juju/go/cmd"
	"launchpad.net/juju/go/log"
	"path/filepath"
)

func saveLog() func() {
	target, debug := log.Target, log.Debug
	return func() {
		log.Target, log.Debug = target, debug
	}
}

type LogSuite struct {
	restoreLog func()
}

var _ = Suite(&LogSuite{})

func (s *LogSuite) SetUpTest(c *C) {
	s.restoreLog = saveLog()
}

func (s *LogSuite) TearDownTest(c *C) {
	s.restoreLog()
}

func (s *LogSuite) TestAddFlags(c *C) {
	l := &cmd.Log{}
	f := gnuflag.NewFlagSet("", gnuflag.ContinueOnError)
	l.AddFlags(f)

	err := f.Parse(false, []string{})
	c.Assert(err, IsNil)
	c.Assert(l.Path, Equals, "")
	c.Assert(l.Verbose, Equals, false)
	c.Assert(l.Debug, Equals, false)

	err = f.Parse(false, []string{"--log-file", "foo", "--verbose", "--debug"})
	c.Assert(err, IsNil)
	c.Assert(l.Path, Equals, "foo")
	c.Assert(l.Verbose, Equals, true)
	c.Assert(l.Debug, Equals, true)
}

func (s *LogSuite) TestStart(c *C) {
	defer saveLog()()
	for _, t := range []struct {
		path    string
		verbose bool
		debug   bool
		target  Checker
	}{
		{"", true, true, NotNil},
		{"", true, false, NotNil},
		{"", false, true, NotNil},
		{"", false, false, IsNil},
		{"foo", true, true, NotNil},
		{"foo", true, false, NotNil},
		{"foo", false, true, NotNil},
		{"foo", false, false, NotNil},
	} {
		l := &cmd.Log{t.path, t.verbose, t.debug}
		ctx := dummyContext(c)
		err := l.Start(ctx)
		c.Assert(err, IsNil)
		c.Assert(log.Target, t.target)
		c.Assert(log.Debug, Equals, t.debug)
	}
}

func (s *LogSuite) TestStderr(c *C) {
	defer saveLog()()
	l := &cmd.Log{Verbose: true}
	ctx := dummyContext(c)
	err := l.Start(ctx)
	c.Assert(err, IsNil)
	log.Printf("hello")
	c.Assert(str(ctx.Stderr), Matches, `.* JUJU hello\n`)
}

func (s *LogSuite) TestRelPathLog(c *C) {
	defer saveLog()()
	l := &cmd.Log{Path: "foo.log"}
	ctx := dummyContext(c)
	err := l.Start(ctx)
	c.Assert(err, IsNil)
	log.Printf("hello")
	c.Assert(str(ctx.Stderr), Equals, "")
	content, err := ioutil.ReadFile(filepath.Join(ctx.Dir, "foo.log"))
	c.Assert(err, IsNil)
	c.Assert(string(content), Matches, `.* JUJU hello\n`)
}

func (s *LogSuite) TestAbsPathLog(c *C) {
	defer saveLog()()
	path := filepath.Join(c.MkDir(), "foo.log")
	l := &cmd.Log{Path: path}
	ctx := dummyContext(c)
	err := l.Start(ctx)
	c.Assert(err, IsNil)
	log.Printf("hello")
	c.Assert(str(ctx.Stderr), Equals, "")
	content, err := ioutil.ReadFile(path)
	c.Assert(err, IsNil)
	c.Assert(string(content), Matches, `.* JUJU hello\n`)
}
<commit_msg>whoops, unsaved buffer<commit_after>package cmd_test

import (
	"io/ioutil"
	"launchpad.net/gnuflag"
	. "launchpad.net/gocheck"
	"launchpad.net/juju/go/cmd"
	"launchpad.net/juju/go/log"
	"path/filepath"
)

type LogSuite struct {
	restoreLog func()
}

var _ = Suite(&LogSuite{})

func (s *LogSuite) SetUpTest(c *C) {
	target, debug := log.Target, log.Debug
	s.restoreLog = func() {
		log.Target, log.Debug = target, debug
	}
}

func (s *LogSuite) TearDownTest(c *C) {
	s.restoreLog()
}

func (s *LogSuite) TestAddFlags(c *C) {
	l := &cmd.Log{}
	f := gnuflag.NewFlagSet("", gnuflag.ContinueOnError)
	l.AddFlags(f)

	err := f.Parse(false, []string{})
	c.Assert(err, IsNil)
	c.Assert(l.Path, Equals, "")
	c.Assert(l.Verbose, Equals, false)
	c.Assert(l.Debug, Equals, false)

	err = f.Parse(false, []string{"--log-file", "foo", "--verbose", "--debug"})
	c.Assert(err, IsNil)
	c.Assert(l.Path, Equals, "foo")
	c.Assert(l.Verbose, Equals, true)
	c.Assert(l.Debug, Equals, true)
}

func (s *LogSuite) TestStart(c *C) {
	for _, t := range []struct {
		path    string
		verbose bool
		debug   bool
		target  Checker
	}{
		{"", true, true, NotNil},
		{"", true, false, NotNil},
		{"", false, true, NotNil},
		{"", false, false, IsNil},
		{"foo", true, true, NotNil},
		{"foo", true, false, NotNil},
		{"foo", false, true, NotNil},
		{"foo", false, false, NotNil},
	} {
		l := &cmd.Log{t.path, t.verbose, t.debug}
		ctx := dummyContext(c)
		err := l.Start(ctx)
		c.Assert(err, IsNil)
		c.Assert(log.Target, t.target)
		c.Assert(log.Debug, Equals, t.debug)
	}
}

func (s *LogSuite) TestStderr(c *C) {
	l := &cmd.Log{Verbose: true}
	ctx := dummyContext(c)
	err := l.Start(ctx)
	c.Assert(err, IsNil)
	log.Printf("hello")
	c.Assert(str(ctx.Stderr), Matches, `.* JUJU hello\n`)
}

func (s *LogSuite) TestRelPathLog(c *C) {
	l := &cmd.Log{Path: "foo.log"}
	ctx := dummyContext(c)
	err := l.Start(ctx)
	c.Assert(err, IsNil)
	log.Printf("hello")
	c.Assert(str(ctx.Stderr), Equals, "")
	content, err := ioutil.ReadFile(filepath.Join(ctx.Dir, "foo.log"))
	c.Assert(err, IsNil)
	c.Assert(string(content), Matches, `.* JUJU hello\n`)
}

func (s *LogSuite) TestAbsPathLog(c *C) {
	path := filepath.Join(c.MkDir(), "foo.log")
	l := &cmd.Log{Path: path}
	ctx := dummyContext(c)
	err := l.Start(ctx)
	c.Assert(err, IsNil)
	log.Printf("hello")
	c.Assert(str(ctx.Stderr), Equals, "")
	content, err := ioutil.ReadFile(path)
	c.Assert(err, IsNil)
	c.Assert(string(content), Matches, `.* JUJU hello\n`)
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"fmt"
	"io"
	"os"

	"github.com/qiniu/goplus/cmd/qexp/gopkg"
)

var (
	exportFile string
)

func createExportFile(pkgDir string) (f io.WriteCloser, err error) {
	os.MkdirAll(pkgDir, 0777)
	exportFile = pkgDir + "/gomod_export.go"
	return os.Create(exportFile)
}

func main() {
	flag.Parse()
	if flag.NArg() < 1 {
		fmt.Fprintf(os.Stderr, "Usage: qexp <goPkgPath>\n")
		flag.PrintDefaults()
		return
	}
	pkgPath := flag.Arg(0)
	defer func() {
		if exportFile != "" {
			os.Remove(exportFile)
		}
	}()
	err := gopkg.Export(pkgPath, createExportFile)
	if err != nil {
		fmt.Fprintln(os.Stderr, "export failed:", err)
		os.Exit(1)
	}
	exportFile = "" // don't remove file if success
}

// -----------------------------------------------------------------------------
<commit_msg>copyright<commit_after>/*
 Copyright 2020 The GoPlus Authors (goplus.org)

 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 (
	"flag"
	"fmt"
	"io"
	"os"

	"github.com/qiniu/goplus/cmd/qexp/gopkg"
)

var (
	exportFile string
)

func createExportFile(pkgDir string) (f io.WriteCloser, err error) {
	os.MkdirAll(pkgDir, 0777)
	exportFile = pkgDir + "/gomod_export.go"
	return os.Create(exportFile)
}

func main() {
	flag.Parse()
	if flag.NArg() < 1 {
		fmt.Fprintf(os.Stderr, "Usage: qexp <goPkgPath>\n")
		flag.PrintDefaults()
		return
	}
	pkgPath := flag.Arg(0)
	defer func() {
		if exportFile != "" {
			os.Remove(exportFile)
		}
	}()
	err := gopkg.Export(pkgPath, createExportFile)
	if err != nil {
		fmt.Fprintln(os.Stderr, "export failed:", err)
		os.Exit(1)
	}
	exportFile = "" // don't remove file if success
}

// -----------------------------------------------------------------------------
<|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
			break
		case "AAAA":
			option.Type = dns.TypeAAAA
			break
		case "ANY":
			option.Type = dns.TypeANY
			break
		default:
			return fmt.Errorf("invalid type for DNS: %v", splits[5])
		}
	}

	*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."+
			" 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 go switch<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
		default:
			return fmt.Errorf("invalid type for DNS: %v", splits[5])
		}
	}

	*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."+
			" 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")
}
<|endoftext|>


<commit_before>package main

import (
	"context"
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"runtime"
	"strings"
	"time"

	"github.com/status-im/status-go/cmd/statusd/debug"
	"github.com/status-im/status-go/geth/api"
	"github.com/status-im/status-go/geth/common"
	"github.com/status-im/status-go/geth/params"
	"github.com/status-im/status-go/metrics"
	nodemetrics "github.com/status-im/status-go/metrics/node"
)

var (
	gitCommit  = "N/A" // rely on linker: -ldflags -X main.GitCommit"
	buildStamp = "N/A" // rely on linker: -ldflags -X main.buildStamp"
)

var (
	prodMode       = flag.Bool("production", false, "Whether production settings should be loaded")
	nodeKeyFile    = flag.String("nodekey", "", "P2P node key file (private key)")
	dataDir        = flag.String("datadir", params.DataDir, "Data directory for the databases and keystore")
	networkID      = flag.Int("networkid", params.RopstenNetworkID, "Network identifier (integer, 1=Homestead, 3=Ropsten, 4=Rinkeby, 777=StatusChain)")
	lesEnabled     = flag.Bool("les", false, "LES protocol enabled (default is disabled)")
	whisperEnabled = flag.Bool("shh", false, "Whisper protocol enabled (default is disabled)")
	swarmEnabled   = flag.Bool("swarm", false, "Swarm protocol enabled")
	maxPeers       = flag.Int("maxpeers", 25, "maximum number of p2p peers (including all protocols)")
	httpEnabled    = flag.Bool("http", false, "HTTP RPC endpoint enabled (default: false)")
	httpPort       = flag.Int("httpport", params.HTTPPort, "HTTP RPC server's listening port")
	ipcEnabled     = flag.Bool("ipc", false, "IPC RPC endpoint enabled")
	cliEnabled     = flag.Bool("cli", false, "Enable debugging CLI server")
	cliPort        = flag.String("cliport", debug.CLIPort, "CLI server's listening port")
	logLevel       = flag.String("log", "INFO", `Log level, one of: "ERROR", "WARN", "INFO", "DEBUG", and "TRACE"`)
	logFile        = flag.String("logfile", "", "Path to the log file")
	version        = flag.Bool("version", false, "Print version")

	listenAddr = flag.String("listenaddr", ":30303", "IP address and port of this node (e.g. 127.0.0.1:30303)")
	standalone = flag.Bool("standalone", true, "Don't actively connect to peers, wait for incoming connections")
	bootnodes  = flag.String("bootnodes", "", "A list of bootnodes separated by comma")

	// stats
	statsEnabled = flag.Bool("stats", false, "Expose node stats via /debug/vars expvar endpoint or Prometheus (log by default)")
	statsAddr    = flag.String("stats.addr", "0.0.0.0:8080", "HTTP address with /debug/vars endpoint")

	// don't change the name of this flag, https://github.com/ethereum/go-ethereum/blob/master/metrics/metrics.go#L41
	ethereumMetrics = flag.Bool("metrics", false, "Expose ethereum metrics with debug_metrics jsonrpc call.")
	// shh stuff
	identityFile = flag.String("shh.identityfile", "", "Protocol identity file (private key used for asymmetric encryption)")
	passwordFile = flag.String("shh.passwordfile", "", "Password file (password is used for symmetric encryption)")
	minPow       = flag.Float64("shh.pow", params.WhisperMinimumPoW, "PoW for messages to be added to queue, in float format")
	ttl          = flag.Int("shh.ttl", params.WhisperTTL, "Time to live for messages, in seconds")

	// MailServer
	enableMailServer = flag.Bool("shh.mailserver", false, "Delivers expired messages on demand")

	// Push Notification
	enablePN     = flag.Bool("shh.notify", false, "Node is capable of sending Push Notifications")
	firebaseAuth = flag.String("shh.firebaseauth", "", "FCM Authorization Key used for sending Push Notifications")
)

func main() {
	flag.Usage = printUsage
	flag.Parse()

	config, err := makeNodeConfig()
	if err != nil {
		log.Fatalf("Making config failed: %v", err)
		return
	}

	if *version {
		printVersion(config, gitCommit, buildStamp)
		return
	}

	backend := api.NewStatusBackend()
	started, err := backend.StartNode(config)
	if err != nil {
		log.Fatalf("Node start failed: %v", err)
		return
	}

	// handle interrupt signals
	interruptCh := haltOnInterruptSignal(backend.NodeManager())

	// wait till node is started
	<-started

	// Check if debugging CLI connection shall be enabled.
	if *cliEnabled {
		err := startDebug(backend)
		if err != nil {
			log.Fatalf("Starting debugging CLI server failed: %v", err)
			return
		}
	}

	// Run stats server.
	if *statsEnabled {
		go startCollectingStats(interruptCh, backend.NodeManager())
	}

	// wait till node has been stopped
	node, err := backend.NodeManager().Node()
	if err != nil {
		log.Fatalf("Getting node failed: %v", err)
		return
	}

	node.Wait()
}

// startDebug starts the debugging API server.
func startDebug(backend *api.StatusBackend) error {
	statusAPI := api.NewStatusAPIWithBackend(backend)
	_, err := debug.New(statusAPI, *cliPort)
	return err
}

// startCollectingStats collects various stats about the node and other protocols like Whisper.
func startCollectingStats(interruptCh <-chan struct{}, nodeManager common.NodeManager) {
	log.Printf("Starting stats on %v", *statsAddr)

	node, err := nodeManager.Node()
	if err != nil {
		log.Printf("Failed to run metrics because could not get node: %v", err)
		return
	}

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	go func() {
		if err := nodemetrics.SubscribeServerEvents(ctx, node); err != nil {
			log.Printf("Failed to subscribe server events: %v", err)
		}
	}()

	server := metrics.NewMetricsServer(*statsAddr)
	go func() {
		err := server.ListenAndServe()
		switch err {
		case http.ErrServerClosed:
		default:
			log.Printf("Metrics server failed: %v", err)
		}
	}()

	<-interruptCh

	if err := server.Shutdown(context.TODO()); err != nil {
		log.Printf("Failed to shutdown metrics server: %v", err)
	}
}

// makeNodeConfig parses incoming CLI options and returns node configuration object
func makeNodeConfig() (*params.NodeConfig, error) {
	devMode := !*prodMode
	nodeConfig, err := params.NewNodeConfig(*dataDir, uint64(*networkID), devMode)
	if err != nil {
		return nil, err
	}

	// TODO(divan): move this logic into params package
	if *nodeKeyFile != "" {
		nodeConfig.NodeKeyFile = *nodeKeyFile
	}

	if *logLevel != "" {
		nodeConfig.LogLevel = *logLevel
	}
	if *logFile != "" {
		nodeConfig.LogFile = *logFile
	}

	nodeConfig.RPCEnabled = *httpEnabled
	nodeConfig.WhisperConfig.Enabled = *whisperEnabled
	nodeConfig.MaxPeers = *maxPeers

	nodeConfig.HTTPPort = *httpPort
	nodeConfig.IPCEnabled = *ipcEnabled

	nodeConfig.LightEthConfig.Enabled = *lesEnabled
	nodeConfig.SwarmConfig.Enabled = *swarmEnabled

	if *standalone {
		nodeConfig.BootClusterConfig.Enabled = false
		nodeConfig.BootClusterConfig.BootNodes = nil
	} else {
		nodeConfig.Discovery = true
	}

	// Even if standalone is true and discovery is disabled,
	// it's possible to use bootnodes in NodeManager.PopulateStaticPeers().
	// TODO(adam): research if we need NodeManager.PopulateStaticPeers() at all.
	if *bootnodes != "" {
		nodeConfig.BootClusterConfig.BootNodes = strings.Split(*bootnodes, ",")
	}

	if *whisperEnabled {
		return whisperConfig(nodeConfig)
	}

	// RPC configuration
	if !*httpEnabled {
		nodeConfig.HTTPHost = "" // HTTP RPC is disabled
	}

	return nodeConfig, nil
}

// printVersion prints verbose output about version and config.
func printVersion(config *params.NodeConfig, gitCommit, buildStamp string) {
	if gitCommit != "" && len(gitCommit) > 8 {
		params.Version += "-" + gitCommit[:8]
	}

	fmt.Println(strings.Title(params.ClientIdentifier))
	fmt.Println("Version:", params.Version)
	if gitCommit != "" {
		fmt.Println("Git Commit:", gitCommit)
	}
	if buildStamp != "" {
		fmt.Println("Build Stamp:", buildStamp)
	}

	fmt.Println("Network Id:", config.NetworkID)
	fmt.Println("Go Version:", runtime.Version())
	fmt.Println("OS:", runtime.GOOS)
	fmt.Printf("GOPATH=%s\n", os.Getenv("GOPATH"))
	fmt.Printf("GOROOT=%s\n", runtime.GOROOT())

	config.LightEthConfig.Genesis = "SKIP"
	fmt.Println("Loaded Config: ", config)
}

func printUsage() {
	usage := `
Usage: statusd [options]
Examples:
  statusd               # run status node with defaults
  statusd -networkid 4  # run node on Rinkeby network
  statusd -datadir /dir # specify different dir for data
  statusd -ipc          # enable IPC for usage with "geth attach"
  statusd -cli          # enable connection by statusd-cli on default port

Options:
`
	fmt.Fprint(os.Stderr, usage) // nolint: gas
	flag.PrintDefaults()
}

// haltOnInterruptSignal catches interrupt signal (SIGINT) and
// stops the node. It times out after 5 seconds
// if the node can not be stopped.
func haltOnInterruptSignal(nodeManager common.NodeManager) <-chan struct{} {
	interruptCh := make(chan struct{})

	go func() {
		signalCh := make(chan os.Signal, 1)
		signal.Notify(signalCh, os.Interrupt)
		defer signal.Stop(signalCh)
		<-signalCh

		close(interruptCh)

		log.Println("Got interrupt, shutting down...")

		nodeStopped, err := nodeManager.StopNode()
		if err != nil {
			log.Printf("Failed to stop node: %v", err)
			os.Exit(1)
		}

		select {
		case <-nodeStopped:
		case <-time.After(time.Second * 5):
			log.Printf("Stopping node timed out")
			os.Exit(1)
		}
	}()

	return interruptCh
}
<commit_msg>Fix linter after ethmetrics were merged (#622)<commit_after>package main

import (
	"context"
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"runtime"
	"strings"
	"time"

	"github.com/status-im/status-go/cmd/statusd/debug"
	"github.com/status-im/status-go/geth/api"
	"github.com/status-im/status-go/geth/common"
	"github.com/status-im/status-go/geth/params"
	"github.com/status-im/status-go/metrics"
	nodemetrics "github.com/status-im/status-go/metrics/node"
)

var (
	gitCommit  = "N/A" // rely on linker: -ldflags -X main.GitCommit"
	buildStamp = "N/A" // rely on linker: -ldflags -X main.buildStamp"
)

var (
	prodMode       = flag.Bool("production", false, "Whether production settings should be loaded")
	nodeKeyFile    = flag.String("nodekey", "", "P2P node key file (private key)")
	dataDir        = flag.String("datadir", params.DataDir, "Data directory for the databases and keystore")
	networkID      = flag.Int("networkid", params.RopstenNetworkID, "Network identifier (integer, 1=Homestead, 3=Ropsten, 4=Rinkeby, 777=StatusChain)")
	lesEnabled     = flag.Bool("les", false, "LES protocol enabled (default is disabled)")
	whisperEnabled = flag.Bool("shh", false, "Whisper protocol enabled (default is disabled)")
	swarmEnabled   = flag.Bool("swarm", false, "Swarm protocol enabled")
	maxPeers       = flag.Int("maxpeers", 25, "maximum number of p2p peers (including all protocols)")
	httpEnabled    = flag.Bool("http", false, "HTTP RPC endpoint enabled (default: false)")
	httpPort       = flag.Int("httpport", params.HTTPPort, "HTTP RPC server's listening port")
	ipcEnabled     = flag.Bool("ipc", false, "IPC RPC endpoint enabled")
	cliEnabled     = flag.Bool("cli", false, "Enable debugging CLI server")
	cliPort        = flag.String("cliport", debug.CLIPort, "CLI server's listening port")
	logLevel       = flag.String("log", "INFO", `Log level, one of: "ERROR", "WARN", "INFO", "DEBUG", and "TRACE"`)
	logFile        = flag.String("logfile", "", "Path to the log file")
	version        = flag.Bool("version", false, "Print version")

	listenAddr = flag.String("listenaddr", ":30303", "IP address and port of this node (e.g. 127.0.0.1:30303)")
	standalone = flag.Bool("standalone", true, "Don't actively connect to peers, wait for incoming connections")
	bootnodes  = flag.String("bootnodes", "", "A list of bootnodes separated by comma")

	// stats
	statsEnabled = flag.Bool("stats", false, "Expose node stats via /debug/vars expvar endpoint or Prometheus (log by default)")
	statsAddr    = flag.String("stats.addr", "0.0.0.0:8080", "HTTP address with /debug/vars endpoint")

	// don't change the name of this flag, https://github.com/ethereum/go-ethereum/blob/master/metrics/metrics.go#L41
	_ = flag.Bool("metrics", false, "Expose ethereum metrics with debug_metrics jsonrpc call.")
	// shh stuff
	identityFile = flag.String("shh.identityfile", "", "Protocol identity file (private key used for asymmetric encryption)")
	passwordFile = flag.String("shh.passwordfile", "", "Password file (password is used for symmetric encryption)")
	minPow       = flag.Float64("shh.pow", params.WhisperMinimumPoW, "PoW for messages to be added to queue, in float format")
	ttl          = flag.Int("shh.ttl", params.WhisperTTL, "Time to live for messages, in seconds")

	// MailServer
	enableMailServer = flag.Bool("shh.mailserver", false, "Delivers expired messages on demand")

	// Push Notification
	enablePN     = flag.Bool("shh.notify", false, "Node is capable of sending Push Notifications")
	firebaseAuth = flag.String("shh.firebaseauth", "", "FCM Authorization Key used for sending Push Notifications")
)

func main() {
	flag.Usage = printUsage
	flag.Parse()

	config, err := makeNodeConfig()
	if err != nil {
		log.Fatalf("Making config failed: %v", err)
		return
	}

	if *version {
		printVersion(config, gitCommit, buildStamp)
		return
	}

	backend := api.NewStatusBackend()
	started, err := backend.StartNode(config)
	if err != nil {
		log.Fatalf("Node start failed: %v", err)
		return
	}

	// handle interrupt signals
	interruptCh := haltOnInterruptSignal(backend.NodeManager())

	// wait till node is started
	<-started

	// Check if debugging CLI connection shall be enabled.
	if *cliEnabled {
		err := startDebug(backend)
		if err != nil {
			log.Fatalf("Starting debugging CLI server failed: %v", err)
			return
		}
	}

	// Run stats server.
	if *statsEnabled {
		go startCollectingStats(interruptCh, backend.NodeManager())
	}

	// wait till node has been stopped
	node, err := backend.NodeManager().Node()
	if err != nil {
		log.Fatalf("Getting node failed: %v", err)
		return
	}

	node.Wait()
}

// startDebug starts the debugging API server.
func startDebug(backend *api.StatusBackend) error {
	statusAPI := api.NewStatusAPIWithBackend(backend)
	_, err := debug.New(statusAPI, *cliPort)
	return err
}

// startCollectingStats collects various stats about the node and other protocols like Whisper.
func startCollectingStats(interruptCh <-chan struct{}, nodeManager common.NodeManager) {
	log.Printf("Starting stats on %v", *statsAddr)

	node, err := nodeManager.Node()
	if err != nil {
		log.Printf("Failed to run metrics because could not get node: %v", err)
		return
	}

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	go func() {
		if err := nodemetrics.SubscribeServerEvents(ctx, node); err != nil {
			log.Printf("Failed to subscribe server events: %v", err)
		}
	}()

	server := metrics.NewMetricsServer(*statsAddr)
	go func() {
		err := server.ListenAndServe()
		switch err {
		case http.ErrServerClosed:
		default:
			log.Printf("Metrics server failed: %v", err)
		}
	}()

	<-interruptCh

	if err := server.Shutdown(context.TODO()); err != nil {
		log.Printf("Failed to shutdown metrics server: %v", err)
	}
}

// makeNodeConfig parses incoming CLI options and returns node configuration object
func makeNodeConfig() (*params.NodeConfig, error) {
	devMode := !*prodMode
	nodeConfig, err := params.NewNodeConfig(*dataDir, uint64(*networkID), devMode)
	if err != nil {
		return nil, err
	}

	// TODO(divan): move this logic into params package
	if *nodeKeyFile != "" {
		nodeConfig.NodeKeyFile = *nodeKeyFile
	}

	if *logLevel != "" {
		nodeConfig.LogLevel = *logLevel
	}
	if *logFile != "" {
		nodeConfig.LogFile = *logFile
	}

	nodeConfig.RPCEnabled = *httpEnabled
	nodeConfig.WhisperConfig.Enabled = *whisperEnabled
	nodeConfig.MaxPeers = *maxPeers

	nodeConfig.HTTPPort = *httpPort
	nodeConfig.IPCEnabled = *ipcEnabled

	nodeConfig.LightEthConfig.Enabled = *lesEnabled
	nodeConfig.SwarmConfig.Enabled = *swarmEnabled

	if *standalone {
		nodeConfig.BootClusterConfig.Enabled = false
		nodeConfig.BootClusterConfig.BootNodes = nil
	} else {
		nodeConfig.Discovery = true
	}

	// Even if standalone is true and discovery is disabled,
	// it's possible to use bootnodes in NodeManager.PopulateStaticPeers().
	// TODO(adam): research if we need NodeManager.PopulateStaticPeers() at all.
	if *bootnodes != "" {
		nodeConfig.BootClusterConfig.BootNodes = strings.Split(*bootnodes, ",")
	}

	if *whisperEnabled {
		return whisperConfig(nodeConfig)
	}

	// RPC configuration
	if !*httpEnabled {
		nodeConfig.HTTPHost = "" // HTTP RPC is disabled
	}

	return nodeConfig, nil
}

// printVersion prints verbose output about version and config.
func printVersion(config *params.NodeConfig, gitCommit, buildStamp string) {
	if gitCommit != "" && len(gitCommit) > 8 {
		params.Version += "-" + gitCommit[:8]
	}

	fmt.Println(strings.Title(params.ClientIdentifier))
	fmt.Println("Version:", params.Version)
	if gitCommit != "" {
		fmt.Println("Git Commit:", gitCommit)
	}
	if buildStamp != "" {
		fmt.Println("Build Stamp:", buildStamp)
	}

	fmt.Println("Network Id:", config.NetworkID)
	fmt.Println("Go Version:", runtime.Version())
	fmt.Println("OS:", runtime.GOOS)
	fmt.Printf("GOPATH=%s\n", os.Getenv("GOPATH"))
	fmt.Printf("GOROOT=%s\n", runtime.GOROOT())

	config.LightEthConfig.Genesis = "SKIP"
	fmt.Println("Loaded Config: ", config)
}

func printUsage() {
	usage := `
Usage: statusd [options]
Examples:
  statusd               # run status node with defaults
  statusd -networkid 4  # run node on Rinkeby network
  statusd -datadir /dir # specify different dir for data
  statusd -ipc          # enable IPC for usage with "geth attach"
  statusd -cli          # enable connection by statusd-cli on default port

Options:
`
	fmt.Fprint(os.Stderr, usage) // nolint: gas
	flag.PrintDefaults()
}

// haltOnInterruptSignal catches interrupt signal (SIGINT) and
// stops the node. It times out after 5 seconds
// if the node can not be stopped.
func haltOnInterruptSignal(nodeManager common.NodeManager) <-chan struct{} {
	interruptCh := make(chan struct{})

	go func() {
		signalCh := make(chan os.Signal, 1)
		signal.Notify(signalCh, os.Interrupt)
		defer signal.Stop(signalCh)
		<-signalCh

		close(interruptCh)

		log.Println("Got interrupt, shutting down...")

		nodeStopped, err := nodeManager.StopNode()
		if err != nil {
			log.Printf("Failed to stop node: %v", err)
			os.Exit(1)
		}

		select {
		case <-nodeStopped:
		case <-time.After(time.Second * 5):
			log.Printf("Stopping node timed out")
			os.Exit(1)
		}
	}()

	return interruptCh
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"fmt"
	"github.com/Symantec/Dominator/lib/constants"
	"github.com/Symantec/Dominator/lib/flagutil"
	"github.com/Symantec/Dominator/lib/srpc"
	"github.com/Symantec/Dominator/lib/srpc/setupclient"
	"os"
	"time"
)

var (
	computedFilesRoot = flag.String("computedFilesRoot", "",
		"Name of directory tree containing computed files")
	debug             = flag.Bool("debug", false, "Enable debug mode")
	deleteBeforeFetch = flag.Bool("deleteBeforeFetch", false,
		"If true, delete prior to Fetch rather than during Update")
	file = flag.String("file", "",
		"Name of file to write encoded data to")
	filterFile = flag.String("filterFile", "",
		"Replacement filter file to apply when pushing image")
	imageServerHostname = flag.String("imageServerHostname", "localhost",
		"Hostname of image server")
	imageServerPortNum = flag.Uint("imageServerPortNum",
		constants.ImageServerPortNumber,
		"Port number of image server")
	interval = flag.Uint("interval", 1,
		"Seconds to sleep between Polls")
	networkSpeedPercent = flag.Uint("networkSpeedPercent",
		constants.DefaultNetworkSpeedPercent,
		"Network speed as percentage of capacity")
	newConnection = flag.Bool("newConnection", false,
		"If true, (re)open a connection for each Poll")
	numPolls = flag.Int("numPolls", 1,
		"The number of polls to run (infinite: < 0)")
	objectServerHostname = flag.String("objectServerHostname", "localhost",
		"Hostname of image server")
	objectServerPortNum = flag.Uint("objectServerPortNum",
		constants.ImageServerPortNumber,
		"Port number of image server")
	scanExcludeList  flagutil.StringList = constants.ScanExcludeList
	scanSpeedPercent                     = flag.Uint("scanSpeedPercent",
		constants.DefaultScanSpeedPercent,
		"Scan speed as percentage of capacity")
	shortPoll = flag.Bool("shortPoll", false,
		"If true, perform a short poll which does not request image or object data")
	showTimes = flag.Bool("showTimes", false,
		"If true, show time taken for some operations")
	subHostname = flag.String("subHostname", "localhost", "Hostname of sub")
	subPortNum  = flag.Uint("subPortNum", constants.SubPortNumber,
		"Port number of sub")
	timeout = flag.Duration("timeout", 15*time.Minute,
		"timeout for push-image retry loop")
	triggersFile = flag.String("triggersFile", "",
		"Replacement triggers file to apply when pushing image")
	triggersString = flag.String("triggersString", "",
		"Replacement triggers string to apply when pushing image")
	wait = flag.Uint("wait", 0, "Seconds to sleep after last Poll")
)

func init() {
	flag.Var(&scanExcludeList, "scanExcludeList",
		"Comma separated list of patterns to exclude from scanning")
}

func printUsage() {
	fmt.Fprintln(os.Stderr,
		"Usage: subtool [flags...] fetch|get-config|poll|set-config")
	fmt.Fprintln(os.Stderr, "Common flags:")
	flag.PrintDefaults()
	fmt.Fprintln(os.Stderr, "Commands:")
	fmt.Fprintln(os.Stderr, "  fetch hashesFile")
	fmt.Fprintln(os.Stderr, "  get-config")
	fmt.Fprintln(os.Stderr, "  get-file remoteFile localFile")
	fmt.Fprintln(os.Stderr, "  poll")
	fmt.Fprintln(os.Stderr, "  push-image image")
	fmt.Fprintln(os.Stderr, "  set-config")
}

type commandFunc func(*srpc.Client, []string)

type subcommand struct {
	command string
	numArgs int
	cmdFunc commandFunc
}

var subcommands = []subcommand{
	{"fetch", 1, fetchSubcommand},
	{"get-config", 0, getConfigSubcommand},
	{"get-file", 2, getFileSubcommand},
	{"poll", 0, pollSubcommand},
	{"push-image", 1, pushImageSubcommand},
	{"set-config", 0, setConfigSubcommand},
}

func main() {
	flag.Usage = printUsage
	flag.Parse()
	if flag.NArg() < 1 {
		printUsage()
		os.Exit(2)
	}
	if *triggersFile != "" && *triggersString != "" {
		fmt.Fprintln(os.Stderr,
			"Cannot specify both -triggersFile and -triggersString")
		os.Exit(2)
	}
	if err := setupclient.SetupTls(true); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	clientName := fmt.Sprintf("%s:%d", *subHostname, *subPortNum)
	client, err := srpc.DialHTTP("tcp", clientName, 0)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error dialing\t%s\n", err)
		os.Exit(1)
	}
	for _, subcommand := range subcommands {
		if flag.Arg(0) == subcommand.command {
			if flag.NArg()-1 != subcommand.numArgs {
				printUsage()
				os.Exit(2)
			}
			subcommand.cmdFunc(client, flag.Args()[1:])
			os.Exit(3)
		}
	}
	printUsage()
	os.Exit(2)
}
<commit_msg>Improve online help for subtool.<commit_after>package main

import (
	"flag"
	"fmt"
	"github.com/Symantec/Dominator/lib/constants"
	"github.com/Symantec/Dominator/lib/flagutil"
	"github.com/Symantec/Dominator/lib/srpc"
	"github.com/Symantec/Dominator/lib/srpc/setupclient"
	"os"
	"time"
)

var (
	computedFilesRoot = flag.String("computedFilesRoot", "",
		"Name of directory tree containing computed files")
	debug             = flag.Bool("debug", false, "Enable debug mode")
	deleteBeforeFetch = flag.Bool("deleteBeforeFetch", false,
		"If true, delete prior to Fetch rather than during Update")
	file = flag.String("file", "",
		"Name of file to write encoded data to")
	filterFile = flag.String("filterFile", "",
		"Replacement filter file to apply when pushing image")
	imageServerHostname = flag.String("imageServerHostname", "localhost",
		"Hostname of image server")
	imageServerPortNum = flag.Uint("imageServerPortNum",
		constants.ImageServerPortNumber,
		"Port number of image server")
	interval = flag.Uint("interval", 1,
		"Seconds to sleep between Polls")
	networkSpeedPercent = flag.Uint("networkSpeedPercent",
		constants.DefaultNetworkSpeedPercent,
		"Network speed as percentage of capacity")
	newConnection = flag.Bool("newConnection", false,
		"If true, (re)open a connection for each Poll")
	numPolls = flag.Int("numPolls", 1,
		"The number of polls to run (infinite: < 0)")
	objectServerHostname = flag.String("objectServerHostname", "localhost",
		"Hostname of image server")
	objectServerPortNum = flag.Uint("objectServerPortNum",
		constants.ImageServerPortNumber,
		"Port number of image server")
	scanExcludeList  flagutil.StringList = constants.ScanExcludeList
	scanSpeedPercent                     = flag.Uint("scanSpeedPercent",
		constants.DefaultScanSpeedPercent,
		"Scan speed as percentage of capacity")
	shortPoll = flag.Bool("shortPoll", false,
		"If true, perform a short poll which does not request image or object data")
	showTimes = flag.Bool("showTimes", false,
		"If true, show time taken for some operations")
	subHostname = flag.String("subHostname", "localhost", "Hostname of sub")
	subPortNum  = flag.Uint("subPortNum", constants.SubPortNumber,
		"Port number of sub")
	timeout = flag.Duration("timeout", 15*time.Minute,
		"timeout for push-image retry loop")
	triggersFile = flag.String("triggersFile", "",
		"Replacement triggers file to apply when pushing image")
	triggersString = flag.String("triggersString", "",
		"Replacement triggers string to apply when pushing image (ignored if triggersFile is set)")
	wait = flag.Uint("wait", 0, "Seconds to sleep after last Poll")
)

func init() {
	flag.Var(&scanExcludeList, "scanExcludeList",
		"Comma separated list of patterns to exclude from scanning")
}

func printUsage() {
	fmt.Fprintln(os.Stderr,
		"Usage: subtool [flags...] fetch|get-config|poll|set-config")
	fmt.Fprintln(os.Stderr, "Common flags:")
	flag.PrintDefaults()
	fmt.Fprintln(os.Stderr, "Commands:")
	fmt.Fprintln(os.Stderr, "  fetch hashesFile")
	fmt.Fprintln(os.Stderr, "  get-config")
	fmt.Fprintln(os.Stderr, "  get-file remoteFile localFile")
	fmt.Fprintln(os.Stderr, "  poll")
	fmt.Fprintln(os.Stderr, "  push-image image")
	fmt.Fprintln(os.Stderr, "  set-config")
}

type commandFunc func(*srpc.Client, []string)

type subcommand struct {
	command string
	numArgs int
	cmdFunc commandFunc
}

var subcommands = []subcommand{
	{"fetch", 1, fetchSubcommand},
	{"get-config", 0, getConfigSubcommand},
	{"get-file", 2, getFileSubcommand},
	{"poll", 0, pollSubcommand},
	{"push-image", 1, pushImageSubcommand},
	{"set-config", 0, setConfigSubcommand},
}

func main() {
	flag.Usage = printUsage
	flag.Parse()
	if flag.NArg() < 1 {
		printUsage()
		os.Exit(2)
	}
	if *triggersFile != "" && *triggersString != "" {
		fmt.Fprintln(os.Stderr,
			"Cannot specify both -triggersFile and -triggersString")
		os.Exit(2)
	}
	if err := setupclient.SetupTls(true); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	clientName := fmt.Sprintf("%s:%d", *subHostname, *subPortNum)
	client, err := srpc.DialHTTP("tcp", clientName, 0)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error dialing\t%s\n", err)
		os.Exit(1)
	}
	for _, subcommand := range subcommands {
		if flag.Arg(0) == subcommand.command {
			if flag.NArg()-1 != subcommand.numArgs {
				printUsage()
				os.Exit(2)
			}
			subcommand.cmdFunc(client, flag.Args()[1:])
			os.Exit(3)
		}
	}
	printUsage()
	os.Exit(2)
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"fmt"
	"log"
	"net"
	"net/http"
	_ "net/http/pprof"
	"os"

	metainfo "github.com/nsf/libtorgo/torrent"

	"bitbucket.org/anacrolix/go.torrent"
)

var (
	downloadDir = flag.String("downloadDir", "", "directory to store download torrent data")
	testPeer    = flag.String("testPeer", "", "bootstrap peer address")
	profAddr    = flag.String("profAddr", "", "http serve address")
)

func init() {
	log.SetFlags(log.LstdFlags | log.Lshortfile)
	flag.Parse()
}

func main() {
	if *profAddr != "" {
		go http.ListenAndServe(*profAddr, nil)
	}
	client := torrent.Client{
		DataDir: *downloadDir,
	}
	client.Start()
	defer client.Stop()
	if flag.NArg() == 0 {
		fmt.Fprintln(os.Stderr, "no torrents specified")
		return
	}
	for _, arg := range flag.Args() {
		metaInfo, err := metainfo.LoadFromFile(arg)
		if err != nil {
			log.Fatal(err)
		}
		err = client.AddTorrent(metaInfo)
		if err != nil {
			log.Fatal(err)
		}
		client.PrioritizeDataRegion(torrent.BytesInfoHash(metaInfo.InfoHash), 0, 999999999)
		err = client.AddPeers(torrent.BytesInfoHash(metaInfo.InfoHash), func() []torrent.Peer {
			if *testPeer == "" {
				return nil
			}
			addr, err := net.ResolveTCPAddr("tcp", *testPeer)
			if err != nil {
				log.Fatal(err)
			}
			return []torrent.Peer{{
				IP:   addr.IP,
				Port: addr.Port,
			}}
		}())
		if err != nil {
			log.Fatal(err)
		}
	}
	client.WaitAll()
}
<commit_msg>Add -listenAddr and actually listen in ./cmd/torrent<commit_after>package main

import (
	"flag"
	"fmt"
	"log"
	"net"
	"net/http"
	_ "net/http/pprof"
	"os"

	metainfo "github.com/nsf/libtorgo/torrent"

	"bitbucket.org/anacrolix/go.torrent"
)

var (
	downloadDir = flag.String("downloadDir", "", "directory to store download torrent data")
	testPeer    = flag.String("testPeer", "", "bootstrap peer address")
	profAddr    = flag.String("profAddr", "", "http serve address")
	// TODO: Check the default torrent listen port.
	listenAddr = flag.String("listenAddr", ":6882", "incoming connection address")
)

func init() {
	log.SetFlags(log.LstdFlags | log.Lshortfile)
	flag.Parse()
}

func makeListener() net.Listener {
	l, err := net.Listen("tcp", *listenAddr)
	if err != nil {
		log.Fatal(err)
	}
	return l
}

func main() {
	if *profAddr != "" {
		go http.ListenAndServe(*profAddr, nil)
	}
	client := torrent.Client{
		DataDir:  *downloadDir,
		Listener: makeListener(),
	}
	client.Start()
	defer client.Stop()
	if flag.NArg() == 0 {
		fmt.Fprintln(os.Stderr, "no torrents specified")
		return
	}
	for _, arg := range flag.Args() {
		metaInfo, err := metainfo.LoadFromFile(arg)
		if err != nil {
			log.Fatal(err)
		}
		err = client.AddTorrent(metaInfo)
		if err != nil {
			log.Fatal(err)
		}
		client.PrioritizeDataRegion(torrent.BytesInfoHash(metaInfo.InfoHash), 0, 999999999)
		err = client.AddPeers(torrent.BytesInfoHash(metaInfo.InfoHash), func() []torrent.Peer {
			if *testPeer == "" {
				return nil
			}
			addr, err := net.ResolveTCPAddr("tcp", *testPeer)
			if err != nil {
				log.Fatal(err)
			}
			return []torrent.Peer{{
				IP:   addr.IP,
				Port: addr.Port,
			}}
		}())
		if err != nil {
			log.Fatal(err)
		}
	}
	client.WaitAll()
}
<|endoftext|>


<commit_before>package cmd

import (
	"context"
	"fmt"
	"log"
	"os"
	"os/exec"
	"runtime"

	"github.com/fatih/color"
	"github.com/gobuffalo/buffalo/generators/assets/webpack"
	rg "github.com/gobuffalo/buffalo/generators/refresh"
	"github.com/markbates/refresh/refresh"
	"github.com/spf13/cobra"
)

// devCmd represents the dev command
var devCmd = &cobra.Command{
	Use:   "dev",
	Short: "Runs your Buffalo app in 'development' mode",
	Long: `Runs your Buffalo app in 'development' mode.
This includes rebuilding your application when files change.
This behavior can be changed in your .buffalo.dev.yml file.`,
	Run: func(c *cobra.Command, args []string) {
		if runtime.GOOS == "windows" {
			color.NoColor = true
		}
		defer func() {
			msg := "There was a problem starting the dev server, Please review the troubleshooting docs: %s\n"
			cause := "Unknown"
			if r := recover(); r != nil {
				if err, ok := r.(error); ok {
					cause = err.Error()
				}
			}
			fmt.Printf(msg, cause)
		}()
		os.Setenv("GO_ENV", "development")
		ctx := context.Background()
		ctx, cancelFunc := context.WithCancel(ctx)
		go func() {
			err := startDevServer(ctx)
			if err != nil {
				cancelFunc()
				log.Fatal(err)
			}
		}()
		go func() {
			err := startWebpack(ctx)
			if err != nil {
				cancelFunc()
				log.Fatal(err)
			}
		}()
		// wait for the ctx to finish
		<-ctx.Done()
	},
}

func startWebpack(ctx context.Context) error {
	cfgFile := "./webpack.config.js"
	_, err := os.Stat(cfgFile)
	if err != nil {
		// there's no webpack, so don't do anything
		return nil
	}
	cmd := exec.Command(webpack.BinPath, "--watch")
	cmd.Stdin = os.Stdin
	cmd.Stderr = os.Stderr
	cmd.Stdout = os.Stdout
	return cmd.Run()
}

func startDevServer(ctx context.Context) error {
	cfgFile := "./.buffalo.dev.yml"
	_, err := os.Stat(cfgFile)
	if err != nil {
		g, err := rg.New()
		if err != nil {
			return err
		}
		err = g.Run("./", map[string]interface{}{
			"name": "buffalo",
		})
	}
	c := &refresh.Configuration{}
	err = c.Load(cfgFile)
	if err != nil {
		return err
	}
	r := refresh.NewWithContext(c, ctx)
	return r.Start()
}

func init() {
	decorate("dev", devCmd)
	RootCmd.AddCommand(devCmd)
}
<commit_msg>added a -d flag to buffalo dev to run the app with delve<commit_after>package cmd

import (
	"context"
	"fmt"
	"log"
	"os"
	"os/exec"
	"runtime"

	"github.com/fatih/color"
	"github.com/gobuffalo/buffalo/generators/assets/webpack"
	rg "github.com/gobuffalo/buffalo/generators/refresh"
	"github.com/markbates/refresh/refresh"
	"github.com/spf13/cobra"
)

var devOptions = struct {
	Debug bool
}{}

// devCmd represents the dev command
var devCmd = &cobra.Command{
	Use:   "dev",
	Short: "Runs your Buffalo app in 'development' mode",
	Long: `Runs your Buffalo app in 'development' mode.
This includes rebuilding your application when files change.
This behavior can be changed in your .buffalo.dev.yml file.`,
	Run: func(c *cobra.Command, args []string) {
		if runtime.GOOS == "windows" {
			color.NoColor = true
		}
		defer func() {
			msg := "There was a problem starting the dev server, Please review the troubleshooting docs: %s\n"
			cause := "Unknown"
			if r := recover(); r != nil {
				if err, ok := r.(error); ok {
					cause = err.Error()
				}
			}
			fmt.Printf(msg, cause)
		}()
		os.Setenv("GO_ENV", "development")
		ctx := context.Background()
		ctx, cancelFunc := context.WithCancel(ctx)
		go func() {
			err := startDevServer(ctx)
			if err != nil {
				cancelFunc()
				log.Fatal(err)
			}
		}()
		go func() {
			err := startWebpack(ctx)
			if err != nil {
				cancelFunc()
				log.Fatal(err)
			}
		}()
		// wait for the ctx to finish
		<-ctx.Done()
	},
}

func startWebpack(ctx context.Context) error {
	cfgFile := "./webpack.config.js"
	_, err := os.Stat(cfgFile)
	if err != nil {
		// there's no webpack, so don't do anything
		return nil
	}
	cmd := exec.Command(webpack.BinPath, "--watch")
	cmd.Stdin = os.Stdin
	cmd.Stderr = os.Stderr
	cmd.Stdout = os.Stdout
	return cmd.Run()
}

func startDevServer(ctx context.Context) error {
	cfgFile := "./.buffalo.dev.yml"
	_, err := os.Stat(cfgFile)
	if err != nil {
		g, err := rg.New()
		if err != nil {
			return err
		}
		err = g.Run("./", map[string]interface{}{
			"name": "buffalo",
		})
	}
	c := &refresh.Configuration{}
	err = c.Load(cfgFile)
	if err != nil {
		return err
	}
	c.Debug = devOptions.Debug
	r := refresh.NewWithContext(c, ctx)
	return r.Start()
}

func init() {
	devCmd.Flags().BoolVarP(&devOptions.Debug, "debug", "d", false, "use delve to debug the app")
	decorate("dev", devCmd)
	RootCmd.AddCommand(devCmd)
}
<|endoftext|>


<commit_before>package main

import (
	"crypto/tls"
	"crypto/x509"
	"fmt"
	"github.com/dotcloud/docker/archive"
	"io"
	"io/ioutil"
	"net/http"
	"os"
)

var VERSION = "0.1.0"

func usage() {
	fmt.Printf("Usage: %s https://example.org/download.tar.bz2\n", os.Args[0])
	os.Exit(1)
}

func version() {
    fmt.Println(VERSION)
    os.Exit(0)
}

func tls_config() *tls.Config {
	pool := x509.NewCertPool()
	cert, err := ioutil.ReadFile("./.cert")
	if err != nil {
		fmt.Printf("Failed to load certificate -- %s\n", err)
		os.Exit(1)
	}
	pool.AppendCertsFromPEM(cert)
	return &tls.Config{RootCAs: pool}
}

func download(url string) io.Reader {
	transport := &http.Transport{TLSClientConfig: tls_config()}
	client := &http.Client{Transport: transport}
	response, err := client.Get(url)
	if err != nil {
		fmt.Printf("Failed to download %s -- %s\n", url, err)
		os.Exit(1)
	}
	fmt.Printf("Downloaded %s\n", url)
	return response.Body
}

func main() {
	if len(os.Args) < 2 {
		usage()
	}
    if os.Args[1] == "-v" {
        version()
    }
	err := archive.Untar(download(os.Args[1]), "/", nil)
	if err != nil {
		fmt.Printf("Failed to extract -- %s\n", err)
	}
	fmt.Println("Successfully extracted archive")
}
<commit_msg>gofmt tabs<commit_after>package main

import (
	"crypto/tls"
	"crypto/x509"
	"fmt"
	"github.com/dotcloud/docker/archive"
	"io"
	"io/ioutil"
	"net/http"
	"os"
)

var VERSION = "0.1.0"

func usage() {
	fmt.Printf("Usage: %s https://example.org/download.tar.bz2\n", os.Args[0])
	os.Exit(1)
}

func version() {
	fmt.Println(VERSION)
	os.Exit(0)
}

func tls_config() *tls.Config {
	pool := x509.NewCertPool()
	cert, err := ioutil.ReadFile("./.cert")
	if err != nil {
		fmt.Printf("Failed to load certificate -- %s\n", err)
		os.Exit(1)
	}
	pool.AppendCertsFromPEM(cert)
	return &tls.Config{RootCAs: pool}
}

func download(url string) io.Reader {
	transport := &http.Transport{TLSClientConfig: tls_config()}
	client := &http.Client{Transport: transport}
	response, err := client.Get(url)
	if err != nil {
		fmt.Printf("Failed to download %s -- %s\n", url, err)
		os.Exit(1)
	}
	fmt.Printf("Downloaded %s\n", url)
	return response.Body
}

func main() {
	if len(os.Args) < 2 {
		usage()
	}
	if os.Args[1] == "-v" {
		version()
	}
	err := archive.Untar(download(os.Args[1]), "/", nil)
	if err != nil {
		fmt.Printf("Failed to extract -- %s\n", err)
	}
	fmt.Println("Successfully extracted archive")
}
<|endoftext|>


<commit_before>package api

import (
	"bytes"
	"crypto/sha256"
	"crypto/tls"
	"crypto/x509"
	"log"
	"net"
	"net/http"
	"time"
)

type Dialer func(network, addr string) (net.Conn, error)

func newDialer(fingerprint []byte, skipCAVerification bool) Dialer {
	return func(network, addr string) (net.Conn, error) {
		c, err := tls.Dial(network, addr, &tls.Config{InsecureSkipVerify: skipCAVerification})
		if err != nil {
			return c, err
		}
		connstate := c.ConnectionState()
		keyPinValid := false
		for _, peercert := range connstate.PeerCertificates {
			der, err := x509.MarshalPKIXPublicKey(peercert.PublicKey)
			hash := sha256.Sum256(der)
			// log.Println(peercert.Issuer)
			// log.Printf("%#v\n\n", hash)
			if err != nil {
				log.Fatal(err)
			}
			if bytes.Compare(hash[0:], fingerprint) == 0 {
				// log.Println("Pinned Key found")
				keyPinValid = true
			}
		}
		if keyPinValid == false {
			log.Fatal("TLS Public Key could not be verified!")
		}
		return c, nil
	}
}

func defaultHTTPClient() *http.Client {
	fingerprint := []byte{0x5b, 0x15, 0x6c, 0xda, 0x7b, 0xc3, 0xd, 0x8b, 0xe8, 0x88, 0x57, 0x75, 0xbc, 0x30, 0xc1, 0x84, 0x18, 0x75, 0x6f, 0x2d, 0x3b, 0x81, 0x91, 0xff, 0x34, 0x10, 0xda, 0x13, 0x4a, 0x83, 0x23, 0x9d}

	tr := &http.Transport{
		MaxIdleConns:       10,
		IdleConnTimeout:    30 * time.Second,
		DisableCompression: true,
		DialTLS:            newDialer(fingerprint, false),
	}

	return &http.Client{
		Transport: tr,
		Timeout:   2 * time.Minute,
	}
}

type Client struct {
	HTTPClient  *http.Client
	APIEndpoint string
	JWT         string
	UserAgent   string
}

func NewClient(apiEndpoint string, jwtToken string) *Client {
	return &Client{
		HTTPClient:  defaultHTTPClient(),
		APIEndpoint: apiEndpoint,
		JWT:         jwtToken,
		UserAgent:   "StormForger CLI (https://stormforger.com)",
	}
}

// FIXME would be nice to return a struct
//       where we see the status and in case of
//       success also the email address of the
//       authenticated user (useful) to check
//       if we are authenticated as the correct user
func (c *Client) Ping() (bool, error) {
	req, err := http.NewRequest("GET", c.APIEndpoint+"/authenticated_ping", nil)

	// TODO how to set these on all requests?
	req.Header.Add("Authorization", "Bearer "+c.JWT)
	req.Header.Set("User-Agent", c.UserAgent)

	resp, err := c.HTTPClient.Do(req)
	if err != nil {
		return false, err
	}

	defer resp.Body.Close()

	return (resp.Status == "200"), nil
}
<commit_msg>fix ping<commit_after>package api

import (
	"bytes"
	"crypto/sha256"
	"crypto/tls"
	"crypto/x509"
	"log"
	"net"
	"net/http"
	"time"
)

type Dialer func(network, addr string) (net.Conn, error)

func newDialer(fingerprint []byte, skipCAVerification bool) Dialer {
	return func(network, addr string) (net.Conn, error) {
		c, err := tls.Dial(network, addr, &tls.Config{InsecureSkipVerify: skipCAVerification})
		if err != nil {
			return c, err
		}
		connstate := c.ConnectionState()
		keyPinValid := false
		for _, peercert := range connstate.PeerCertificates {
			der, err := x509.MarshalPKIXPublicKey(peercert.PublicKey)
			hash := sha256.Sum256(der)
			// log.Println(peercert.Issuer)
			// log.Printf("%#v\n\n", hash)
			if err != nil {
				log.Fatal(err)
			}
			if bytes.Compare(hash[0:], fingerprint) == 0 {
				// log.Println("Pinned Key found")
				keyPinValid = true
			}
		}
		if keyPinValid == false {
			log.Fatal("TLS Public Key could not be verified!")
		}
		return c, nil
	}
}

func defaultHTTPClient() *http.Client {
	fingerprint := []byte{0x5b, 0x15, 0x6c, 0xda, 0x7b, 0xc3, 0xd, 0x8b, 0xe8, 0x88, 0x57, 0x75, 0xbc, 0x30, 0xc1, 0x84, 0x18, 0x75, 0x6f, 0x2d, 0x3b, 0x81, 0x91, 0xff, 0x34, 0x10, 0xda, 0x13, 0x4a, 0x83, 0x23, 0x9d}

	tr := &http.Transport{
		MaxIdleConns:       10,
		IdleConnTimeout:    30 * time.Second,
		DisableCompression: true,
		DialTLS:            newDialer(fingerprint, false),
	}

	return &http.Client{
		Transport: tr,
		Timeout:   2 * time.Minute,
	}
}

type Client struct {
	HTTPClient  *http.Client
	APIEndpoint string
	JWT         string
	UserAgent   string
}

func NewClient(apiEndpoint string, jwtToken string) *Client {
	return &Client{
		HTTPClient:  defaultHTTPClient(),
		APIEndpoint: apiEndpoint,
		JWT:         jwtToken,
		UserAgent:   "StormForger CLI (https://stormforger.com)",
	}
}

// FIXME would be nice to return a struct
//       where we see the status and in case of
//       success also the email address of the
//       authenticated user (useful) to check
//       if we are authenticated as the correct user
func (c *Client) Ping() (bool, error) {
	req, err := http.NewRequest("GET", c.APIEndpoint+"/authenticated_ping", nil)

	// TODO how to set these on all requests?
	req.Header.Add("Authorization", "Bearer "+c.JWT)
	req.Header.Set("User-Agent", c.UserAgent)

	resp, err := c.HTTPClient.Do(req)
	if err != nil {
		return false, err
	}

	defer resp.Body.Close()

	return (resp.StatusCode == 200), nil
}
<|endoftext|>


<commit_before>package cloudflare

const (
	E_UNAUTH     string = "E_UNAUTH"
	E_INVLDINPUT string = "E_INVLDINPUT"
	E_MAXAPI     string = "E_MAXAPI"
)

type Root struct {
	Response string      `json:"response"`
	Result   interface{} `json:"result"`
	Message  string      `json:"msg"`
}

/* Strutures for Stats Request */

type Stats struct {
	TimeZero float64      `json:"timeZero"`
	TimeEnd  float64      `json:"timeEnd"`
	Count    int          `json:"count"`
	HasMore  bool         `json:"has_more"`
	Objs     []StatsChild `json:"objs"`
}

type StatsChild struct {
	CachedServerTime    float64        `json:"cachedServerTime"`
	CachedExpryTime     float64        `json:"cachedExpryTime"`
	TrafficBreakdown    []TrafficChild `json:"trafficBreakdown"`
	BandwidthServed     ServedStats    `json:"bandwidthServed"`
	requestsServed      ServedStats    `json:"requestsServed"`
	ProZone             bool           `json:"pro_zone"`
	PageLoadTime        string         `json:"pageLoadTime"`
	CurrentServerTime   float64        `json:"currentServerTime"`
	Interval            int            `json:"interval"`
	ZoneCDate           float64        `json:"zoneCDate"`
	UserSecuritySetting string         `json:"userSecuritySetting"`
	DevMode             int            `json:dev_mode`
	Ipv46               int            `json:"ipv46"`
	Ob                  int            `json:"op"`
	CacheLevel          string         `json:"cache_lvl"`
}

type TrafficChild struct {
	Pageviews TrafficChildStats `json:"pagesviews"`
	Uniques   TrafficChildStats `json:"uniques"`
}

type TrafficChildStats struct {
	Regular int `json:"regular"`
	Threat  int `json:"threat"`
	Crawler int `json:"crawler"`
}

type ServedStats struct {
	Cloudflare float64 `json:"cloudflare"`
	User       float64 `json:"user"`
}

/* End Strutures for Stats Request */

/* Strutures for Zone Multi Load Request */

type ZonesLoad struct {
	HasMore bool       `json:"has_more"`
	Count   int        `json:"count"`
	Objs    []ZoneLoad `json:"objs"`
}

type ZoneLoad struct {
	ZoneId          string           `json:"zone_id"`
	UserId          string           `json:"user_id"`
	ZoneName        string           `json:"zone_name"`
	DisplayName     string           `json:"display_name"`
	ZoneStatus      string           `json:"zone_status"`
	ZoneMode        string           `json:"zone_mode"`
	HostId          string           `json:"host_id"`
	ZoneType        string           `json:"zone_type"`
	HostPubName     string           `json:"host_pubname"`
	HostWebsite     string           `json:"host_website"`
	Vtxt            string           `json:"vtxt"`
	Fqdns           []string         `json:"fqdns"`
	Step            string           `json:"step"`
	ZoneStatusClass string           `json:"zone_status_class"`
	ZoneStatusDesc  string           `json:"zone_status_desc"`
	NsVanityMap     []interface{}    `json:"ns_vanity_map"`
	OrigRegistrar   string           `json:"orig_registrar"`
	OrigDnshost     string           `json:"orig_dnshost"`
	OrigNsnames     string           `json:"orig_dnshost"`
	Props           ZoneLoadProperty `json:"props"`
	ConfirmCode     []Codes          `json:"confirm_code"`
	Allow           []string         `json:"allow"`
}

type ZoneLoadProperty struct {
	DnsCName       int `json:"dns_cname"`
	DnsPartner     int `json:"dns_partner"`
	DnsAnonPartner int `json:"dns_anon_partner"`
	Pro            int `json:"pro"`
	ExpiredPro     int `json:"exprired_pro"`
	ProSub         int `json:"pro_sub"`
	Ssl            int `json:"ssl"`
	ExpiredSsl     int `json:"expired_ssl"`
	ExpriredRsPro  int `json:"expired_rs_pro"`
	ResellerPro    int `reseller_pro`
	ForceInteral   int `json:"force_interal"`
	SslNeeded      int `json:"ssl_needed"`
	AlexaRank      int `json:"alexa_rank"`
}

type Codes struct {
	ZoneDeactivate string `json:"zone_deactivate"`
	ZoneDevModel   string `json:"zone_dev_mode1"`
}

/* End Strutures for Zone Multi Load Request */

/* Strutures for Dns Records Request */

type DnsRecords struct {
	HasMore bool     `json:"has_more"`
	Count   int      `json:"count"`
	Objs    []Record `json:"objs"`
}

type Record struct {
	Id             string      `json:"rec_id"`
	Tag            string      `json:"rec_tag"`
	ZoneName       string      `json:"zone_name"`
	Name           string      `json:"name"`
	DisplayName    string      `json:"display_name"`
	Type           string      `json:"type"`
	Prio           string      `json:"prio"`
	Content        string      `json:"content"`
	DisplayContent string      `json:"display_content"`
	Ttl            string      `json:"ttl"`
	TtlCeil        int         `json:"ttl_ceil"`
	SslId          string      `json:"ssl_id"`
	SslStatus      string      `json:"ssl_status"`
	SslExpiresOn   string      `json:"ssl_expires_on"`
	AutoTtl        int         `json:"auto_ttl"`
	ServiceMode    string      `json:"service_mode"`
	Props          DnsProperty `json:"props"`
}

type DnsProperty struct {
	Proxiable   int `json:"proxiable"`
	CloudOn     int `json:"cloud_on"`
	CfOpen      int `json:"cf_open"`
	Ssl         int `json:"ssl"`
	ExpiredSsl  int `json:"expired_ssl"`
	ExpiringSsl int `json:"expiring_ssl"`
	PendingSsl  int `json:"pending_ssl"`
}

/* End Strutures for Dns Records Request */

/* Strutures for Zones Check Request */

type ZonesCheck struct {
	Zones map[string]int `json:"zones"`
}

/* END Strutures for Zones Check Request */

/* Strutures for Zones Ips Request */

type ZoneIps struct {
	Ips Ip `json:"ips"`
}

type Ip struct {
	Ip             string  `json:"ip"`
	Classification string  `json:"classification"`
	Hits           string  `json:"hits"`
	Latitude       float64 `json:"latitude"`
	Longitude      float64 `json:"longitude"`
	ZoneName       string  `json:"zone_name"`
}

/* END Strutures for Zones Ips Request */

/* Strutures for Zone Settings Request */

type ZoneSettings struct {
	Result []Settings `json:"result"`
}

type Settings struct {
	UserSecuritySetting string `json:"userSecuritySetting"`
	DevMode             int    `json:"dev_mode"`
	Ipv46               int    `json:"ipv46"`
	Ob                  int    `json:"ob"`
	CacheLevel          string `json:"cache_lvl"`
	OutboundLinks       string `json:"outboundLinks"`
	Async               string `json:"async"`
	Bic                 string `json:"bic"`
	ChlTtl              string `json:"chl_ttl"`
	ExpTtl              string `json:"exp_ttl"`
	FpurgeTs            string `json:"fpurge_ts"`
	Hotling             string `json:"hotlink"`
	Img                 string `json:"img"`
	Lazy                string `json:"lazy"`
	Minify              string `json:"minify"`
	Outlink             string `json:"outlink"`
	Preload             string `json:"preload"`
	S404                string `json:"s404"`
	SecLvl              string `json:"sec_lvl"`
	Sdpy                string `json:"sdpy"`
	Ssl                 string `json:"ssl"`
	WafProfile          string `json:"waf_profile"`
}

/* END Strutures for Zone Settings Request */

type SecLevel struct {
	Zone ZoneLoad `json:"zone"`
}

type CacheLevel struct {
	Zone ZoneLoad `json:"zone"`
}

type DevMode struct {
	ExpiresOn float64  `json:"expires_on"`
	Zone      ZoneLoad `json:"zone"`
}

type PurgeCache struct {
	FpurgeTs float64  `json:"fpurge_ts"`
	Zone     ZoneLoad `json:"zone"`
}

type PurgeFile struct {
	Vtxt_match string `json:"vtxt_match"`
	Url        string `json:"url"`
}

type ModIp struct {
	Ip     string `json:"ip"`
	Action string `json:"action"`
}

type NewRecord struct {
	Rec Record `json:"obj"`
}

type EditRecord struct {
	Rec Record `json:"obj"`
}
<commit_msg>Fix structures related to api<commit_after>package cloudflare

const (
	E_UNAUTH     string = "E_UNAUTH"
	E_INVLDINPUT string = "E_INVLDINPUT"
	E_MAXAPI     string = "E_MAXAPI"
)

type Root struct {
	Response string `json:"response"`
	Result   string `json:"result"`
	Message  string `json:"msg"`
}

/* Strutures for Stats Request */

type RootStats struct {
	Response Stats  `json:"response"`
	Result   string `json:"result"`
	Message  string `json:"msg"`
}

type Stats struct {
	TimeZero float64      `json:"timeZero"`
	TimeEnd  float64      `json:"timeEnd"`
	Count    int          `json:"count"`
	HasMore  bool         `json:"has_more"`
	Objs     []StatsChild `json:"objs"`
}

type StatsChild struct {
	CachedServerTime    float64        `json:"cachedServerTime"`
	CachedExpryTime     float64        `json:"cachedExpryTime"`
	TrafficBreakdown    []TrafficChild `json:"trafficBreakdown"`
	BandwidthServed     ServedStats    `json:"bandwidthServed"`
	requestsServed      ServedStats    `json:"requestsServed"`
	ProZone             bool           `json:"pro_zone"`
	PageLoadTime        string         `json:"pageLoadTime"`
	CurrentServerTime   float64        `json:"currentServerTime"`
	Interval            int            `json:"interval"`
	ZoneCDate           float64        `json:"zoneCDate"`
	UserSecuritySetting string         `json:"userSecuritySetting"`
	DevMode             int            `json:dev_mode`
	Ipv46               int            `json:"ipv46"`
	Ob                  int            `json:"op"`
	CacheLevel          string         `json:"cache_lvl"`
}

type TrafficChild struct {
	Pageviews TrafficChildStats `json:"pagesviews"`
	Uniques   TrafficChildStats `json:"uniques"`
}

type TrafficChildStats struct {
	Regular int `json:"regular"`
	Threat  int `json:"threat"`
	Crawler int `json:"crawler"`
}

type ServedStats struct {
	Cloudflare float64 `json:"cloudflare"`
	User       float64 `json:"user"`
}

/* End Strutures for Stats Request */

/* Strutures for Zone Multi Load Request */

type RootZones struct {
	Response Zones  `json:"response"`
	Result   string `json:"result"`
	Message  string `json:"msg"`
}

type Zones struct {
	Zones ZonesLoad `json:"zones"`
}

type ZonesLoad struct {
	HasMore bool       `json:"has_more"`
	Count   int        `json:"count"`
	Objs    []ZoneLoad `json:"objs"`
}

type ZoneLoad struct {
	ZoneId          string            `json:"zone_id"`
	UserId          string            `json:"user_id"`
	ZoneName        string            `json:"zone_name"`
	DisplayName     string            `json:"display_name"`
	ZoneStatus      string            `json:"zone_status"`
	ZoneMode        string            `json:"zone_mode"`
	HostId          string            `json:"host_id"`
	ZoneType        string            `json:"zone_type"`
	HostPubName     string            `json:"host_pubname"`
	HostWebsite     string            `json:"host_website"`
	Vtxt            string            `json:"vtxt"`
	Fqdns           []string          `json:"fqdns"`
	Step            string            `json:"step"`
	ZoneStatusClass string            `json:"zone_status_class"`
	ZoneStatusDesc  string            `json:"zone_status_desc"`
	NsVanityMap     []interface{}     `json:"ns_vanity_map"`
	OrigRegistrar   string            `json:"orig_registrar"`
	OrigDnshost     string            `json:"orig_dnshost"`
	OrigNsnames     string            `json:"orig_dnshost"`
	Props           ZoneLoadProperty  `json:"props"`
	ConfirmCode     map[string]string `json:"confirm_code"`
	Allow           []string          `json:"allow"`
}

type ZoneLoadProperty struct {
	DnsCName       int `json:"dns_cname"`
	DnsPartner     int `json:"dns_partner"`
	DnsAnonPartner int `json:"dns_anon_partner"`
	Pro            int `json:"pro"`
	ExpiredPro     int `json:"exprired_pro"`
	ProSub         int `json:"pro_sub"`
	Ssl            int `json:"ssl"`
	ExpiredSsl     int `json:"expired_ssl"`
	ExpriredRsPro  int `json:"expired_rs_pro"`
	ResellerPro    int `reseller_pro`
	ForceInteral   int `json:"force_interal"`
	SslNeeded      int `json:"ssl_needed"`
	AlexaRank      int `json:"alexa_rank"`
}

type Codes struct {
	ZoneDeactivate string `json:"zone_deactivate"`
	ZoneDevModel   string `json:"zone_dev_mode1"`
}

/* End Strutures for Zone Multi Load Request */

/* Strutures for Dns Records Request */

type RootDnsRecords struct {
	Response DnsRecords `json:"response"`
	Result   string     `json:"result"`
	Message  string     `json:"msg"`
}

type DnsRecords struct {
	HasMore bool     `json:"has_more"`
	Count   int      `json:"count"`
	Objs    []Record `json:"objs"`
}

type Record struct {
	Id             string      `json:"rec_id"`
	Tag            string      `json:"rec_tag"`
	ZoneName       string      `json:"zone_name"`
	Name           string      `json:"name"`
	DisplayName    string      `json:"display_name"`
	Type           string      `json:"type"`
	Prio           string      `json:"prio"`
	Content        string      `json:"content"`
	DisplayContent string      `json:"display_content"`
	Ttl            string      `json:"ttl"`
	TtlCeil        int         `json:"ttl_ceil"`
	SslId          string      `json:"ssl_id"`
	SslStatus      string      `json:"ssl_status"`
	SslExpiresOn   string      `json:"ssl_expires_on"`
	AutoTtl        int         `json:"auto_ttl"`
	ServiceMode    string      `json:"service_mode"`
	Props          DnsProperty `json:"props"`
}

type DnsProperty struct {
	Proxiable   int `json:"proxiable"`
	CloudOn     int `json:"cloud_on"`
	CfOpen      int `json:"cf_open"`
	Ssl         int `json:"ssl"`
	ExpiredSsl  int `json:"expired_ssl"`
	ExpiringSsl int `json:"expiring_ssl"`
	PendingSsl  int `json:"pending_ssl"`
}

/* End Strutures for Dns Records Request */

/* Strutures for Zones Check Request */

type RootZonesCheck struct {
	Response ZonesCheck `json:"response"`
	Result   string     `json:"result"`
	Message  string     `json:"msg"`
}

type ZonesCheck struct {
	Zones map[string]int `json:"zones"`
}

/* END Strutures for Zones Check Request */

/* Strutures for Zones Ips Request */

type RootZoneIps struct {
	Response ZoneIps `json:"response"`
	Result   string  `json:"result"`
	Message  string  `json:"msg"`
}

type ZoneIps struct {
	Ips Ip `json:"ips"`
}

type Ip struct {
	Ip             string  `json:"ip"`
	Classification string  `json:"classification"`
	Hits           string  `json:"hits"`
	Latitude       float64 `json:"latitude"`
	Longitude      float64 `json:"longitude"`
	ZoneName       string  `json:"zone_name"`
}

/* END Strutures for Zones Ips Request */

/* Strutures for Zone Settings Request */

type RootZoneSettings struct {
	Response ZoneSettings `json:"response"`
	Result   string       `json:"result"`
	Message  string       `json:"msg"`
}

type ZoneSettings struct {
	Result []Settings `json:"result"`
}

type Settings struct {
	UserSecuritySetting string `json:"userSecuritySetting"`
	DevMode             int    `json:"dev_mode"`
	Ipv46               int    `json:"ipv46"`
	Ob                  int    `json:"ob"`
	CacheLevel          string `json:"cache_lvl"`
	OutboundLinks       string `json:"outboundLinks"`
	Async               string `json:"async"`
	Bic                 string `json:"bic"`
	ChlTtl              string `json:"chl_ttl"`
	ExpTtl              string `json:"exp_ttl"`
	FpurgeTs            string `json:"fpurge_ts"`
	Hotling             string `json:"hotlink"`
	Img                 string `json:"img"`
	Lazy                string `json:"lazy"`
	Minify              string `json:"minify"`
	Outlink             string `json:"outlink"`
	Preload             string `json:"preload"`
	S404                string `json:"s404"`
	SecLvl              string `json:"sec_lvl"`
	Sdpy                string `json:"sdpy"`
	Ssl                 string `json:"ssl"`
	WafProfile          string `json:"waf_profile"`
}

/* END Strutures for Zone Settings Request */

type RootSecLevel struct {
	Response SecLevel `json:"response"`
	Result   string   `json:"result"`
	Message  string   `json:"msg"`
}

type SecLevel struct {
	Zone ZoneLoad `json:"zone"`
}

/**/

type RootCacheLevel struct {
	Response CacheLevel `json:"response"`
	Result   string     `json:"result"`
	Message  string     `json:"msg"`
}

type CacheLevel struct {
	Zone ZoneLoad `json:"zone"`
}

/**/

type RootDevMode struct {
	Response DevMode `json:"response"`
	Result   string  `json:"result"`
	Message  string  `json:"msg"`
}

type DevMode struct {
	ExpiresOn float64  `json:"expires_on"`
	Zone      ZoneLoad `json:"zone"`
}

/**/

type RootPurgeCache struct {
	Response PurgeCache `json:"response"`
	Result   string     `json:"result"`
	Message  string     `json:"msg"`
}

type PurgeCache struct {
	FpurgeTs float64  `json:"fpurge_ts"`
	Zone     ZoneLoad `json:"zone"`
}

/**/

type RootPurgeFile struct {
	Response PurgeFile `json:"response"`
	Result   string    `json:"result"`
	Message  string    `json:"msg"`
}

type PurgeFile struct {
	Vtxt_match string `json:"vtxt_match"`
	Url        string `json:"url"`
}

/**/

type RootModIp struct {
	Response ModIp  `json:"response"`
	Result   string `json:"result"`
	Message  string `json:"msg"`
}

type ModIp struct {
	Ip     string `json:"ip"`
	Action string `json:"action"`
}

/**/

type RootNewRecord struct {
	Response NewRecord `json:"response"`
	Result   string    `json:"result"`
	Message  string    `json:"msg"`
}

type NewRecord struct {
	Rec Record `json:"obj"`
}

/**/

type RootEditRecord struct {
	Response EditRecord `json:"response"`
	Result   string     `json:"result"`
	Message  string     `json:"msg"`
}

type EditRecord struct {
	Rec Record `json:"obj"`
}

/**/

type RootLookupIp struct {
	Response LookupIp `json:"response"`
	Result   string   `json:"result"`
	Message  string   `json:"msg"`
}

type LookupIp struct {
	Ip string `json:"[IP]"`
}
<|endoftext|>