<commit_before>// Copyright 2014 Kelsey Hightower. All rights reserved.
// Use of this source code is governed by a BSD-style
// license found in the LICENSE file.

// Package memkv implements an in-memory key/value store.
package memkv

import (
	"errors"
	"path"
	"path/filepath"
	"sort"
	"strings"
	"sync"
)

var ErrNotExist = errors.New("key does not exist")
var ErrNoMatch = errors.New("no keys match")

// A Store represents an in-memory key-value store safe for
// concurrent access.
type Store struct {
	FuncMap map[string]interface{}
	sync.RWMutex
	m map[string]KVPair
}

// New creates and initializes a new Store.
func New() Store {
	s := Store{m: make(map[string]KVPair)}
	s.FuncMap = map[string]interface{}{
		"exists": s.Exists,
		"ls":     s.List,
		"lsdir":  s.ListDir,
		"get":    s.Get,
		"gets":   s.GetAll,
		"getv":   s.GetValue,
		"getvs":  s.GetAllValues,
	}
	return s
}

// Delete deletes the KVPair associated with key.
func (s Store) Del(key string) {
	s.Lock()
	delete(s.m, key)
	s.Unlock()
}

// Exists checks for the existence of key in the store.
func (s Store) Exists(key string) bool {
	_, err := s.Get(key)
	if err != nil {
		return false
	}
	return true
}

// Get gets the KVPair associated with key. If there is no KVPair
// associated with key, Get returns KVPair{}, ErrNotExist.
func (s Store) Get(key string) (KVPair, error) {
	s.RLock()
	kv, ok := s.m[key]
	s.RUnlock()
	if !ok {
		return kv, ErrNotExist
	}
	return kv, nil
}

// GetValue gets the value associated with key. If there are no values
// associated with key, GetValue returns "", ErrNotExist.
func (s Store) GetValue(key string) (string, error) {
	kv, err := s.Get(key)
	if err != nil {
		return "", err
	}
	return kv.Value, nil
}

// GetAll returns a KVPair for all nodes with keys matching pattern.
// The syntax of patterns is the same as in filepath.Match.
func (s Store) GetAll(pattern string) (KVPairs, error) {
	ks := make(KVPairs, 0)
	s.RLock()
	defer s.RUnlock()
	for _, kv := range s.m {
		m, err := filepath.Match(pattern, kv.Key)
		if err != nil {
			return nil, err
		}
		if m {
			ks = append(ks, kv)
		}
	}
	if len(ks) == 0 {
		return ks, nil
	}
	sort.Sort(ks)
	return ks, nil
}

func (s Store) GetAllValues(pattern string) ([]string, error) {
	vs := make([]string, 0)
	ks, err := s.GetAll(pattern)
	if err != nil {
		return vs, err
	}
	if len(ks) == 0 {
		return vs, nil
	}
	for _, kv := range ks {
		vs = append(vs, kv.Value)
	}
	sort.Strings(vs)
	return vs, nil
}

func (s Store) List(filePath string) []string {
	vs := make([]string, 0)
	m := make(map[string]bool)
	s.RLock()
	defer s.RUnlock()
	for _, kv := range s.m {
		if kv.Key == filePath {
			m[path.Base(kv.Key)] = true
			continue
		}
		if strings.HasPrefix(kv.Key, filePath) {
			m[strings.Split(stripKey(kv.Key, filePath), "/")[0]] = true
		}
	}
	for k := range m {
		vs = append(vs, k)
	}
	sort.Strings(vs)
	return vs
}

func (s Store) ListDir(filePath string) []string {
	vs := make([]string, 0)
	m := make(map[string]bool)
	s.RLock()
	defer s.RUnlock()
	for _, kv := range s.m {
		if strings.HasPrefix(kv.Key, filePath) {
			items := strings.Split(stripKey(kv.Key, filePath), "/")
			if len(items) < 2 {
				continue
			}
			m[items[0]] = true
		}
	}
	for k := range m {
		vs = append(vs, k)
	}
	sort.Strings(vs)
	return vs
}

// Set sets the KVPair entry associated with key to value.
func (s Store) Set(key string, value string) {
	s.Lock()
	s.m[key] = KVPair{key, value}
	s.Unlock()
}

func (s Store) Purge() {
	s.Lock()
	for k := range s.m {
		delete(s.m, k)
	}
	s.Unlock()
}

func stripKey(key, prefix string) string {
	return strings.TrimPrefix(strings.TrimPrefix(key, prefix), "/")
}
<commit_msg>Add getvd method to specify default value with getv<commit_after>// Copyright 2014 Kelsey Hightower. All rights reserved.
// Use of this source code is governed by a BSD-style
// license found in the LICENSE file.

// Package memkv implements an in-memory key/value store.
package memkv

import (
	"errors"
	"path"
	"path/filepath"
	"sort"
	"strings"
	"sync"
)

var ErrNotExist = errors.New("key does not exist")
var ErrNoMatch = errors.New("no keys match")

// A Store represents an in-memory key-value store safe for
// concurrent access.
type Store struct {
	FuncMap map[string]interface{}
	sync.RWMutex
	m map[string]KVPair
}

// New creates and initializes a new Store.
func New() Store {
	s := Store{m: make(map[string]KVPair)}
	s.FuncMap = map[string]interface{}{
		"exists": s.Exists,
		"ls":     s.List,
		"lsdir":  s.ListDir,
		"get":    s.Get,
		"gets":   s.GetAll,
		"getv":   s.GetValue,
		"getvd":   s.GetValueIfExists,
		"getvs":  s.GetAllValues,
	}
	return s
}

// Delete deletes the KVPair associated with key.
func (s Store) Del(key string) {
	s.Lock()
	delete(s.m, key)
	s.Unlock()
}

// Exists checks for the existence of key in the store.
func (s Store) Exists(key string) bool {
	_, err := s.Get(key)
	if err != nil {
		return false
	}
	return true
}

// Get gets the KVPair associated with key. If there is no KVPair
// associated with key, Get returns KVPair{}, ErrNotExist.
func (s Store) Get(key string) (KVPair, error) {
	s.RLock()
	kv, ok := s.m[key]
	s.RUnlock()
	if !ok {
		return kv, ErrNotExist
	}
	return kv, nil
}

// GetValue gets the value associated with key. If there are no values
// associated with key, GetValue returns "", ErrNotExist.
func (s Store) GetValue(key string) (string, error) {
	kv, err := s.Get(key)
	if err != nil {
		return "", err
	}
	return kv.Value, nil
}

// GetValueIfExists gets the value associated with key. If there are no values
// associated with key, GetValue returns default value.
func (s Store) GetValueIfExists(key string, defaultValue string) (string) {
	kv, err := s.Get(key)
	if err != nil {
		return defaultValue
	}
	return kv.Value
}

// GetAll returns a KVPair for all nodes with keys matching pattern.
// The syntax of patterns is the same as in filepath.Match.
func (s Store) GetAll(pattern string) (KVPairs, error) {
	ks := make(KVPairs, 0)
	s.RLock()
	defer s.RUnlock()
	for _, kv := range s.m {
		m, err := filepath.Match(pattern, kv.Key)
		if err != nil {
			return nil, err
		}
		if m {
			ks = append(ks, kv)
		}
	}
	if len(ks) == 0 {
		return ks, nil
	}
	sort.Sort(ks)
	return ks, nil
}

func (s Store) GetAllValues(pattern string) ([]string, error) {
	vs := make([]string, 0)
	ks, err := s.GetAll(pattern)
	if err != nil {
		return vs, err
	}
	if len(ks) == 0 {
		return vs, nil
	}
	for _, kv := range ks {
		vs = append(vs, kv.Value)
	}
	sort.Strings(vs)
	return vs, nil
}

func (s Store) List(filePath string) []string {
	vs := make([]string, 0)
	m := make(map[string]bool)
	s.RLock()
	defer s.RUnlock()
	for _, kv := range s.m {
		if kv.Key == filePath {
			m[path.Base(kv.Key)] = true
			continue
		}
		if strings.HasPrefix(kv.Key, filePath) {
			m[strings.Split(stripKey(kv.Key, filePath), "/")[0]] = true
		}
	}
	for k := range m {
		vs = append(vs, k)
	}
	sort.Strings(vs)
	return vs
}

func (s Store) ListDir(filePath string) []string {
	vs := make([]string, 0)
	m := make(map[string]bool)
	s.RLock()
	defer s.RUnlock()
	for _, kv := range s.m {
		if strings.HasPrefix(kv.Key, filePath) {
			items := strings.Split(stripKey(kv.Key, filePath), "/")
			if len(items) < 2 {
				continue
			}
			m[items[0]] = true
		}
	}
	for k := range m {
		vs = append(vs, k)
	}
	sort.Strings(vs)
	return vs
}

// Set sets the KVPair entry associated with key to value.
func (s Store) Set(key string, value string) {
	s.Lock()
	s.m[key] = KVPair{key, value}
	s.Unlock()
}

func (s Store) Purge() {
	s.Lock()
	for k := range s.m {
		delete(s.m, k)
	}
	s.Unlock()
}

func stripKey(key, prefix string) string {
	return strings.TrimPrefix(strings.TrimPrefix(key, prefix), "/")
}
<|endoftext|>


<commit_before>package main

import (
	"github.com/dvrkps/dojo/initfuncs/aaa"
	"github.com/dvrkps/dojo/initfuncs/zzz"
)

var global string

func init() {
	println("main/main: top init")
	setGlobal("mit")
}

func main() {
	println("main")
	setGlobal("mm")
	aaa.Aaa()
	zzz.Zzz()
}

func init() {
	println("main/main: bottom init")
	setGlobal("mib")
}

func setGlobal(s string) {
	old := global
	global = s
	println("new: ", global, " old: ", old)
}
<commit_msg>initfuncs: add default value to global<commit_after>package main

import (
	"github.com/dvrkps/dojo/initfuncs/aaa"
	"github.com/dvrkps/dojo/initfuncs/zzz"
)

var global = "default"

func init() {
	println("main/main: top init")
	setGlobal("mit")
}

func main() {
	println("main")
	setGlobal("mm")
	aaa.Aaa()
	zzz.Zzz()
}

func init() {
	println("main/main: bottom init")
	setGlobal("mib")
}

func setGlobal(s string) {
	old := global
	global = s
	println("new: ", global, " old: ", old)
}
<|endoftext|>


<commit_before>package kubernetes

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

	"github.com/docker/cli/cli/command"
	composev1beta1 "github.com/docker/cli/kubernetes/client/clientset_generated/clientset/typed/compose/v1beta1"
	"github.com/docker/docker/pkg/homedir"
	"github.com/spf13/cobra"
	restclient "k8s.io/client-go/rest"
	"k8s.io/client-go/tools/clientcmd"
)

// KubeCli holds kubernetes specifics (client, namespace) with the command.Cli
type KubeCli struct {
	command.Cli
	kubeConfig    *restclient.Config
	kubeNamespace string
}

// WrapCli wraps command.Cli with kubernetes specifics
func WrapCli(dockerCli command.Cli, cmd *cobra.Command) (*KubeCli, error) {
	var err error
	cli := &KubeCli{
		Cli:           dockerCli,
		kubeNamespace: "default",
	}
	if cmd.PersistentFlags().Changed("namespace") {
		cli.kubeNamespace, err = cmd.PersistentFlags().GetString("namespace")
		if err != nil {
			return nil, err
		}
	}
	kubeConfig := ""
	if cmd.PersistentFlags().Changed("kubeconfig") {
		kubeConfig, err = cmd.PersistentFlags().GetString("kubeconfig")
		if err != nil {
			return nil, err
		}
	}
	if kubeConfig == "" {
		if config := os.Getenv("KUBECONFIG"); config != "" {
			kubeConfig = config
		} else {
			kubeConfig = filepath.Join(homedir.Get(), ".kube/config")
		}
	}

	config, err := clientcmd.BuildConfigFromFlags("", kubeConfig)
	if err != nil {
		return nil, fmt.Errorf("Failed to load kubernetes configuration file '%s'", kubeConfig)
	}
	cli.kubeConfig = config

	return cli, nil
}

func (c *KubeCli) composeClient() (*Factory, error) {
	return NewFactory(c.kubeNamespace, c.kubeConfig)
}

func (c *KubeCli) stacks() (composev1beta1.StackInterface, error) {
	err := APIPresent(c.kubeConfig)
	if err != nil {
		return nil, err
	}

	clientSet, err := composev1beta1.NewForConfig(c.kubeConfig)
	if err != nil {
		return nil, err
	}

	return clientSet.Stacks(c.kubeNamespace), nil
}
<commit_msg>Using Flags instead of PersistentFlags, as Kubernetes flags seem not to be defined in the "persistent space".<commit_after>package kubernetes

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

	"github.com/docker/cli/cli/command"
	composev1beta1 "github.com/docker/cli/kubernetes/client/clientset_generated/clientset/typed/compose/v1beta1"
	"github.com/docker/docker/pkg/homedir"
	"github.com/spf13/cobra"
	restclient "k8s.io/client-go/rest"
	"k8s.io/client-go/tools/clientcmd"
)

// KubeCli holds kubernetes specifics (client, namespace) with the command.Cli
type KubeCli struct {
	command.Cli
	kubeConfig    *restclient.Config
	kubeNamespace string
}

// WrapCli wraps command.Cli with kubernetes specifics
func WrapCli(dockerCli command.Cli, cmd *cobra.Command) (*KubeCli, error) {
	var err error
	cli := &KubeCli{
		Cli:           dockerCli,
		kubeNamespace: "default",
	}
	if cmd.Flags().Changed("namespace") {
		cli.kubeNamespace, err = cmd.Flags().GetString("namespace")
		if err != nil {
			return nil, err
		}
	}
	kubeConfig := ""
	if cmd.Flags().Changed("kubeconfig") {
		kubeConfig, err = cmd.Flags().GetString("kubeconfig")
		if err != nil {
			return nil, err
		}
	}
	if kubeConfig == "" {
		if config := os.Getenv("KUBECONFIG"); config != "" {
			kubeConfig = config
		} else {
			kubeConfig = filepath.Join(homedir.Get(), ".kube/config")
		}
	}

	config, err := clientcmd.BuildConfigFromFlags("", kubeConfig)
	if err != nil {
		return nil, fmt.Errorf("Failed to load kubernetes configuration file '%s'", kubeConfig)
	}
	cli.kubeConfig = config

	return cli, nil
}

func (c *KubeCli) composeClient() (*Factory, error) {
	return NewFactory(c.kubeNamespace, c.kubeConfig)
}

func (c *KubeCli) stacks() (composev1beta1.StackInterface, error) {
	err := APIPresent(c.kubeConfig)
	if err != nil {
		return nil, err
	}

	clientSet, err := composev1beta1.NewForConfig(c.kubeConfig)
	if err != nil {
		return nil, err
	}

	return clientSet.Stacks(c.kubeNamespace), nil
}
<|endoftext|>


<commit_before>package rubyapp

import (
	"fmt"
	"path/filepath"
	"reflect"
	"sort"
	"testing"

	"github.com/hashicorp/otto/app"
	"github.com/hashicorp/otto/appfile"
)

func TestApp_impl(t *testing.T) {
	var _ app.App = new(App)
}

func TestAppImplicit(t *testing.T) {
	cases := []struct {
		Dir  string
		Deps []string
	}{
		{
			"implicit-none",
			nil,
		},

		{
			"implicit-redis",
			[]string{"github.com/hashicorp/otto/examples/redis"},
		},
	}

	for _, tc := range cases {
		errPrefix := fmt.Sprintf("In '%s': ", tc.Dir)

		// Build our context we send in
		var ctx app.Context
		ctx.Appfile = &appfile.File{Path: filepath.Join("./test-fixtures", tc.Dir, "Appfile")}

		// Test it!
		var a App
		f, err := a.Implicit(&ctx)
		if err != nil {
			t.Fatalf("%s: %s", errPrefix, err)
		}
		if (len(tc.Deps) == 0) != (f == nil) {
			// Complicated statement above but basically: should be nil if
			// we expected no deps, and should not be nil if we expect deps
			t.Fatalf("%s: deps: %#v\n\ninvalid file: %#v", errPrefix, tc.Deps, f)
		}
		if f == nil {
			continue
		}

		// Test the deps
		actual := make([]string, 0, len(f.Application.Dependencies))
		for _, dep := range f.Application.Dependencies {
			actual = append(actual, dep.Source)
		}

		// Sort the deps for determinism
		sort.Strings(actual)
		sort.Strings(tc.Deps)

		// Test
		if !reflect.DeepEqual(actual, tc.Deps) {
			t.Fatalf("%s\n\ngot: %#v\n\nexpected: %#v", errPrefix, actual, tc.Deps)
		}
	}
}
<commit_msg>app/ruby: style<commit_after>package rubyapp

import (
	"fmt"
	"path/filepath"
	"reflect"
	"sort"
	"testing"

	"github.com/hashicorp/otto/app"
	"github.com/hashicorp/otto/appfile"
)

func TestApp_impl(t *testing.T) {
	var _ app.App = new(App)
}

func TestAppImplicit(t *testing.T) {
	cases := []struct {
		Dir  string
		Deps []string
	}{
		{
			"implicit-none",
			nil,
		},

		{
			"implicit-redis",
			[]string{"github.com/hashicorp/otto/examples/redis"},
		},
	}

	for _, tc := range cases {
		errPrefix := fmt.Sprintf("In '%s': ", tc.Dir)

		// Build our context we send in
		var ctx app.Context
		ctx.Appfile = &appfile.File{Path: filepath.Join("./test-fixtures", tc.Dir, "Appfile")}

		// Get the implicit file
		var a App
		f, err := a.Implicit(&ctx)
		if err != nil {
			t.Fatalf("%s: %s", errPrefix, err)
		}
		if (len(tc.Deps) == 0) != (f == nil) {
			// Complicated statement above but basically: should be nil if
			// we expected no deps, and should not be nil if we expect deps
			t.Fatalf("%s: deps: %#v\n\ninvalid file: %#v", errPrefix, tc.Deps, f)
		}
		if f == nil {
			continue
		}

		// Build the deps we got and sort them for determinism
		actual := make([]string, 0, len(f.Application.Dependencies))
		for _, dep := range f.Application.Dependencies {
			actual = append(actual, dep.Source)
		}
		sort.Strings(actual)
		sort.Strings(tc.Deps)

		// Test
		if !reflect.DeepEqual(actual, tc.Deps) {
			t.Fatalf("%s\n\ngot: %#v\n\nexpected: %#v", errPrefix, actual, tc.Deps)
		}
	}
}
<|endoftext|>


<commit_before>package class

import (
    "sync"
    . "jvmgo/any"
    "jvmgo/util"
)

type ReentrantLock struct {
    holder      Any // *rtda.Thread
    holderLock  sync.Mutex
    lock        sync.Mutex
    lockCount   int
}

// thread: *rtda.Thread
func (self *ReentrantLock) Lock(thread Any) {
    self.holderLock.Lock()
    defer self.holderLock.Unlock()

    if self.holder == thread {
        self.lockCount++
    } else if self.holder == nil {
        self.holder = thread
        self.lockCount++
        self.lock.Lock()
    }
}

func (self *ReentrantLock) Unlock(thread Any) {
    self.holderLock.Lock()
    defer self.holderLock.Unlock()

    if self.holder == thread && self.lockCount > 0 {
        self.lockCount--
        if self.lockCount == 0 {
            self.holder = nil
            self.lock.Unlock()
        }
    } else {
        // todo
        util.Panicf("BAD ReentrantLock state! holder:%v lockCount:%v",
            self.holder, self.lockCount)
    }
}
<commit_msg>ReentrantLock...<commit_after>package class

import (
    "sync"
    . "jvmgo/any"
)

type ReentrantLock struct {
    holder      Any // *rtda.Thread
    holderLock  sync.Mutex
    lock        sync.Mutex
    lockCount   int
}

func (self *ReentrantLock) Lock(thread Any) {
    self.holderLock.Lock()
    if self.holder == thread {
        self.lockCount++
        self.holderLock.Unlock()
        return
    } else {
        self.holderLock.Unlock()
    }

    self.lock.Lock()
    self.holder = thread
    self.lockCount = 1
}

func (self *ReentrantLock) Unlock(thread Any) {
    self.holderLock.Lock()
    if self.holder == thread {
        self.lockCount--
        if self.lockCount == 0 {
            self.lock.Unlock()
        }
    }
    self.holderLock.Unlock()
}
<|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 certificates

import (
	"fmt"
	"io"

	"github.com/spf13/cobra"

	certificatesv1beta1 "k8s.io/api/certificates/v1beta1"
	"k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/cli-runtime/pkg/genericclioptions"
	"k8s.io/cli-runtime/pkg/printers"
	"k8s.io/cli-runtime/pkg/resource"
	certificatesv1beta1client "k8s.io/client-go/kubernetes/typed/certificates/v1beta1"
	cmdutil "k8s.io/kubectl/pkg/cmd/util"
	"k8s.io/kubectl/pkg/scheme"
	"k8s.io/kubectl/pkg/util/i18n"
	"k8s.io/kubectl/pkg/util/templates"
)

func NewCmdCertificate(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
	cmd := &cobra.Command{
		Use:                   "certificate SUBCOMMAND",
		DisableFlagsInUseLine: true,
		Short:                 i18n.T("Modify certificate resources."),
		Long:                  "Modify certificate resources.",
		Run: func(cmd *cobra.Command, args []string) {
			cmd.Help()
		},
	}

	cmd.AddCommand(NewCmdCertificateApprove(f, ioStreams))
	cmd.AddCommand(NewCmdCertificateDeny(f, ioStreams))

	return cmd
}

type CertificateOptions struct {
	resource.FilenameOptions

	PrintFlags *genericclioptions.PrintFlags
	PrintObj   printers.ResourcePrinterFunc

	csrNames    []string
	outputStyle string

	clientSet certificatesv1beta1client.CertificatesV1beta1Interface
	builder   *resource.Builder

	genericclioptions.IOStreams
}

// NewCertificateOptions creates the options for certificate
func NewCertificateOptions(ioStreams genericclioptions.IOStreams) *CertificateOptions {
	return &CertificateOptions{
		PrintFlags: genericclioptions.NewPrintFlags("approved").WithTypeSetter(scheme.Scheme),
		IOStreams:  ioStreams,
	}
}

func (o *CertificateOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {
	o.csrNames = args
	o.outputStyle = cmdutil.GetFlagString(cmd, "output")

	printer, err := o.PrintFlags.ToPrinter()
	if err != nil {
		return err
	}

	o.PrintObj = func(obj runtime.Object, out io.Writer) error {
		return printer.PrintObj(obj, out)
	}

	o.builder = f.NewBuilder()

	clientConfig, err := f.ToRESTConfig()
	if err != nil {
		return err
	}
	o.clientSet, err = certificatesv1beta1client.NewForConfig(clientConfig)
	if err != nil {
		return err
	}

	return nil
}

func (o *CertificateOptions) Validate() error {
	if len(o.csrNames) < 1 && cmdutil.IsFilenameSliceEmpty(o.Filenames, o.Kustomize) {
		return fmt.Errorf("one or more CSRs must be specified as <name> or -f <filename>")
	}
	return nil
}

func NewCmdCertificateApprove(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
	o := NewCertificateOptions(ioStreams)

	cmd := &cobra.Command{
		Use:                   "approve (-f FILENAME | NAME)",
		DisableFlagsInUseLine: true,
		Short:                 i18n.T("Approve a certificate signing request"),
		Long: templates.LongDesc(`
		Approve a certificate signing request.

		kubectl certificate approve allows a cluster admin to approve a certificate
		signing request (CSR). This action tells a certificate signing controller to
		issue a certificate to the requestor with the attributes requested in the CSR.

		SECURITY NOTICE: Depending on the requested attributes, the issued certificate
		can potentially grant a requester access to cluster resources or to authenticate
		as a requested identity. Before approving a CSR, ensure you understand what the
		signed certificate can do.
		`),
		Run: func(cmd *cobra.Command, args []string) {
			cmdutil.CheckErr(o.Complete(f, cmd, args))
			cmdutil.CheckErr(o.Validate())
			cmdutil.CheckErr(o.RunCertificateApprove(cmdutil.GetFlagBool(cmd, "force")))
		},
	}

	o.PrintFlags.AddFlags(cmd)

	cmd.Flags().Bool("force", false, "Update the CSR even if it is already approved.")
	cmdutil.AddFilenameOptionFlags(cmd, &o.FilenameOptions, "identifying the resource to update")

	return cmd
}

func (o *CertificateOptions) RunCertificateApprove(force bool) error {
	return o.modifyCertificateCondition(o.builder, o.clientSet, force, func(csr *certificatesv1beta1.CertificateSigningRequest) (*certificatesv1beta1.CertificateSigningRequest, bool) {
		var alreadyApproved bool
		for _, c := range csr.Status.Conditions {
			if c.Type == certificatesv1beta1.CertificateApproved {
				alreadyApproved = true
			}
		}
		if alreadyApproved {
			return csr, true
		}
		csr.Status.Conditions = append(csr.Status.Conditions, certificatesv1beta1.CertificateSigningRequestCondition{
			Type:           certificatesv1beta1.CertificateApproved,
			Reason:         "KubectlApprove",
			Message:        "This CSR was approved by kubectl certificate approve.",
			LastUpdateTime: metav1.Now(),
		})
		return csr, false
	})
}

func NewCmdCertificateDeny(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
	o := NewCertificateOptions(ioStreams)

	cmd := &cobra.Command{
		Use:                   "deny (-f FILENAME | NAME)",
		DisableFlagsInUseLine: true,
		Short:                 i18n.T("Deny a certificate signing request"),
		Long: templates.LongDesc(`
		Deny a certificate signing request.

		kubectl certificate deny allows a cluster admin to deny a certificate
		signing request (CSR). This action tells a certificate signing controller to
		not to issue a certificate to the requestor.
		`),
		Run: func(cmd *cobra.Command, args []string) {
			cmdutil.CheckErr(o.Complete(f, cmd, args))
			cmdutil.CheckErr(o.Validate())
			cmdutil.CheckErr(o.RunCertificateDeny(cmdutil.GetFlagBool(cmd, "force")))
		},
	}

	o.PrintFlags.AddFlags(cmd)

	cmd.Flags().Bool("force", false, "Update the CSR even if it is already denied.")
	cmdutil.AddFilenameOptionFlags(cmd, &o.FilenameOptions, "identifying the resource to update")

	return cmd
}

func (o *CertificateOptions) RunCertificateDeny(force bool) error {
	return o.modifyCertificateCondition(o.builder, o.clientSet, force, func(csr *certificatesv1beta1.CertificateSigningRequest) (*certificatesv1beta1.CertificateSigningRequest, bool) {
		var alreadyDenied bool
		for _, c := range csr.Status.Conditions {
			if c.Type == certificatesv1beta1.CertificateDenied {
				alreadyDenied = true
			}
		}
		if alreadyDenied {
			return csr, true
		}
		csr.Status.Conditions = append(csr.Status.Conditions, certificatesv1beta1.CertificateSigningRequestCondition{
			Type:           certificatesv1beta1.CertificateDenied,
			Reason:         "KubectlDeny",
			Message:        "This CSR was denied by kubectl certificate deny.",
			LastUpdateTime: metav1.Now(),
		})
		return csr, false
	})
}

func (o *CertificateOptions) modifyCertificateCondition(builder *resource.Builder, clientSet certificatesv1beta1client.CertificatesV1beta1Interface, force bool, modify func(csr *certificatesv1beta1.CertificateSigningRequest) (*certificatesv1beta1.CertificateSigningRequest, bool)) error {
	var found int
	r := builder.
		WithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).
		ContinueOnError().
		FilenameParam(false, &o.FilenameOptions).
		ResourceNames("certificatesigningrequest", o.csrNames...).
		RequireObject(true).
		Flatten().
		Latest().
		Do()
	err := r.Visit(func(info *resource.Info, err error) error {
		if err != nil {
			return err
		}
		for i := 0; ; i++ {
			csr := info.Object.(*certificatesv1beta1.CertificateSigningRequest)
			csr, hasCondition := modify(csr)
			if !hasCondition || force {
				csr, err = clientSet.CertificateSigningRequests().UpdateApproval(csr)
				if errors.IsConflict(err) && i < 10 {
					if err := info.Get(); err != nil {
						return err
					}
					continue
				}
				if err != nil {
					return err
				}
			}
			break
		}
		found++

		return o.PrintObj(info.Object, o.Out)
	})
	if found == 0 {
		fmt.Fprintf(o.Out, "No resources found\n")
	}
	return err
}
<commit_msg>Kubectl certificate signing: fix certificate deny message (#84400)<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 certificates

import (
	"fmt"
	"io"

	"github.com/spf13/cobra"

	certificatesv1beta1 "k8s.io/api/certificates/v1beta1"
	"k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/cli-runtime/pkg/genericclioptions"
	"k8s.io/cli-runtime/pkg/printers"
	"k8s.io/cli-runtime/pkg/resource"
	certificatesv1beta1client "k8s.io/client-go/kubernetes/typed/certificates/v1beta1"
	cmdutil "k8s.io/kubectl/pkg/cmd/util"
	"k8s.io/kubectl/pkg/scheme"
	"k8s.io/kubectl/pkg/util/i18n"
	"k8s.io/kubectl/pkg/util/templates"
)

func NewCmdCertificate(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
	cmd := &cobra.Command{
		Use:                   "certificate SUBCOMMAND",
		DisableFlagsInUseLine: true,
		Short:                 i18n.T("Modify certificate resources."),
		Long:                  "Modify certificate resources.",
		Run: func(cmd *cobra.Command, args []string) {
			cmd.Help()
		},
	}

	cmd.AddCommand(NewCmdCertificateApprove(f, ioStreams))
	cmd.AddCommand(NewCmdCertificateDeny(f, ioStreams))

	return cmd
}

type CertificateOptions struct {
	resource.FilenameOptions

	PrintFlags *genericclioptions.PrintFlags
	PrintObj   printers.ResourcePrinterFunc

	csrNames    []string
	outputStyle string

	clientSet certificatesv1beta1client.CertificatesV1beta1Interface
	builder   *resource.Builder

	genericclioptions.IOStreams
}

// NewCertificateOptions creates the options for certificate
func NewCertificateOptions(ioStreams genericclioptions.IOStreams, operation string) *CertificateOptions {
	return &CertificateOptions{
		PrintFlags: genericclioptions.NewPrintFlags(operation).WithTypeSetter(scheme.Scheme),
		IOStreams:  ioStreams,
	}
}

func (o *CertificateOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {
	o.csrNames = args
	o.outputStyle = cmdutil.GetFlagString(cmd, "output")

	printer, err := o.PrintFlags.ToPrinter()
	if err != nil {
		return err
	}

	o.PrintObj = func(obj runtime.Object, out io.Writer) error {
		return printer.PrintObj(obj, out)
	}

	o.builder = f.NewBuilder()

	clientConfig, err := f.ToRESTConfig()
	if err != nil {
		return err
	}
	o.clientSet, err = certificatesv1beta1client.NewForConfig(clientConfig)
	if err != nil {
		return err
	}

	return nil
}

func (o *CertificateOptions) Validate() error {
	if len(o.csrNames) < 1 && cmdutil.IsFilenameSliceEmpty(o.Filenames, o.Kustomize) {
		return fmt.Errorf("one or more CSRs must be specified as <name> or -f <filename>")
	}
	return nil
}

func NewCmdCertificateApprove(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
	o := NewCertificateOptions(ioStreams, "approved")

	cmd := &cobra.Command{
		Use:                   "approve (-f FILENAME | NAME)",
		DisableFlagsInUseLine: true,
		Short:                 i18n.T("Approve a certificate signing request"),
		Long: templates.LongDesc(`
		Approve a certificate signing request.

		kubectl certificate approve allows a cluster admin to approve a certificate
		signing request (CSR). This action tells a certificate signing controller to
		issue a certificate to the requestor with the attributes requested in the CSR.

		SECURITY NOTICE: Depending on the requested attributes, the issued certificate
		can potentially grant a requester access to cluster resources or to authenticate
		as a requested identity. Before approving a CSR, ensure you understand what the
		signed certificate can do.
		`),
		Run: func(cmd *cobra.Command, args []string) {
			cmdutil.CheckErr(o.Complete(f, cmd, args))
			cmdutil.CheckErr(o.Validate())
			cmdutil.CheckErr(o.RunCertificateApprove(cmdutil.GetFlagBool(cmd, "force")))
		},
	}

	o.PrintFlags.AddFlags(cmd)

	cmd.Flags().Bool("force", false, "Update the CSR even if it is already approved.")
	cmdutil.AddFilenameOptionFlags(cmd, &o.FilenameOptions, "identifying the resource to update")

	return cmd
}

func (o *CertificateOptions) RunCertificateApprove(force bool) error {
	return o.modifyCertificateCondition(o.builder, o.clientSet, force, func(csr *certificatesv1beta1.CertificateSigningRequest) (*certificatesv1beta1.CertificateSigningRequest, bool) {
		var alreadyApproved bool
		for _, c := range csr.Status.Conditions {
			if c.Type == certificatesv1beta1.CertificateApproved {
				alreadyApproved = true
			}
		}
		if alreadyApproved {
			return csr, true
		}
		csr.Status.Conditions = append(csr.Status.Conditions, certificatesv1beta1.CertificateSigningRequestCondition{
			Type:           certificatesv1beta1.CertificateApproved,
			Reason:         "KubectlApprove",
			Message:        "This CSR was approved by kubectl certificate approve.",
			LastUpdateTime: metav1.Now(),
		})
		return csr, false
	})
}

func NewCmdCertificateDeny(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
	o := NewCertificateOptions(ioStreams, "denied")

	cmd := &cobra.Command{
		Use:                   "deny (-f FILENAME | NAME)",
		DisableFlagsInUseLine: true,
		Short:                 i18n.T("Deny a certificate signing request"),
		Long: templates.LongDesc(`
		Deny a certificate signing request.

		kubectl certificate deny allows a cluster admin to deny a certificate
		signing request (CSR). This action tells a certificate signing controller to
		not to issue a certificate to the requestor.
		`),
		Run: func(cmd *cobra.Command, args []string) {
			cmdutil.CheckErr(o.Complete(f, cmd, args))
			cmdutil.CheckErr(o.Validate())
			cmdutil.CheckErr(o.RunCertificateDeny(cmdutil.GetFlagBool(cmd, "force")))
		},
	}

	o.PrintFlags.AddFlags(cmd)

	cmd.Flags().Bool("force", false, "Update the CSR even if it is already denied.")
	cmdutil.AddFilenameOptionFlags(cmd, &o.FilenameOptions, "identifying the resource to update")

	return cmd
}

func (o *CertificateOptions) RunCertificateDeny(force bool) error {
	return o.modifyCertificateCondition(o.builder, o.clientSet, force, func(csr *certificatesv1beta1.CertificateSigningRequest) (*certificatesv1beta1.CertificateSigningRequest, bool) {
		var alreadyDenied bool
		for _, c := range csr.Status.Conditions {
			if c.Type == certificatesv1beta1.CertificateDenied {
				alreadyDenied = true
			}
		}
		if alreadyDenied {
			return csr, true
		}
		csr.Status.Conditions = append(csr.Status.Conditions, certificatesv1beta1.CertificateSigningRequestCondition{
			Type:           certificatesv1beta1.CertificateDenied,
			Reason:         "KubectlDeny",
			Message:        "This CSR was denied by kubectl certificate deny.",
			LastUpdateTime: metav1.Now(),
		})
		return csr, false
	})
}

func (o *CertificateOptions) modifyCertificateCondition(builder *resource.Builder, clientSet certificatesv1beta1client.CertificatesV1beta1Interface, force bool, modify func(csr *certificatesv1beta1.CertificateSigningRequest) (*certificatesv1beta1.CertificateSigningRequest, bool)) error {
	var found int
	r := builder.
		WithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).
		ContinueOnError().
		FilenameParam(false, &o.FilenameOptions).
		ResourceNames("certificatesigningrequest", o.csrNames...).
		RequireObject(true).
		Flatten().
		Latest().
		Do()
	err := r.Visit(func(info *resource.Info, err error) error {
		if err != nil {
			return err
		}
		for i := 0; ; i++ {
			csr := info.Object.(*certificatesv1beta1.CertificateSigningRequest)
			csr, hasCondition := modify(csr)
			if !hasCondition || force {
				csr, err = clientSet.CertificateSigningRequests().UpdateApproval(csr)
				if errors.IsConflict(err) && i < 10 {
					if err := info.Get(); err != nil {
						return err
					}
					continue
				}
				if err != nil {
					return err
				}
			}
			break
		}
		found++

		return o.PrintObj(info.Object, o.Out)
	})
	if found == 0 {
		fmt.Fprintf(o.Out, "No resources found\n")
	}
	return err
}
<|endoftext|>


<commit_before>// Copyright 2015 The Prometheus 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 collector

import (
	"path"

	"github.com/prometheus/procfs"
	"gopkg.in/alecthomas/kingpin.v2"
)

var (
	// The path of the proc filesystem.
	procPath   = kingpin.Flag("path.procfs", "procfs mountpoint.").Default(procfs.DefaultMountPoint).String()
	sysPath    = kingpin.Flag("path.sysfs", "sysfs mountpoint.").Default("/sys").String()
	rootfsPath = kingpin.Flag("path.rootfs", "rootfs mountpoint.").Default("/").String()
)

func procFilePath(name string) string {
	return path.Join(*procPath, name)
}

func sysFilePath(name string) string {
	return path.Join(*sysPath, name)
}

func rootfsFilePath(name string) string {
	return path.Join(*rootfsPath, name)
}
<commit_msg>collector: use path/filepath for handling file paths (#1228)<commit_after>// Copyright 2015 The Prometheus 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 collector

import (
	"path/filepath"

	"github.com/prometheus/procfs"
	kingpin "gopkg.in/alecthomas/kingpin.v2"
)

var (
	// The path of the proc filesystem.
	procPath   = kingpin.Flag("path.procfs", "procfs mountpoint.").Default(procfs.DefaultMountPoint).String()
	sysPath    = kingpin.Flag("path.sysfs", "sysfs mountpoint.").Default("/sys").String()
	rootfsPath = kingpin.Flag("path.rootfs", "rootfs mountpoint.").Default("/").String()
)

func procFilePath(name string) string {
	return filepath.Join(*procPath, name)
}

func sysFilePath(name string) string {
	return filepath.Join(*sysPath, name)
}

func rootfsFilePath(name string) string {
	return filepath.Join(*rootfsPath, name)
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"encoding/json"
	"front/bindata"
	"github.com/gorilla/websocket"
	"github.com/skratchdot/open-golang/open"
	"io"
	"log"
	"mime"
	"net"
	"net/http"
	pathop "path"
	"strconv"
	"time"
)

//go:generate go-bindata -prefix "../../frontend/target/frontend.out" -pkg bindata -o ../bin/src/front/bindata/binasset.go ../../frontend/target/frontend.out/...

type data_struct struct {
	Data string
}

type push_event struct {
	Time int64
}

func makeTimestamp() int64 {
	return time.Now().UnixNano() / (int64(time.Millisecond) / int64(time.Nanosecond))
}

var eventmap = map[string](func(data_struct) data_struct){
	"buttons/send": eventButtonSend,
}

var upgrader = websocket.Upgrader{}

func eventButtonSend(data data_struct) data_struct {
	data.Data = data.Data + "! Hello from the Go side!"
	return data
}

func push_handler(rw http.ResponseWriter, req *http.Request) {
	rw.Header().Set("Content-Type", "application/json")
	rw.Header().Set("Cache-Control", "no-cache")
	var data push_event
	data.Time = makeTimestamp()
	js, err := json.Marshal(data)
	if err != nil {
		log.Panic(err)
	}
	rw.Write(js)
}

func static_handler(rw http.ResponseWriter, req *http.Request) {
	if req.Method == http.MethodGet {
		var path string = req.URL.Path
		if path == "" {
			path = "index.html"
		}

		if path == "__mailbox__" {
			push_handler(rw, req)
		} else {
			if bs, err := bindata.Asset(path); err != nil {
				log.Printf("Can't find resource : %s", path)
				rw.WriteHeader(http.StatusNotFound)
			} else {
				mime := mime.TypeByExtension(pathop.Ext(path))
				var reader = bytes.NewBuffer(bs)
				if mime == "" {
					mime = http.DetectContentType(bs)
				}
				log.Printf("Resource '%s' mime=%s", path, mime)
				rw.Header().Set("Content-Type", mime)
				rw.Header().Set("Cache-Control", "no-cache")
				io.Copy(rw, reader)
			}
		}
	} else if req.Method == http.MethodPost {
		path := req.URL.Path
		log.Printf("Incoming event : %s", path)

		eventfunc := eventmap[path]

		if eventfunc == nil {
			log.Panic("Can't find event processor for " + path)
		}

		decoder := json.NewDecoder(req.Body)

		var t data_struct
		err := decoder.Decode(&t)

		if err != nil {
			http.Error(rw, err.Error(), http.StatusInternalServerError)
			log.Print(err)
		} else {
			t = eventfunc(t)
			js, error := json.Marshal(t)
			if error != nil {
				http.Error(rw, error.Error(), http.StatusInternalServerError)
			} else {
				rw.Header().Set("Content-Type", "application/json")
				rw.Header().Set("Cache-Control", "no-cache")
				rw.Write(js)
			}
		}
	}
}

func findFreePort() (int, error) {
	addr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:0")
	if err != nil {
		return 0, err
	}

	l, err := net.ListenTCP("tcp", addr)
	if err != nil {
		return 0, err
	}
	defer l.Close()
	return l.Addr().(*net.TCPAddr).Port, nil
}

func main() {
	port, err := findFreePort()

	if err != nil {
		log.Fatal(err)
	}

	log.Printf("Application server address 127.0.0.1:%d", port)

	http.Handle("/", http.StripPrefix("/", http.HandlerFunc(static_handler)))
	listenStartBrowserAndServe("127.0.0.1:" + strconv.Itoa(port))
}

type tcpKeepAliveListener struct {
	*net.TCPListener
}

func listenStartBrowserAndServe(addr string) error {
	server := &http.Server{Addr: addr, Handler: nil}

	ln, err := net.Listen("tcp", addr)
	if err != nil {
		return err
	}

	err = open.Run("http://" + addr + "/index.html")
	if err != nil {
		return err
	}

	return server.Serve(tcpKeepAliveListener{ln.(*net.TCPListener)})

}
<commit_msg>removed extra code<commit_after>package main

import (
	"bytes"
	"encoding/json"
	"front/bindata"
	"github.com/skratchdot/open-golang/open"
	"io"
	"log"
	"mime"
	"net"
	"net/http"
	pathop "path"
	"strconv"
	"time"
)

//go:generate go-bindata -prefix "../../frontend/target/frontend.out" -pkg bindata -o ../bin/src/front/bindata/binasset.go ../../frontend/target/frontend.out/...

type data_struct struct {
	Data string
}

type push_event struct {
	Time int64
}

func makeTimestamp() int64 {
	return time.Now().UnixNano() / (int64(time.Millisecond) / int64(time.Nanosecond))
}

var eventmap = map[string](func(data_struct) data_struct){
	"buttons/send": eventButtonSend,
}

func eventButtonSend(data data_struct) data_struct {
	data.Data = data.Data + "! Hello from the Go side!"
	return data
}

func push_handler(rw http.ResponseWriter, req *http.Request) {
	rw.Header().Set("Content-Type", "application/json")
	rw.Header().Set("Cache-Control", "no-cache")
	var data push_event
	data.Time = makeTimestamp()
	js, err := json.Marshal(data)
	if err != nil {
		log.Panic(err)
	}
	rw.Write(js)
}

func static_handler(rw http.ResponseWriter, req *http.Request) {
	if req.Method == http.MethodGet {
		var path string = req.URL.Path
		if path == "" {
			path = "index.html"
		}

		if path == "__mailbox__" {
			push_handler(rw, req)
		} else {
			if bs, err := bindata.Asset(path); err != nil {
				log.Printf("Can't find resource : %s", path)
				rw.WriteHeader(http.StatusNotFound)
			} else {
				mime := mime.TypeByExtension(pathop.Ext(path))
				var reader = bytes.NewBuffer(bs)
				if mime == "" {
					mime = http.DetectContentType(bs)
				}
				log.Printf("Resource '%s' mime=%s", path, mime)
				rw.Header().Set("Content-Type", mime)
				rw.Header().Set("Cache-Control", "no-cache")
				io.Copy(rw, reader)
			}
		}
	} else if req.Method == http.MethodPost {
		path := req.URL.Path
		log.Printf("Incoming event : %s", path)

		eventfunc := eventmap[path]

		if eventfunc == nil {
			log.Panic("Can't find event processor for " + path)
		}

		decoder := json.NewDecoder(req.Body)

		var t data_struct
		err := decoder.Decode(&t)

		if err != nil {
			http.Error(rw, err.Error(), http.StatusInternalServerError)
			log.Print(err)
		} else {
			t = eventfunc(t)
			js, error := json.Marshal(t)
			if error != nil {
				http.Error(rw, error.Error(), http.StatusInternalServerError)
			} else {
				rw.Header().Set("Content-Type", "application/json")
				rw.Header().Set("Cache-Control", "no-cache")
				rw.Write(js)
			}
		}
	}
}

func findFreePort() (int, error) {
	addr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:0")
	if err != nil {
		return 0, err
	}

	l, err := net.ListenTCP("tcp", addr)
	if err != nil {
		return 0, err
	}
	defer l.Close()
	return l.Addr().(*net.TCPAddr).Port, nil
}

func main() {
	port, err := findFreePort()

	if err != nil {
		log.Fatal(err)
	}

	log.Printf("Application server address 127.0.0.1:%d", port)

	http.Handle("/", http.StripPrefix("/", http.HandlerFunc(static_handler)))
	listenStartBrowserAndServe("127.0.0.1:" + strconv.Itoa(port))
}

type tcpKeepAliveListener struct {
	*net.TCPListener
}

func listenStartBrowserAndServe(addr string) error {
	server := &http.Server{Addr: addr, Handler: nil}

	ln, err := net.Listen("tcp", addr)
	if err != nil {
		return err
	}

	err = open.Run("http://" + addr + "/index.html")
	if err != nil {
		return err
	}

	return server.Serve(tcpKeepAliveListener{ln.(*net.TCPListener)})

}
<|endoftext|>


<commit_before><commit_msg>languages/golang/blockchain-in-go/bolt_0.go<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2013-2016 Laurent Moussault. All rights reserved.
// Licensed under a simplified BSD license (see LICENSE file).

package main

//------------------------------------------------------------------------------

import (
	"log"
	"strings"

	"github.com/drakmaniso/glam"
	"github.com/drakmaniso/glam/color"
	. "github.com/drakmaniso/glam/geom"
	"github.com/drakmaniso/glam/geom/plane"
	"github.com/drakmaniso/glam/gfx"
)

//------------------------------------------------------------------------------

var pipeline gfx.Pipeline

type perVertex struct {
	position Vec2      `layout:"0"`
	color    color.RGB `layout:"1"`
}

type perObject struct {
	transform Mat3x4
}

var transform gfx.Buffer
var colorfulTriangle gfx.Buffer

//------------------------------------------------------------------------------

var vertexShader = strings.NewReader(`
#version 450 core

layout(location = 0) in vec2 Position;
layout(location = 1) in vec3 Color;

layout(std140, binding = 0) uniform PerObject {
	mat3 Transform;
} obj;

out gl_PerVertex {
	vec4 gl_Position;
};

out PerVertex {
	layout(location = 0) out vec3 Color;
} vert;

void main(void) {
	vec3 p = obj.Transform * vec3(Position, 1);
	gl_Position = vec4(p.xy, 0.5, 1);
	vert.Color = Color;
}
`)

var fragmentShader = strings.NewReader(`
#version 450 core

in PerVertex {
	layout(location = 0) in vec3 Color;
} vert;

out vec4 Color;

void main(void) {
	Color = vec4(vert.Color, 1);
}
`)

//------------------------------------------------------------------------------

func main() {
	log.SetFlags(log.Lshortfile)

	g := &game{}
	glam.Handler = g

	var err error

	// Setup the Pipeline
	vs, err := gfx.NewVertexShader(vertexShader)
	if err != nil {
		log.Fatal(err)
	}
	fs, err := gfx.NewFragmentShader(fragmentShader)
	if err != nil {
		log.Fatal(err)
	}
	pipeline, err = gfx.NewPipeline(vs, fs)
	if err != nil {
		log.Fatal(err)
	}
	err = pipeline.VertexFormat(0, perVertex{})
	if err != nil {
		log.Fatal(err)
	}
	pipeline.ClearColor(Vec4{0.9, 0.9, 0.9, 1.0})

	// Create the Uniform Buffer
	transform, err = gfx.NewBuffer(uintptr(64), gfx.DynamicStorage)
	if err != nil {
		log.Fatal(err)
	}

	// Create the Vertex Buffer
	data := []perVertex{
		{Vec2{0, 0.75}, color.RGB{R: 0.3, G: 0, B: 0.8}},
		{Vec2{-0.65, -0.465}, color.RGB{R: 0.8, G: 0.3, B: 0}},
		{Vec2{0.65, -0.465}, color.RGB{R: 0, G: 0.6, B: 0.2}},
	}
	colorfulTriangle, err = gfx.NewBuffer(data, 0)
	if err != nil {
		log.Fatal(err)
	}

	// Run the Game Loop
	err = glam.Run()
	if err != nil {
		log.Fatal(err)
	}
}

//------------------------------------------------------------------------------

type game struct{}

var angle float32

func (g *game) Update() {
	angle += 0.01
}

func (g *game) Draw() {
	pipeline.Bind()
	pipeline.UniformBuffer(0, transform)

	m := plane.Rotation(angle)
	t := perObject{
		transform: m.Mat3x4(),
	}
	transform.Update(&t, 0)

	pipeline.VertexBuffer(0, colorfulTriangle, 0)
	gfx.Draw(gfx.Triangles, 0, 3)
}

//------------------------------------------------------------------------------
<commit_msg>Add cube<commit_after>// Copyright (c) 2013-2016 Laurent Moussault. All rights reserved.
// Licensed under a simplified BSD license (see LICENSE file).

package main

//------------------------------------------------------------------------------

import (
	"log"
	"strings"

	"github.com/drakmaniso/glam"
	"github.com/drakmaniso/glam/color"
	. "github.com/drakmaniso/glam/geom"
	"github.com/drakmaniso/glam/geom/space"
	"github.com/drakmaniso/glam/gfx"
)

//------------------------------------------------------------------------------

var pipeline gfx.Pipeline

type perVertex struct {
	position Vec3      `layout:"0"`
	color    color.RGB `layout:"1"`
}

type perObject struct {
	transform Mat4
}

var transform gfx.Buffer
var colorfulTriangle gfx.Buffer

//------------------------------------------------------------------------------

var vertexShader = strings.NewReader(`
#version 450 core

layout(location = 0) in vec3 Position;
layout(location = 1) in vec3 Color;

layout(std140, binding = 0) uniform PerObject {
	mat4 Transform;
} obj;

out gl_PerVertex {
	vec4 gl_Position;
};

out PerVertex {
	layout(location = 0) out vec3 Color;
} vert;

void main(void) {
	gl_Position = obj.Transform * vec4(Position, 1);
	vert.Color = Color;
}
`)

var fragmentShader = strings.NewReader(`
#version 450 core

in PerVertex {
	layout(location = 0) in vec3 Color;
} vert;

out vec4 Color;

void main(void) {
	Color = vec4(vert.Color, 1);
}
`)

//------------------------------------------------------------------------------

func main() {
	log.SetFlags(log.Lshortfile)

	g := &game{}
	glam.Handler = g

	var err error

	// Setup the Pipeline
	vs, err := gfx.NewVertexShader(vertexShader)
	if err != nil {
		log.Fatal(err)
	}
	fs, err := gfx.NewFragmentShader(fragmentShader)
	if err != nil {
		log.Fatal(err)
	}
	pipeline, err = gfx.NewPipeline(vs, fs)
	if err != nil {
		log.Fatal(err)
	}
	err = pipeline.VertexFormat(0, perVertex{})
	if err != nil {
		log.Fatal(err)
	}
	pipeline.ClearColor(Vec4{0.9, 0.9, 0.9, 1.0})

	// Create the Uniform Buffer
	transform, err = gfx.NewBuffer(uintptr(64), gfx.DynamicStorage)
	if err != nil {
		log.Fatal(err)
	}

	// Create the Vertex Buffer
	data := []perVertex{
		// Front Face
		{Vec3{0, 0, 1}, color.RGB{R: 0.3, G: 0, B: 0.8}},
		{Vec3{1, 1, 1}, color.RGB{R: 0.3, G: 0, B: 0.8}},
		{Vec3{0, 1, 1}, color.RGB{R: 0.3, G: 0, B: 0.8}},
		{Vec3{0, 0, 1}, color.RGB{R: 0.3, G: 0, B: 0.8}},
		{Vec3{1, 0, 1}, color.RGB{R: 0.3, G: 0, B: 0.8}},
		{Vec3{1, 1, 1}, color.RGB{R: 0.3, G: 0, B: 0.8}},
		// Back Face
		{Vec3{0, 0, 0}, color.RGB{R: 0.3, G: 0, B: 0.8}},
		{Vec3{0, 1, 0}, color.RGB{R: 0.3, G: 0, B: 0.8}},
		{Vec3{1, 1, 0}, color.RGB{R: 0.3, G: 0, B: 0.8}},
		{Vec3{0, 0, 0}, color.RGB{R: 0.3, G: 0, B: 0.8}},
		{Vec3{1, 1, 0}, color.RGB{R: 0.3, G: 0, B: 0.8}},
		{Vec3{1, 0, 0}, color.RGB{R: 0.3, G: 0, B: 0.8}},
		// Right Face
		{Vec3{1, 0, 1}, color.RGB{R: 0.8, G: 0.3, B: 0}},
		{Vec3{1, 1, 0}, color.RGB{R: 0.8, G: 0.3, B: 0}},
		{Vec3{1, 1, 1}, color.RGB{R: 0.8, G: 0.3, B: 0}},
		{Vec3{1, 0, 1}, color.RGB{R: 0.8, G: 0.3, B: 0}},
		{Vec3{1, 0, 0}, color.RGB{R: 0.8, G: 0.3, B: 0}},
		{Vec3{1, 1, 0}, color.RGB{R: 0.8, G: 0.3, B: 0}},
		// Left Face
		{Vec3{0, 0, 1}, color.RGB{R: 0.8, G: 0.3, B: 0}},
		{Vec3{0, 1, 1}, color.RGB{R: 0.8, G: 0.3, B: 0}},
		{Vec3{0, 1, 0}, color.RGB{R: 0.8, G: 0.3, B: 0}},
		{Vec3{0, 0, 1}, color.RGB{R: 0.8, G: 0.3, B: 0}},
		{Vec3{0, 1, 0}, color.RGB{R: 0.8, G: 0.3, B: 0}},
		{Vec3{0, 0, 0}, color.RGB{R: 0.8, G: 0.3, B: 0}},
		// Bottom Face
		{Vec3{0, 0, 1}, color.RGB{R: 0, G: 0.6, B: 0.2}},
		{Vec3{0, 0, 0}, color.RGB{R: 0, G: 0.6, B: 0.2}},
		{Vec3{1, 0, 1}, color.RGB{R: 0, G: 0.6, B: 0.2}},
		{Vec3{0, 0, 0}, color.RGB{R: 0, G: 0.6, B: 0.2}},
		{Vec3{1, 0, 0}, color.RGB{R: 0, G: 0.6, B: 0.2}},
		{Vec3{1, 0, 1}, color.RGB{R: 0, G: 0.6, B: 0.2}},
		// Top Face
		{Vec3{0, 1, 1}, color.RGB{R: 0, G: 0.6, B: 0.2}},
		{Vec3{1, 1, 1}, color.RGB{R: 0, G: 0.6, B: 0.2}},
		{Vec3{0, 1, 0}, color.RGB{R: 0, G: 0.6, B: 0.2}},
		{Vec3{0, 1, 0}, color.RGB{R: 0, G: 0.6, B: 0.2}},
		{Vec3{1, 1, 1}, color.RGB{R: 0, G: 0.6, B: 0.2}},
		{Vec3{1, 1, 0}, color.RGB{R: 0, G: 0.6, B: 0.2}},
	}
	colorfulTriangle, err = gfx.NewBuffer(data, 0)
	if err != nil {
		log.Fatal(err)
	}

	// Run the Game Loop
	err = glam.Run()
	if err != nil {
		log.Fatal(err)
	}
}

//------------------------------------------------------------------------------

type game struct{}

var angle float32

func (g *game) Update() {
	angle += 0.01
}

func (g *game) Draw() {
	pipeline.Bind()
	pipeline.UniformBuffer(0, transform)

	m := space.Perspective(0.535, 1.0, 0.001, 1000.0)
	m = m.Times(space.LookAt(Vec3{0, 0, 5}, Vec3{0, 0, 0}, Vec3{0, 1, 0}))
	m = m.Times(space.Rotation(angle, Vec3{1, -0.5, 0.25}.Normalized()))
	m = m.Times(space.Translation(Vec3{-0.5, -0.5, -0.5}))
	t := perObject{
		transform: m,
	}
	transform.Update(&t, 0)

	pipeline.VertexBuffer(0, colorfulTriangle, 0)
	gfx.Draw(gfx.Triangles, 0, 6*2*3)
}

//------------------------------------------------------------------------------
<|endoftext|>


<commit_before>package main

import (
	"archive/zip"
	"bytes"
	"encoding/json"
	"flag"
	"fmt"
	"github.com/valyala/fasthttp"
	"github.com/valyala/fasthttp/fasthttpproxy"
	_ "golang.org/x/image/webp"
	"image"
	"image/jpeg"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"runtime"
	"sync"
)

type GalleryInfo struct {
	LocalLang string      `json:"language_localname"`
	Lang      string      `json:"language"`
	Date      string      `json:"date"`
	Files     []ImageInfo `json:"files"`
	// Tags
	Id    string `json:"id"`
	Type  string `json:"type"`
	Title string `json:"title"`
}

type ImageInfo struct {
	Width   uint   `json:"width"`
	Name    string `json:"name"`
	Height  uint   `json:"height"`
	Hash    string `json:"hash"`
	HasWebp int    `json:"haswebp"`
	HasAvif int    `json:"hasavif"`
}

type Result struct {
	Image   []byte
	ImgName string
	WK_ID   int
	IsWebp  bool
}

func GetImageNamesFromID(GalleryID string) []ImageInfo {
	code, resp, err := Client.Get(nil, "https://ltn.hitomi.la/galleries/"+GalleryID+".js")
	if err != nil {
		log.Fatal(err)
	}
	if code != 200 {
		log.Fatal(err)
	}
	resp = bytes.Replace(resp, []byte("var galleryinfo = "), []byte(""), -1)
	var g GalleryInfo
	err = json.Unmarshal(resp, &g)
	if err != nil {
		log.Fatal(err)
	}
	return g.Files
}

func LnsCurrentDirectory() {
	http.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("."))))

	http.ListenAndServe(":80", nil)
}

func DownloadImage(url string, try int, signal chan<- string) []byte {
	for i := 0; i < try; i++ {
		if i != 0 {
			signal <- fmt.Sprintf("Redownloading %s: #%d/%d", url, i+1, try)
		}
		req := fasthttp.AcquireRequest()
		req.URI().Update(url)
		req.Header.SetMethod("GET")
		req.Header.Set("Referer", "https://hitomi.la")
		req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0")
		res := fasthttp.AcquireResponse()
		if err := Client.Do(req, res); err == nil && res.Header.StatusCode() == 200 && res.Header.ContentLength() > 0 {
			img := make([]byte, res.Header.ContentLength())
			copy(img, res.Body())
			fasthttp.ReleaseResponse(res)
			fasthttp.ReleaseRequest(req)
			return img
		} else {
			signal <- fmt.Sprintf("Download Error: %s: %d %v", url, res.Header.StatusCode(), err)
		}
		fasthttp.ReleaseResponse(res)
		fasthttp.ReleaseRequest(req)
	}
	signal <- "Download Failed: " + url
	return nil
}

func DownloadWorker(no int, rLimit int, signal chan<- string, ctrl <-chan struct{}, jobs <-chan ImageInfo, out chan<- Result) {
	for j := range jobs {
		select {
		case out <- Result{DownloadImage(ImageURLFromImageInfo(j), rLimit, signal), j.Name, no, j.HasWebp == 1}:
		case <-ctrl:
			return
		}
	}
}

var Gallery_ID = flag.String("Gallery_ID", "", "Hitomi.la Gallery ID")
var Gallery_Name = flag.String("Gallery_Name", "", "Hitomi.la Gallery name")
var Do_Compression = flag.Bool("Do_Compression", true, "Compress downloaded files if true")
var HTTPSvr = flag.Bool("HTTPSvr", false, "Start HTTP Server")
var RetryLimit = flag.Int("Retry_Limit", 3, "Limit of image download retry")
var Socks5 = flag.String("Socks5_Proxy", "", "Socks5 Proxy address")

var Client fasthttp.Client

func init() {
	flag.StringVar(Gallery_ID, "i", "", "Hitomi.la Gallery ID")
	flag.StringVar(Gallery_Name, "n", "", "Hitomi.la Gallery Name")
	flag.BoolVar(Do_Compression, "c", true, "Compress downloaded files if true")
	flag.BoolVar(HTTPSvr, "s", false, "Start HTTP Server")
	flag.IntVar(RetryLimit, "r", 3, "Limit of image download retry")
	flag.StringVar(Socks5, "socks", "", "Socks5 Proxy address")
}

func main() {
	defer func() {
		if r := recover(); r != nil {
			fmt.Println("panic:", r)
		}
	}()

	flag.Parse()
	if *Gallery_ID == "" {
		fmt.Println("<Commands>")
		fmt.Println("-i : Gallery ID")
		fmt.Println("-n : Gallery Name")
		fmt.Println("-c : Compression")
		fmt.Println("-s : Start HTTP Server")
		fmt.Println("-r : Limit of image download retry")
		fmt.Println("-socks : Socks5 proxy address")
		os.Exit(1)
	}
	if *Gallery_Name == "" {
		*Gallery_Name = *Gallery_ID
	}

	if *Socks5 != "" {
		Client.Dial = fasthttpproxy.FasthttpSocksDialer(*Socks5)
	}

	runtime.GOMAXPROCS(runtime.NumCPU())

	fmt.Println("using", runtime.GOMAXPROCS(0), "CPU(s)")

	fmt.Println("Gallery ID :", *Gallery_ID)
	fmt.Println("Gallery Name :", *Gallery_Name)
	fmt.Println("Compression :", *Do_Compression)
	fmt.Println("Start HTTP Server :", *HTTPSvr)
	fmt.Println("Download retry limit :", *RetryLimit)
	fmt.Println("Socks5 proxy address :", *Socks5)

	fmt.Println("fetching image list")
	img_lst := GetImageNamesFromID(*Gallery_ID)
	num_lst := len(img_lst)
	fmt.Println("fetched", num_lst, "images")

	var archiveFile *os.File
	var zipWriter *zip.Writer

	if *Do_Compression {
		//init zip archiver
		archiveFile, err := os.OpenFile(
			*Gallery_Name+".zip",
			os.O_CREATE|os.O_WRONLY|os.O_TRUNC,
			os.FileMode(0644))
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
		zipWriter = zip.NewWriter(archiveFile)
	} else {
		os.Mkdir(*Gallery_Name, 0777)
	}

	ctrl := make(chan struct{})
	jobs := make(chan ImageInfo)
	out := make(chan Result)
	signals := make(chan string)

	var wg sync.WaitGroup
	NumWorkers := 10
	wg.Add(NumWorkers)

	go func() {
		for {
			fmt.Println(<-signals)
		}
	}()

	for i := 0; i < NumWorkers; i++ {
		go func(n int) {
			DownloadWorker(n, *RetryLimit, signals, ctrl, jobs, out)
			wg.Done()
		}(i)
	}

	go func() {
		wg.Wait()
		close(out)
	}()

	go func() {
		for _, work := range img_lst {
			jobs <- work
		}
		close(jobs)
	}()

	count := 0
	for r := range out {
		count++

		if r.IsWebp {
			img, ext, err := image.Decode(bytes.NewBuffer(r.Image))
			if err != nil {
				log.Println(err)
			}

			if ext != "webp" {
				log.Printf("Image extension mismatch: %s != webp", ext)
			}

			var iBuffer bytes.Buffer
			err = jpeg.Encode(&iBuffer, img, &jpeg.Options{Quality: 100})
			if err != nil {
				log.Println("Encode Error:", err)
			}

			r.Image = iBuffer.Bytes()
		}

		if *Do_Compression {
			var f io.Writer
			var err error
			if r.IsWebp {
				f, err = zipWriter.Create(r.ImgName + ".jpg")
			} else {
				f, err = zipWriter.Create(r.ImgName)
			}
			if err != nil {
				fmt.Println(err)
			}
			_, err = f.Write(r.Image)
			if err != nil {
				fmt.Println(err)
			}
		} else {
			var err error
			if r.IsWebp {
				err = ioutil.WriteFile(*Gallery_Name+"/"+r.ImgName+".jpg", r.Image, os.FileMode(0644))
			} else {
				err = ioutil.WriteFile(*Gallery_Name+"/"+r.ImgName, r.Image, os.FileMode(0644))
			}
			if err != nil {
				fmt.Println(err)
			}
		}
		fmt.Printf("[worker %d] downloaded %s\n", r.WK_ID, r.ImgName)

		if count == num_lst {
			close(ctrl)
		}
	}

	if *Do_Compression {
		zipWriter.Close()
		archiveFile.Close()
	}

	if *HTTPSvr == true {
		fmt.Println("HTTP Server started. Press Ctrl+C to exit")
		LnsCurrentDirectory()
	}
}
<commit_msg>Update error handling<commit_after>package main

import (
	"archive/zip"
	"bytes"
	"encoding/json"
	"flag"
	"fmt"
	"github.com/valyala/fasthttp"
	"github.com/valyala/fasthttp/fasthttpproxy"
	_ "golang.org/x/image/webp"
	"image"
	"image/jpeg"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"runtime"
	"sync"
)

type GalleryInfo struct {
	LocalLang string      `json:"language_localname"`
	Lang      string      `json:"language"`
	Date      string      `json:"date"`
	Files     []ImageInfo `json:"files"`
	// Tags
	Id    string `json:"id"`
	Type  string `json:"type"`
	Title string `json:"title"`
}

type ImageInfo struct {
	Width   uint   `json:"width"`
	Name    string `json:"name"`
	Height  uint   `json:"height"`
	Hash    string `json:"hash"`
	HasWebp int    `json:"haswebp"`
	HasAvif int    `json:"hasavif"`
}

type Result struct {
	Image   []byte
	ImgName string
	WK_ID   int
	IsWebp  bool
}

func GetImageNamesFromID(GalleryID string) []ImageInfo {
	code, resp, err := Client.Get(nil, "https://ltn.hitomi.la/galleries/"+GalleryID+".js")
	if err != nil {
		log.Fatal(err)
	}
	if code != 200 {
		log.Fatal("Error:", code)
	}
	resp = bytes.Replace(resp, []byte("var galleryinfo = "), []byte(""), -1)
	var g GalleryInfo
	err = json.Unmarshal(resp, &g)
	if err != nil {
		log.Fatal(err)
	}
	return g.Files
}

func LnsCurrentDirectory() {
	http.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("."))))

	http.ListenAndServe(":80", nil)
}

func DownloadImage(url string, try int, signal chan<- string) []byte {
	for i := 0; i < try; i++ {
		if i != 0 {
			signal <- fmt.Sprintf("Redownloading %s: #%d/%d", url, i+1, try)
		}
		req := fasthttp.AcquireRequest()
		req.URI().Update(url)
		req.Header.SetMethod("GET")
		req.Header.Set("Referer", "https://hitomi.la")
		req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0")
		res := fasthttp.AcquireResponse()
		if err := Client.Do(req, res); err == nil && res.Header.StatusCode() == 200 && res.Header.ContentLength() > 0 {
			img := make([]byte, res.Header.ContentLength())
			copy(img, res.Body())
			fasthttp.ReleaseResponse(res)
			fasthttp.ReleaseRequest(req)
			return img
		} else {
			signal <- fmt.Sprintf("Download Error: %s: %d %v", url, res.Header.StatusCode(), err)
		}
		fasthttp.ReleaseResponse(res)
		fasthttp.ReleaseRequest(req)
	}
	signal <- "Download Failed: " + url
	return nil
}

func DownloadWorker(no int, rLimit int, signal chan<- string, ctrl <-chan struct{}, jobs <-chan ImageInfo, out chan<- Result) {
	for j := range jobs {
		select {
		case out <- Result{DownloadImage(ImageURLFromImageInfo(j), rLimit, signal), j.Name, no, j.HasWebp == 1}:
		case <-ctrl:
			return
		}
	}
}

var Gallery_ID = flag.String("Gallery_ID", "", "Hitomi.la Gallery ID")
var Gallery_Name = flag.String("Gallery_Name", "", "Hitomi.la Gallery name")
var Do_Compression = flag.Bool("Do_Compression", true, "Compress downloaded files if true")
var HTTPSvr = flag.Bool("HTTPSvr", false, "Start HTTP Server")
var RetryLimit = flag.Int("Retry_Limit", 3, "Limit of image download retry")
var Socks5 = flag.String("Socks5_Proxy", "", "Socks5 Proxy address")

var Client fasthttp.Client

func init() {
	flag.StringVar(Gallery_ID, "i", "", "Hitomi.la Gallery ID")
	flag.StringVar(Gallery_Name, "n", "", "Hitomi.la Gallery Name")
	flag.BoolVar(Do_Compression, "c", true, "Compress downloaded files if true")
	flag.BoolVar(HTTPSvr, "s", false, "Start HTTP Server")
	flag.IntVar(RetryLimit, "r", 3, "Limit of image download retry")
	flag.StringVar(Socks5, "socks", "", "Socks5 Proxy address")
}

func main() {
	defer func() {
		if r := recover(); r != nil {
			fmt.Println("panic:", r)
		}
	}()

	flag.Parse()
	if *Gallery_ID == "" {
		fmt.Println("<Commands>")
		fmt.Println("-i : Gallery ID")
		fmt.Println("-n : Gallery Name")
		fmt.Println("-c : Compression")
		fmt.Println("-s : Start HTTP Server")
		fmt.Println("-r : Limit of image download retry")
		fmt.Println("-socks : Socks5 proxy address")
		os.Exit(1)
	}
	if *Gallery_Name == "" {
		*Gallery_Name = *Gallery_ID
	}

	if *Socks5 != "" {
		Client.Dial = fasthttpproxy.FasthttpSocksDialer(*Socks5)
	}

	runtime.GOMAXPROCS(runtime.NumCPU())

	fmt.Println("using", runtime.GOMAXPROCS(0), "CPU(s)")

	fmt.Println("Gallery ID :", *Gallery_ID)
	fmt.Println("Gallery Name :", *Gallery_Name)
	fmt.Println("Compression :", *Do_Compression)
	fmt.Println("Start HTTP Server :", *HTTPSvr)
	fmt.Println("Download retry limit :", *RetryLimit)
	fmt.Println("Socks5 proxy address :", *Socks5)

	fmt.Println("fetching image list")
	img_lst := GetImageNamesFromID(*Gallery_ID)
	num_lst := len(img_lst)
	fmt.Println("fetched", num_lst, "images")

	var archiveFile *os.File
	var zipWriter *zip.Writer

	if *Do_Compression {
		//init zip archiver
		archiveFile, err := os.OpenFile(
			*Gallery_Name+".zip",
			os.O_CREATE|os.O_WRONLY|os.O_TRUNC,
			os.FileMode(0644))
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
		zipWriter = zip.NewWriter(archiveFile)
	} else {
		os.Mkdir(*Gallery_Name, 0777)
	}

	ctrl := make(chan struct{})
	jobs := make(chan ImageInfo)
	out := make(chan Result)
	signals := make(chan string)

	var wg sync.WaitGroup
	NumWorkers := 10
	wg.Add(NumWorkers)

	go func() {
		for {
			fmt.Println(<-signals)
		}
	}()

	for i := 0; i < NumWorkers; i++ {
		go func(n int) {
			DownloadWorker(n, *RetryLimit, signals, ctrl, jobs, out)
			wg.Done()
		}(i)
	}

	go func() {
		wg.Wait()
		close(out)
	}()

	go func() {
		for _, work := range img_lst {
			jobs <- work
		}
		close(jobs)
	}()

	count := 0
	for r := range out {
		count++

		if r.IsWebp {
			img, ext, err := image.Decode(bytes.NewBuffer(r.Image))
			if err != nil {
				log.Println(err)
			}

			if ext != "webp" {
				log.Printf("Image extension mismatch: %s != webp", ext)
			}

			var iBuffer bytes.Buffer
			err = jpeg.Encode(&iBuffer, img, &jpeg.Options{Quality: 100})
			if err != nil {
				log.Println("Encode Error:", err)
			}

			r.Image = iBuffer.Bytes()
		}

		if *Do_Compression {
			var f io.Writer
			var err error
			if r.IsWebp {
				f, err = zipWriter.Create(r.ImgName + ".jpg")
			} else {
				f, err = zipWriter.Create(r.ImgName)
			}
			if err != nil {
				fmt.Println(err)
			}
			_, err = f.Write(r.Image)
			if err != nil {
				fmt.Println(err)
			}
		} else {
			var err error
			if r.IsWebp {
				err = ioutil.WriteFile(*Gallery_Name+"/"+r.ImgName+".jpg", r.Image, os.FileMode(0644))
			} else {
				err = ioutil.WriteFile(*Gallery_Name+"/"+r.ImgName, r.Image, os.FileMode(0644))
			}
			if err != nil {
				fmt.Println(err)
			}
		}
		fmt.Printf("[worker %d] downloaded %s\n", r.WK_ID, r.ImgName)

		if count == num_lst {
			close(ctrl)
		}
	}

	if *Do_Compression {
		zipWriter.Close()
		archiveFile.Close()
	}

	if *HTTPSvr == true {
		fmt.Println("HTTP Server started. Press Ctrl+C to exit")
		LnsCurrentDirectory()
	}
}
<|endoftext|>


<commit_before>package instance

import (
	"os"

	"bosh-google-cpi/api"
	"bosh-google-cpi/util"
	bosherr "github.com/cloudfoundry/bosh-utils/errors"
)

const asyncDeleteKey = "CPI_ASYNC_DELETE"

func (i GoogleInstanceService) Delete(id string) error {
	instance, found, err := i.Find(id, "")
	if err != nil {
		return err
	}
	if !found {
		return api.NewVMNotFoundError(id)
	}

	i.logger.Debug(googleInstanceServiceLogTag, "Deleting Google Instance '%s'", id)
	operation, err := i.computeService.Instances.Delete(i.project, util.ResourceSplitter(instance.Zone), id).Do()
	if err != nil {
		return bosherr.WrapErrorf(err, "Failed to delete Google Instance '%s'", id)
	}

	if os.Getenv(asyncDeleteKey) == "" {
		i.logger.Debug(googleInstanceServiceLogTag, "Waiting for instance %q to delete", id)
		if _, err = i.operationService.Waiter(operation, instance.Zone, ""); err != nil {
			return bosherr.WrapErrorf(err, "Failed to delete Google Instance '%s'", id)
		}
	}

	if err = i.removeFromTargetPool(instance.SelfLink); err != nil {
		return bosherr.WrapErrorf(err, "Failed to remove Google Instance %q from Target Pool", id)
	}

	if err = i.removeFromBackendService(instance.SelfLink); err != nil {
		return bosherr.WrapErrorf(err, "Failed to remove Google Instance %q from Backend Services", id)
	}
	return nil
}
<commit_msg>Remove instances from Target Pool before deleting the instance [fixes #318]<commit_after>package instance

import (
	"os"

	"bosh-google-cpi/api"
	"bosh-google-cpi/util"

	bosherr "github.com/cloudfoundry/bosh-utils/errors"
)

const asyncDeleteKey = "CPI_ASYNC_DELETE"

func (i GoogleInstanceService) Delete(id string) error {
	instance, found, err := i.Find(id, "")
	if err != nil {
		return err
	}
	if !found {
		return api.NewVMNotFoundError(id)
	}

	if err = i.removeFromTargetPool(instance.SelfLink); err != nil {
		return bosherr.WrapErrorf(err, "Failed to remove Google Instance %q from Target Pool", id)
	}

	if err = i.removeFromBackendService(instance.SelfLink); err != nil {
		return bosherr.WrapErrorf(err, "Failed to remove Google Instance %q from Backend Services", id)
	}

	i.logger.Debug(googleInstanceServiceLogTag, "Deleting Google Instance '%s'", id)
	operation, err := i.computeService.Instances.Delete(i.project, util.ResourceSplitter(instance.Zone), id).Do()
	if err != nil {
		return bosherr.WrapErrorf(err, "Failed to delete Google Instance '%s'", id)
	}

	if os.Getenv(asyncDeleteKey) == "" {
		i.logger.Debug(googleInstanceServiceLogTag, "Waiting for instance %q to delete", id)
		if _, err = i.operationService.Waiter(operation, instance.Zone, ""); err != nil {
			return bosherr.WrapErrorf(err, "Failed to delete Google Instance '%s'", id)
		}
	}

	return nil
}
<|endoftext|>


<commit_before>package ucloud

import (
	"testing"
)

// ---------------- TestAllocateEIP ------------------
func TestAllocateEIP(t *testing.T) {
	r := &AllocateEIP{Region: "cn-north-01",
		OperatorName: "Bgp",
		Bandwidth:    4,
	}
	cmp := `https://api.ucloud.cn/?Action=AllocateEIP&Region=cn-north-01&OperatorName=Bgp&Bandwidth=4`

	if err := FakeGetAndCmp(r, cmp); err != nil {
		t.Fatal(err)
	}
}

// ---------------- TestDescribeEIP ------------------
func TestDescribeEIP(t *testing.T) {
	r := &DescribeEIP{Region: "cn-north-01"}
	cmp := `https://api.ucloud.cn/?Action=DescribeEIP&Region=cn-north-01`

	if err := FakeGetAndCmp(r, cmp); err != nil {
		t.Fatal(err)
	}
}

// ---------------- TestUpdateEIPAttribute ------------------
func TestUpdateEIPAttribute(t *testing.T) {
	r := &UpdateEIPAttribute{Remark: "test",
		Name:   "test",
		Region: "cn-north-01",
		EIPId:  "eip-w2pew1",
		Tag:    "test",
	}
	cmp := `https://api.ucloud.cn/?Action=UpdateEIPAttribute&Region=cn-north-01&EIPId=eip-w2pew1&Name=test&Tag=test&Remark=test`

	if err := FakeGetAndCmp(r, cmp); err != nil {
		t.Fatal(err)
	}
}

// ---------------- TestReleaseEIP ------------------
func TestReleaseEIP(t *testing.T) {
	r := &ReleaseEIP{Region: "cn-north-01",
		EIPId: "eip-wintta",
	}
	cmp := `https://api.ucloud.cn/?Action=ReleaseEIP&Region=cn-north-01&EIPId=eip-wintta`

	if err := FakeGetAndCmp(r, cmp); err != nil {
		t.Fatal(err)
	}
}

// ---------------- TestBindEIP ------------------
func TestBindEIP(t *testing.T) {
	r := &BindEIP{ResourceType: "uhost",
		Region:     "cn-north-01",
		EIPId:      "eip-1inlb2",
		ResourceId: "uhost-0ttesd",
	}
	cmp := `https://api.ucloud.cn/?Action=BindEIP&Region=cn-north-01&EIPId=eip-1inlb2&ResourceType=uhost&ResourceId=uhost-0ttesd`

	if err := FakeGetAndCmp(r, cmp); err != nil {
		t.Fatal(err)
	}
}

// ---------------- TestUnbindEIP ------------------
func TestUnbindEIP(t *testing.T) {
	r := &UnBindEIP{ResourceType: "uhost",
		Region:     "cn-north-01",
		EIPId:      "eip-1inlb2",
		ResourceId: "uhost-0ttesd",
	}
	cmp := `https://api.ucloud.cn/?Action=UnBindEIP&Region=cn-north-01&EIPId=eip-1inlb2&ResourceType=uhost&ResourceId=uhost-0ttesd`

	if err := FakeGetAndCmp(r, cmp); err != nil {
		t.Fatal(err)
	}
}

// ---------------- TestModifyEIPBandwidth ------------------
func TestModifyEIPBandwidth(t *testing.T) {
	r := &ModifyEIPBandwidth{Region: "cn-north-01",
		EIPId:     "eip-dr1e2n",
		Bandwidth: 4,
	}
	cmp := `https://api.ucloud.cn/?Action=ModifyEIPBandwidth&Region=cn-north-01&EIPId=eip-dr1e2n&Bandwidth=4`

	if err := FakeGetAndCmp(r, cmp); err != nil {
		t.Fatal(err)
	}
}

// ---------------- TestModifyEIPWeight ------------------
func TestModifyEIPWeight(t *testing.T) {
	r := &ModifyEIPWeight{Region: "cn-north-01",
		EIPId:  "eip-dr1e2n",
		Weight: 4,
	}
	cmp := `https://api.ucloud.cn/?Action=ModifyEIPWeight&Region=cn-north-01&EIPId=eip-dr1e2n&Weight=4`

	if err := FakeGetAndCmp(r, cmp); err != nil {
		t.Fatal(err)
	}
}

// ---------------- TestGetEIPPrice ------------------
func TestGetEIPPrice(t *testing.T) {
	r := &GetEIPPrice{Region: "cn-north-01",
		OperatorName: "Bgp",
		Bandwidth:    4,
	}
	cmp := `https://api.ucloud.cn/?Action=GetEIPPrice&Region=cn-north-01&OperatorName=Bgp&Bandwidth=4`

	if err := FakeGetAndCmp(r, cmp); err != nil {
		t.Fatal(err)
	}
}

// ---------------- TestAllocateVIP ------------------
func TestAllocateVIP(t *testing.T) {
	r := &AllocateVIP{Region: "cn-north-01"}
	cmp := `https://api.ucloud.cn/?Action=AllocateVIP&Region=cn-north-01`

	if err := FakeGetAndCmp(r, cmp); err != nil {
		t.Fatal(err)
	}
}

// ---------------- TestDescribeVIP ------------------
func TestDescribeVIP(t *testing.T) {
	r := &DescribeVIP{Region: "cn-north-01"}
	cmp := `https://api.ucloud.cn/?Action=DescribeVIP&Region=cn-north-01`

	if err := FakeGetAndCmp(r, cmp); err != nil {
		t.Fatal(err)
	}
}

// ---------------- TestReleaseVIP ------------------
func TestReleaseVIP(t *testing.T) {
	r := &ReleaseVIP{Region: "cn-north-01",
		VIP: "10.10.3.13",
	}
	cmp := `https://api.ucloud.cn/?Action=ReleaseVIP&Region=cn-north-01&VIP=10.10.3.13`

	if err := FakeGetAndCmp(r, cmp); err != nil {
		t.Fatal(err)
	}
}

// ---------------- TestDescribeSecurityGroup ------------------
func TestDescribeSecurityGroup(t *testing.T) {
	r := &DescribeSecurityGroup{Region: "cn-north-01",
		GroupId: 6583,
	}
	cmp := `https://api.ucloud.cn/?Action=DescribeSecurityGroup&Region=cn-north-01&GroupId=6583`

	if err := FakeGetAndCmp(r, cmp); err != nil {
		t.Fatal(err)
	}
}

// ---------------- TestDescribeSecurityGroupResource ------------------
func TestDescribeSecurityGroupResource(t *testing.T) {
	r := &DescribeSecurityGroupResource{Region: "cn-north-01",
		GroupId: 6583,
	}
	cmp := `https://api.ucloud.cn/?Action=DescribeSecurityGroupResource&Region=cn-north-01&GroupId=6583`

	if err := FakeGetAndCmp(r, cmp); err != nil {
		t.Fatal(err)
	}
}

// ---------------- TestCreateSecurityGroup ------------------
func TestCreateSecurityGroup(t *testing.T) {
	r := &CreateSecurityGroup{Region: "cn-north-01",
		Rule:      []string{"TCP|3306|0.0.0.0/0|DROP|50", "UDP|53|0.0.0.0/0|ACCEPT|50"},
		GroupName: "NewSecurityGroup",
	}
	cmp := `https://api.ucloud.cn/?Action=CreateSecurityGroup&Region=cn-north-01&GroupName=NewSecurityGroup&Rule.1=UDP|53|0.0.0.0/0|ACCEPT|50&Rule.0=TCP|3306|0.0.0.0/0|DROP|50`

	if err := FakeGetAndCmp(r, cmp); err != nil {
		t.Fatal(err)
	}
}

// ---------------- TestUpdateSecurityGroup ------------------
func TestUpdateSecurityGroup(t *testing.T) {
	r := &UpdateSecurityGroup{Region: "cn-north-01",
		GroupId: "6583",
		Rule:    []string{"TCP|3306|0.0.0.0/0|DROP|50", "UDP|53|0.0.0.0/0|ACCEPT|50"},
	}
	cmp := `https://api.ucloud.cn/?Action=UpdateSecurityGroup&Region=cn-north-01&GroupId=6583&Rule.1=UDP|53|0.0.0.0/0|ACCEPT|50&Rule.0=TCP|3306|0.0.0.0/0|DROP|50`

	if err := FakeGetAndCmp(r, cmp); err != nil {
		t.Fatal(err)
	}
}

// ---------------- TestGrantSecurityGroup ------------------
func TestGrantSecurityGroup(t *testing.T) {
	r := &GrantSecurityGroup{ResourceType: "UHost",
		Region:     "cn-north-01",
		GroupId:    "6583",
		ResourceId: "uhost-w4d53b",
	}
	cmp := `https://api.ucloud.cn/?Action=GrantSecurityGroup&Region=cn-north-01&GroupId=6583&ResourceType=UHost&ResourceId=uhost-w4d53b`

	if err := FakeGetAndCmp(r, cmp); err != nil {
		t.Fatal(err)
	}
}

// ---------------- TestDeleteSecurityGroup ------------------
func TestDeleteSecurityGroup(t *testing.T) {
	r := &DeleteSecurityGroup{Region: "cn-north-01",
		GroupId: "6583",
	}
	cmp := `https://api.ucloud.cn/?Action=DeleteSecurityGroup&Region=cn-north-01&GroupId=6583`

	if err := FakeGetAndCmp(r, cmp); err != nil {
		t.Fatal(err)
	}
}
<commit_msg>update UNet<commit_after>package ucloud

import (
	"fmt"
	"testing"
)

// ---------------- TestAllocateEIP ------------------
func TestAllocateEIP(t *testing.T) {
	fmt.Println("UNet....")
	r := &AllocateEIP{Region: "cn-north-01",
		OperatorName: "Bgp",
		Bandwidth:    4,
	}
	cmp := `https://api.ucloud.cn/?Action=AllocateEIP&Region=cn-north-01&OperatorName=Bgp&Bandwidth=4`

	if err := FakeGetAndCmp(r, cmp); err != nil {
		t.Fatal(err)
	}
}

// ---------------- TestDescribeEIP ------------------
func TestDescribeEIP(t *testing.T) {
	r := &DescribeEIP{Region: "cn-north-01"}
	cmp := `https://api.ucloud.cn/?Action=DescribeEIP&Region=cn-north-01`

	if err := FakeGetAndCmp(r, cmp); err != nil {
		t.Fatal(err)
	}
}

// ---------------- TestUpdateEIPAttribute ------------------
func TestUpdateEIPAttribute(t *testing.T) {
	r := &UpdateEIPAttribute{Remark: "test",
		Name:   "test",
		Region: "cn-north-01",
		EIPId:  "eip-w2pew1",
		Tag:    "test",
	}
	cmp := `https://api.ucloud.cn/?Action=UpdateEIPAttribute&Region=cn-north-01&EIPId=eip-w2pew1&Name=test&Tag=test&Remark=test`

	if err := FakeGetAndCmp(r, cmp); err != nil {
		t.Fatal(err)
	}
}

// ---------------- TestReleaseEIP ------------------
func TestReleaseEIP(t *testing.T) {
	r := &ReleaseEIP{Region: "cn-north-01",
		EIPId: "eip-wintta",
	}
	cmp := `https://api.ucloud.cn/?Action=ReleaseEIP&Region=cn-north-01&EIPId=eip-wintta`

	if err := FakeGetAndCmp(r, cmp); err != nil {
		t.Fatal(err)
	}
}

// ---------------- TestBindEIP ------------------
func TestBindEIP(t *testing.T) {
	r := &BindEIP{ResourceType: "uhost",
		Region:     "cn-north-01",
		EIPId:      "eip-1inlb2",
		ResourceId: "uhost-0ttesd",
	}
	cmp := `https://api.ucloud.cn/?Action=BindEIP&Region=cn-north-01&EIPId=eip-1inlb2&ResourceType=uhost&ResourceId=uhost-0ttesd`

	if err := FakeGetAndCmp(r, cmp); err != nil {
		t.Fatal(err)
	}
}

// ---------------- TestUnbindEIP ------------------
func TestUnbindEIP(t *testing.T) {
	r := &UnBindEIP{ResourceType: "uhost",
		Region:     "cn-north-01",
		EIPId:      "eip-1inlb2",
		ResourceId: "uhost-0ttesd",
	}
	cmp := `https://api.ucloud.cn/?Action=UnBindEIP&Region=cn-north-01&EIPId=eip-1inlb2&ResourceType=uhost&ResourceId=uhost-0ttesd`

	if err := FakeGetAndCmp(r, cmp); err != nil {
		t.Fatal(err)
	}
}

// ---------------- TestModifyEIPBandwidth ------------------
func TestModifyEIPBandwidth(t *testing.T) {
	r := &ModifyEIPBandwidth{Region: "cn-north-01",
		EIPId:     "eip-dr1e2n",
		Bandwidth: 4,
	}
	cmp := `https://api.ucloud.cn/?Action=ModifyEIPBandwidth&Region=cn-north-01&EIPId=eip-dr1e2n&Bandwidth=4`

	if err := FakeGetAndCmp(r, cmp); err != nil {
		t.Fatal(err)
	}
}

// ---------------- TestModifyEIPWeight ------------------
func TestModifyEIPWeight(t *testing.T) {
	r := &ModifyEIPWeight{Region: "cn-north-01",
		EIPId:  "eip-dr1e2n",
		Weight: 4,
	}
	cmp := `https://api.ucloud.cn/?Action=ModifyEIPWeight&Region=cn-north-01&EIPId=eip-dr1e2n&Weight=4`

	if err := FakeGetAndCmp(r, cmp); err != nil {
		t.Fatal(err)
	}
}

// ---------------- TestGetEIPPrice ------------------
func TestGetEIPPrice(t *testing.T) {
	r := &GetEIPPrice{Region: "cn-north-01",
		OperatorName: "Bgp",
		Bandwidth:    4,
	}
	cmp := `https://api.ucloud.cn/?Action=GetEIPPrice&Region=cn-north-01&OperatorName=Bgp&Bandwidth=4`

	if err := FakeGetAndCmp(r, cmp); err != nil {
		t.Fatal(err)
	}
}

// ---------------- TestAllocateVIP ------------------
func TestAllocateVIP(t *testing.T) {
	r := &AllocateVIP{Region: "cn-north-01"}
	cmp := `https://api.ucloud.cn/?Action=AllocateVIP&Region=cn-north-01`

	if err := FakeGetAndCmp(r, cmp); err != nil {
		t.Fatal(err)
	}
}

// ---------------- TestDescribeVIP ------------------
func TestDescribeVIP(t *testing.T) {
	r := &DescribeVIP{Region: "cn-north-01"}
	cmp := `https://api.ucloud.cn/?Action=DescribeVIP&Region=cn-north-01`

	if err := FakeGetAndCmp(r, cmp); err != nil {
		t.Fatal(err)
	}
}

// ---------------- TestReleaseVIP ------------------
func TestReleaseVIP(t *testing.T) {
	r := &ReleaseVIP{Region: "cn-north-01",
		VIP: "10.10.3.13",
	}
	cmp := `https://api.ucloud.cn/?Action=ReleaseVIP&Region=cn-north-01&VIP=10.10.3.13`

	if err := FakeGetAndCmp(r, cmp); err != nil {
		t.Fatal(err)
	}
}

// ---------------- TestDescribeSecurityGroup ------------------
func TestDescribeSecurityGroup(t *testing.T) {
	r := &DescribeSecurityGroup{Region: "cn-north-01",
		GroupId: 6583,
	}
	cmp := `https://api.ucloud.cn/?Action=DescribeSecurityGroup&Region=cn-north-01&GroupId=6583`

	if err := FakeGetAndCmp(r, cmp); err != nil {
		t.Fatal(err)
	}
}

// ---------------- TestDescribeSecurityGroupResource ------------------
func TestDescribeSecurityGroupResource(t *testing.T) {
	r := &DescribeSecurityGroupResource{Region: "cn-north-01",
		GroupId: 6583,
	}
	cmp := `https://api.ucloud.cn/?Action=DescribeSecurityGroupResource&Region=cn-north-01&GroupId=6583`

	if err := FakeGetAndCmp(r, cmp); err != nil {
		t.Fatal(err)
	}
}

// ---------------- TestCreateSecurityGroup ------------------
func TestCreateSecurityGroup(t *testing.T) {
	r := &CreateSecurityGroup{Region: "cn-north-01",
		Rule:      []string{"TCP|3306|0.0.0.0/0|DROP|50", "UDP|53|0.0.0.0/0|ACCEPT|50"},
		GroupName: "NewSecurityGroup",
	}
	cmp := `https://api.ucloud.cn/?Action=CreateSecurityGroup&Region=cn-north-01&GroupName=NewSecurityGroup&Rule.1=UDP|53|0.0.0.0/0|ACCEPT|50&Rule.0=TCP|3306|0.0.0.0/0|DROP|50`

	if err := FakeGetAndCmp(r, cmp); err != nil {
		t.Fatal(err)
	}
}

// ---------------- TestUpdateSecurityGroup ------------------
func TestUpdateSecurityGroup(t *testing.T) {
	r := &UpdateSecurityGroup{Region: "cn-north-01",
		GroupId: "6583",
		Rule:    []string{"TCP|3306|0.0.0.0/0|DROP|50", "UDP|53|0.0.0.0/0|ACCEPT|50"},
	}
	cmp := `https://api.ucloud.cn/?Action=UpdateSecurityGroup&Region=cn-north-01&GroupId=6583&Rule.1=UDP|53|0.0.0.0/0|ACCEPT|50&Rule.0=TCP|3306|0.0.0.0/0|DROP|50`

	if err := FakeGetAndCmp(r, cmp); err != nil {
		t.Fatal(err)
	}
}

// ---------------- TestGrantSecurityGroup ------------------
func TestGrantSecurityGroup(t *testing.T) {
	r := &GrantSecurityGroup{ResourceType: "UHost",
		Region:     "cn-north-01",
		GroupId:    "6583",
		ResourceId: "uhost-w4d53b",
	}
	cmp := `https://api.ucloud.cn/?Action=GrantSecurityGroup&Region=cn-north-01&GroupId=6583&ResourceType=UHost&ResourceId=uhost-w4d53b`

	if err := FakeGetAndCmp(r, cmp); err != nil {
		t.Fatal(err)
	}
}

// ---------------- TestDeleteSecurityGroup ------------------
func TestDeleteSecurityGroup(t *testing.T) {
	r := &DeleteSecurityGroup{Region: "cn-north-01",
		GroupId: "6583",
	}
	cmp := `https://api.ucloud.cn/?Action=DeleteSecurityGroup&Region=cn-north-01&GroupId=6583`

	if err := FakeGetAndCmp(r, cmp); err != nil {
		t.Fatal(err)
	}
}
<|endoftext|>


<commit_before><commit_msg>fixed merge issue<commit_after><|endoftext|>


<commit_before>package integration

import (
	"fmt"
	"runtime"
	"testing"

	"github.com/bitrise-io/go-utils/cmdex"
	"github.com/stretchr/testify/require"
)

func Test_VersionOutput(t *testing.T) {
	t.Log("Version")
	{
		out, err := cmdex.RunCommandAndReturnCombinedStdoutAndStderr(binPath(), "version")
		require.NoError(t, err)
		require.Equal(t, "1.4.3", out)
	}

	t.Log("Version --full")
	{
		out, err := cmdex.RunCommandAndReturnCombinedStdoutAndStderr(binPath(), "version", "--full")
		require.NoError(t, err)

		expectedOSVersion := fmt.Sprintf("%s (%s)", runtime.GOOS, runtime.GOARCH)
		expectedVersionOut := fmt.Sprintf(`version: 1.4.3
format version: 1.3.1
os: %s
go: %s
build number:
commit:`, expectedOSVersion, runtime.Version())

		require.Equal(t, expectedVersionOut, out)
	}
}
<commit_msg>version test update<commit_after>package integration

import (
	"fmt"
	"runtime"
	"testing"

	"github.com/bitrise-io/go-utils/cmdex"
	"github.com/stretchr/testify/require"
)

func Test_VersionOutput(t *testing.T) {
	t.Log("Version")
	{
		out, err := cmdex.RunCommandAndReturnCombinedStdoutAndStderr(binPath(), "version")
		require.NoError(t, err)
		require.Equal(t, "1.4.4", out)
	}

	t.Log("Version --full")
	{
		out, err := cmdex.RunCommandAndReturnCombinedStdoutAndStderr(binPath(), "version", "--full")
		require.NoError(t, err)

		expectedOSVersion := fmt.Sprintf("%s (%s)", runtime.GOOS, runtime.GOARCH)
		expectedVersionOut := fmt.Sprintf(`version: 1.4.4
format version: 1.3.1
os: %s
go: %s
build number:
commit:`, expectedOSVersion, runtime.Version())

		require.Equal(t, expectedVersionOut, out)
	}
}
<|endoftext|>