<commit_before>// Copyright 2015 CoreOS, 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 version implements etcd version parsing and contains latest version
// information.
package version

import (
	"fmt"
	"os"
	"path"
	"strings"

	"github.com/coreos/etcd/pkg/fileutil"
	"github.com/coreos/etcd/pkg/types"
)

var (
	// MinClusterVersion is the min cluster version this etcd binary is compatible with.
	MinClusterVersion = "2.2.0"
	Version           = "2.3.0-alpha.1+git"

	// Git SHA Value will be set during build
	GitSHA = "Not provided (use ./build instead of go build)"
)

// DataDirVersion is an enum for versions of etcd logs.
type DataDirVersion string

const (
	DataDirUnknown  DataDirVersion = "Unknown WAL"
	DataDir2_0      DataDirVersion = "2.0.0"
	DataDir2_0Proxy DataDirVersion = "2.0 proxy"
	DataDir2_0_1    DataDirVersion = "2.0.1"
)

type Versions struct {
	Server  string `json:"etcdserver"`
	Cluster string `json:"etcdcluster"`
	// TODO: raft state machine version
}

func DetectDataDir(dirpath string) (DataDirVersion, error) {
	names, err := fileutil.ReadDir(dirpath)
	if err != nil {
		if os.IsNotExist(err) {
			err = nil
		}
		// Error reading the directory
		return DataDirUnknown, err
	}
	nameSet := types.NewUnsafeSet(names...)
	if nameSet.Contains("member") {
		ver, err := DetectDataDir(path.Join(dirpath, "member"))
		if ver == DataDir2_0 {
			return DataDir2_0_1, nil
		}
		return ver, err
	}
	if nameSet.ContainsAll([]string{"snap", "wal"}) {
		// .../wal cannot be empty to exist.
		walnames, err := fileutil.ReadDir(path.Join(dirpath, "wal"))
		if err == nil && len(walnames) > 0 {
			return DataDir2_0, nil
		}
	}
	if nameSet.ContainsAll([]string{"proxy"}) {
		return DataDir2_0Proxy, nil
	}
	return DataDirUnknown, nil
}

// Cluster only keeps the major.minor.
func Cluster(v string) string {
	vs := strings.Split(v, ".")
	if len(vs) <= 2 {
		return v
	}
	return fmt.Sprintf("%s.%s", vs[0], vs[1])
}
<commit_msg>version: bump to 2.3<commit_after>// Copyright 2015 CoreOS, 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 version implements etcd version parsing and contains latest version
// information.
package version

import (
	"fmt"
	"os"
	"path"
	"strings"

	"github.com/coreos/etcd/pkg/fileutil"
	"github.com/coreos/etcd/pkg/types"
)

var (
	// MinClusterVersion is the min cluster version this etcd binary is compatible with.
	MinClusterVersion = "2.2.0"
	Version           = "2.3.0"

	// Git SHA Value will be set during build
	GitSHA = "Not provided (use ./build instead of go build)"
)

// DataDirVersion is an enum for versions of etcd logs.
type DataDirVersion string

const (
	DataDirUnknown  DataDirVersion = "Unknown WAL"
	DataDir2_0      DataDirVersion = "2.0.0"
	DataDir2_0Proxy DataDirVersion = "2.0 proxy"
	DataDir2_0_1    DataDirVersion = "2.0.1"
)

type Versions struct {
	Server  string `json:"etcdserver"`
	Cluster string `json:"etcdcluster"`
	// TODO: raft state machine version
}

func DetectDataDir(dirpath string) (DataDirVersion, error) {
	names, err := fileutil.ReadDir(dirpath)
	if err != nil {
		if os.IsNotExist(err) {
			err = nil
		}
		// Error reading the directory
		return DataDirUnknown, err
	}
	nameSet := types.NewUnsafeSet(names...)
	if nameSet.Contains("member") {
		ver, err := DetectDataDir(path.Join(dirpath, "member"))
		if ver == DataDir2_0 {
			return DataDir2_0_1, nil
		}
		return ver, err
	}
	if nameSet.ContainsAll([]string{"snap", "wal"}) {
		// .../wal cannot be empty to exist.
		walnames, err := fileutil.ReadDir(path.Join(dirpath, "wal"))
		if err == nil && len(walnames) > 0 {
			return DataDir2_0, nil
		}
	}
	if nameSet.ContainsAll([]string{"proxy"}) {
		return DataDir2_0Proxy, nil
	}
	return DataDirUnknown, nil
}

// Cluster only keeps the major.minor.
func Cluster(v string) string {
	vs := strings.Split(v, ".")
	if len(vs) <= 2 {
		return v
	}
	return fmt.Sprintf("%s.%s", vs[0], vs[1])
}
<|endoftext|>


<commit_before>package version

var (
	Release = "1.24.1-dev"
	GitHash string
)
<commit_msg>Bump version<commit_after>package version

var (
	Release = "1.24.2-dev"
	GitHash string
)
<|endoftext|>


<commit_before>package version

import (
	"fmt"
	"strings"
)

var (
	// The git commit that was compiled. These will be filled in by the
	// compiler.
	GitCommit   string
	GitDescribe string

	// The main version number that is being run at the moment.
	//
	// Version must conform to the format expected by github.com/hashicorp/go-version
	// for tests to work.
	Version = "0.9.3"

	// A pre-release marker for the version. If this is "" (empty string)
	// then it means that it is a final release. Otherwise, this is a pre-release
	// such as "dev" (in development), "beta", "rc1", etc.
	VersionPrerelease = "rc1"
)

// GetHumanVersion composes the parts of the version in a way that's suitable
// for displaying to humans.
func GetHumanVersion() string {
	version := Version
	if GitDescribe != "" {
		version = GitDescribe
	}

	release := VersionPrerelease
	if GitDescribe == "" && release == "" {
		release = "dev"
	}
	if release != "" {
		version += fmt.Sprintf("-%s", release)
		if GitCommit != "" {
			version += fmt.Sprintf(" (%s)", GitCommit)
		}
	}

	// Strip off any single quotes added by the git information.
	return strings.Replace(version, "'", "", -1)
}
<commit_msg>Puts the tree into 0.9.3-rc2 release mode.<commit_after>package version

import (
	"fmt"
	"strings"
)

var (
	// The git commit that was compiled. These will be filled in by the
	// compiler.
	GitCommit   string
	GitDescribe string

	// The main version number that is being run at the moment.
	//
	// Version must conform to the format expected by github.com/hashicorp/go-version
	// for tests to work.
	Version = "0.9.3"

	// A pre-release marker for the version. If this is "" (empty string)
	// then it means that it is a final release. Otherwise, this is a pre-release
	// such as "dev" (in development), "beta", "rc1", etc.
	VersionPrerelease = "rc2"
)

// GetHumanVersion composes the parts of the version in a way that's suitable
// for displaying to humans.
func GetHumanVersion() string {
	version := Version
	if GitDescribe != "" {
		version = GitDescribe
	}

	release := VersionPrerelease
	if GitDescribe == "" && release == "" {
		release = "dev"
	}
	if release != "" {
		version += fmt.Sprintf("-%s", release)
		if GitCommit != "" {
			version += fmt.Sprintf(" (%s)", GitCommit)
		}
	}

	// Strip off any single quotes added by the git information.
	return strings.Replace(version, "'", "", -1)
}
<|endoftext|>


<commit_before>/**
 *  Copyright 2014 Paul Querna
 *
 *  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 otp

import (
	"github.com/boombuler/barcode"
	"github.com/boombuler/barcode/qr"

	"crypto/md5"
	"crypto/sha1"
	"crypto/sha256"
	"crypto/sha512"
	"errors"
	"fmt"
	"hash"
	"image"
	"net/url"
	"strings"
	"strconv"
)

// Error when attempting to convert the secret from base32 to raw bytes.
var ErrValidateSecretInvalidBase32 = errors.New("Decoding of secret as base32 failed.")

// The user provided passcode length was not expected.
var ErrValidateInputInvalidLength = errors.New("Input length unexpected")

// When generating a Key, the Issuer must be set.
var ErrGenerateMissingIssuer = errors.New("Issuer must be set")

// When generating a Key, the Account Name must be set.
var ErrGenerateMissingAccountName = errors.New("AccountName must be set")

// Key represents an TOTP or HTOP key.
type Key struct {
	orig string
	url  *url.URL
}

// NewKeyFromURL creates a new Key from an TOTP or HOTP url.
//
// The URL format is documented here:
//   https://github.com/google/google-authenticator/wiki/Key-Uri-Format
//
func NewKeyFromURL(orig string) (*Key, error) {
	s := strings.TrimSpace(orig)

	u, err := url.Parse(s)

	if err != nil {
		return nil, err
	}

	return &Key{
		orig: s,
		url:  u,
	}, nil
}

func (k *Key) String() string {
	return k.orig
}

// Image returns an QR-Code image of the specified width and height,
// suitable for use by many clients like Google-Authenricator
// to enroll a user's TOTP/HOTP key.
func (k *Key) Image(width int, height int) (image.Image, error) {
	b, err := qr.Encode(k.orig, qr.M, qr.Auto)

	if err != nil {
		return nil, err
	}

	b, err = barcode.Scale(b, width, height)

	if err != nil {
		return nil, err
	}

	return b, nil
}

// Type returns "hotp" or "totp".
func (k *Key) Type() string {
	return k.url.Host
}

// Issuer returns the name of the issuing organization.
func (k *Key) Issuer() string {
	q := k.url.Query()

	issuer := q.Get("issuer")

	if issuer != "" {
		return issuer
	}

	p := strings.TrimPrefix(k.url.Path, "/")
	i := strings.Index(p, ":")

	if i == -1 {
		return ""
	}

	return p[:i]
}

// AccountName returns the name of the user's account.
func (k *Key) AccountName() string {
	p := strings.TrimPrefix(k.url.Path, "/")
	i := strings.Index(p, ":")

	if i == -1 {
		return p
	}

	return p[i+1:]
}

// Secret returns the opaque secret for this Key.
func (k *Key) Secret() string {
	q := k.url.Query()

	return q.Get("secret")
}

// Period returns a tiny int representing the rotation time in seconds.
func (k *Key) Period() uint64 {
	q := k.url.Query()

	if u, err := strconv.ParseUint(q.Get("period"), 10, 64); err == nil {
		return u
	}

	// If no period is defined 30 seconds is the default per (rfc6238)
	return 30
}

// URL returns the OTP URL as a string
func (k *Key) URL() string {
	return k.url.String()
}

// Algorithm represents the hashing function to use in the HMAC
// operation needed for OTPs.
type Algorithm int

const (
	AlgorithmSHA1 Algorithm = iota
	AlgorithmSHA256
	AlgorithmSHA512
	AlgorithmMD5
)

func (a Algorithm) String() string {
	switch a {
	case AlgorithmSHA1:
		return "SHA1"
	case AlgorithmSHA256:
		return "SHA256"
	case AlgorithmSHA512:
		return "SHA512"
	case AlgorithmMD5:
		return "MD5"
	}
	panic("unreached")
}

func (a Algorithm) Hash() hash.Hash {
	switch a {
	case AlgorithmSHA1:
		return sha1.New()
	case AlgorithmSHA256:
		return sha256.New()
	case AlgorithmSHA512:
		return sha512.New()
	case AlgorithmMD5:
		return md5.New()
	}
	panic("unreached")
}

// Digits represents the number of digits present in the
// user's OTP passcode. Six and Eight are the most common values.
type Digits int

const (
	DigitsSix   Digits = 6
	DigitsEight Digits = 8
)

// Format converts an integer into the zero-filled size for this Digits.
func (d Digits) Format(in int32) string {
	f := fmt.Sprintf("%%0%dd", d)
	return fmt.Sprintf(f, in)
}

// Length returns the number of characters for this Digits.
func (d Digits) Length() int {
	return int(d)
}

func (d Digits) String() string {
	return fmt.Sprintf("%d", d)
}
<commit_msg>Update otp.go (#57)<commit_after>/**
 *  Copyright 2014 Paul Querna
 *
 *  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 otp

import (
	"github.com/boombuler/barcode"
	"github.com/boombuler/barcode/qr"

	"crypto/md5"
	"crypto/sha1"
	"crypto/sha256"
	"crypto/sha512"
	"errors"
	"fmt"
	"hash"
	"image"
	"net/url"
	"strings"
	"strconv"
)

// Error when attempting to convert the secret from base32 to raw bytes.
var ErrValidateSecretInvalidBase32 = errors.New("Decoding of secret as base32 failed.")

// The user provided passcode length was not expected.
var ErrValidateInputInvalidLength = errors.New("Input length unexpected")

// When generating a Key, the Issuer must be set.
var ErrGenerateMissingIssuer = errors.New("Issuer must be set")

// When generating a Key, the Account Name must be set.
var ErrGenerateMissingAccountName = errors.New("AccountName must be set")

// Key represents an TOTP or HTOP key.
type Key struct {
	orig string
	url  *url.URL
}

// NewKeyFromURL creates a new Key from an TOTP or HOTP url.
//
// The URL format is documented here:
//   https://github.com/google/google-authenticator/wiki/Key-Uri-Format
//
func NewKeyFromURL(orig string) (*Key, error) {
	s := strings.TrimSpace(orig)

	u, err := url.Parse(s)

	if err != nil {
		return nil, err
	}

	return &Key{
		orig: s,
		url:  u,
	}, nil
}

func (k *Key) String() string {
	return k.orig
}

// Image returns an QR-Code image of the specified width and height,
// suitable for use by many clients like Google-Authenricator
// to enroll a user's TOTP/HOTP key.
func (k *Key) Image(width int, height int) (image.Image, error) {
	b, err := qr.Encode(k.orig, qr.M, qr.Auto)

	if err != nil {
		return nil, err
	}

	b, err = barcode.Scale(b, width, height)

	if err != nil {
		return nil, err
	}

	return b, nil
}

// Type returns "hotp" or "totp".
func (k *Key) Type() string {
	return k.url.Host
}

// Issuer returns the name of the issuing organization.
func (k *Key) Issuer() string {
	q := k.url.Query()

	issuer := q.Get("issuer")

	if issuer != "" {
		return issuer
	}

	p := strings.TrimPrefix(k.url.Path, "/")
	i := strings.Index(p, ":")

	if i == -1 {
		return ""
	}

	return p[:i]
}

// AccountName returns the name of the user's account.
func (k *Key) AccountName() string {
	p := strings.TrimPrefix(k.url.Path, "/")
	i := strings.Index(p, ":")

	if i == -1 {
		return p
	}

	return p[i+1:]
}

// Secret returns the opaque secret for this Key.
func (k *Key) Secret() string {
	q := k.url.Query()

	return q.Get("secret")
}

// Period returns a tiny int representing the rotation time in seconds.
func (k *Key) Period() uint64 {
	q := k.url.Query()

	if u, err := strconv.ParseUint(q.Get("period"), 10, 64); err == nil {
		return u
	}

	// If no period is defined 30 seconds is the default per (rfc6238)
	return 30
}

// URL returns the OTP URL as a string
func (k *Key) URL() string {
	return k.url.String()
}

// Algorithm represents the hashing function to use in the HMAC
// operation needed for OTPs.
type Algorithm int

const (
	// AlgorithmSHA1 should be used for compatibility with Google Authenticator.
	//
	// See https://github.com/pquerna/otp/issues/55 for additional details.
	AlgorithmSHA1 Algorithm = iota
	AlgorithmSHA256
	AlgorithmSHA512
	AlgorithmMD5
)

func (a Algorithm) String() string {
	switch a {
	case AlgorithmSHA1:
		return "SHA1"
	case AlgorithmSHA256:
		return "SHA256"
	case AlgorithmSHA512:
		return "SHA512"
	case AlgorithmMD5:
		return "MD5"
	}
	panic("unreached")
}

func (a Algorithm) Hash() hash.Hash {
	switch a {
	case AlgorithmSHA1:
		return sha1.New()
	case AlgorithmSHA256:
		return sha256.New()
	case AlgorithmSHA512:
		return sha512.New()
	case AlgorithmMD5:
		return md5.New()
	}
	panic("unreached")
}

// Digits represents the number of digits present in the
// user's OTP passcode. Six and Eight are the most common values.
type Digits int

const (
	DigitsSix   Digits = 6
	DigitsEight Digits = 8
)

// Format converts an integer into the zero-filled size for this Digits.
func (d Digits) Format(in int32) string {
	f := fmt.Sprintf("%%0%dd", d)
	return fmt.Sprintf(f, in)
}

// Length returns the number of characters for this Digits.
func (d Digits) Length() int {
	return int(d)
}

func (d Digits) String() string {
	return fmt.Sprintf("%d", d)
}
<|endoftext|>


<commit_before>package version

const (
	Version = "0.1.9"
)
<commit_msg>version: 0.1.9+git bump<commit_after>package version

const (
	Version = "0.1.9+git"
)
<|endoftext|>


<commit_before>package version

const Version = "1.3.4"
<commit_msg>chore(version): 1.3.5<commit_after>package version

const Version = "1.3.5"
<|endoftext|>


<commit_before>// Copyright 2011 Karl Sackett <karl.sackett@gmail.com>
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.

// p03.go
// Find the largest prime factor of a composite number.

package main

import (
	"big"
	"os"
	"fmt"
	"strconv"
	//"rand"
)

// Euclid's algorithm to compute the greatest common divisor of two integers.
//func euclid(a int, b int) int {
//	if b == 0 {
//		return a
//	}
//	return euclid(b, a%b)
//}

// Pollard-Rho heuristic to factor a large integer.
func pollardRho(n Int64) []Int64 {
	var f []Int64
	d := new(big.Int)
	i := 11
	//x := rand.Intn(n)
	x := new(big.Int).SetInt64(2)
	y := x
	k := 2
	for j := 0; j < 10; j++ {
		i++
		fmt.Println(x, y)
		x = ((x * x) - 1) % n
		//d = euclid((y - x), n)
		big.GcdInt(d, nil, nil, (y - x), n)
		if d != 1 && d != n {
			fmt.Println(d)
			f = append(f, d.Int64)
		}
		if i == k {
			y = x
			k = k * 2
		}
	}
	return f
}

func main() {
	var p []big.Int
	c, _ := strconv.Atoi(os.Args[1])
	p = pollardRho(c)

	fmt.Println(p)
}

<commit_msg>Remove p03.go.<commit_after><|endoftext|>


<commit_before>// Package version holds some version data common to bosun and scollector.
// Most of these values will be inserted at build time with `-ldFlags` directives for official builds.
package version // import "bosun.org/version"

import (
	"fmt"
	"time"
)

// These variables will be set at linking time for official builds.
// build.go will set date and sha, but `go get` will set none of these.
var (
	// Version number for official releases Updated manually before each release.
	Version = "0.2.0"

	// Set to any non-empty value by official release script
	OfficialBuild string
	// Date and time of build. Should be in YYYYMMDDHHMMSS format
	VersionDate string
	// VersionSHA should be set at build time as the most recent commit hash.
	VersionSHA string
)

// Get a string representing the version information for the current binary.
func GetVersionInfo(app string) string {
	if OfficialBuild == "" {
		Version = Version + "-dev"
	}
	timeString := ""
	buildTime, err := time.Parse("20060102150405", VersionDate)
	if err == nil {
		timeString = " Built " + buildTime.Format(time.RFC822)
	}
	return fmt.Sprintf("%s version %v (%v)%s\n", app, Version, VersionSHA, timeString)
}
<commit_msg>version: improved output<commit_after>// Package version holds some version data common to bosun and scollector.
// Most of these values will be inserted at build time with `-ldFlags` directives for official builds.
package version // import "bosun.org/version"

import (
	"fmt"
	"time"
)

// These variables will be set at linking time for official builds.
// build.go will set date and sha, but `go get` will set none of these.
var (
	// Version number for official releases Updated manually before each release.
	Version = "0.2.0"

	// Set to any non-empty value by official release script
	OfficialBuild string
	// Date and time of build. Should be in YYYYMMDDHHMMSS format
	VersionDate string
	// VersionSHA should be set at build time as the most recent commit hash.
	VersionSHA string
)

// Get a string representing the version information for the current binary.
func GetVersionInfo(app string) string {
	var sha, build string
	version := Version
	if OfficialBuild == "" {
		version += "-dev"
	}
	if buildTime, err := time.Parse("20060102150405", VersionDate); err == nil {
		build = " built " + buildTime.Format(time.RFC3339)
	}
	if VersionSHA != "" {
		sha = fmt.Sprintf(" (%s)", VersionSHA)
	}
	return fmt.Sprintf("%s version %s%s%s", app, version, sha, build)
}
<|endoftext|>


<commit_before>package xenserver

import (
	"bytes"
	gossh "code.google.com/p/go.crypto/ssh"
	"fmt"
	"github.com/mitchellh/multistep"
	commonssh "github.com/mitchellh/packer/common/ssh"
	"github.com/mitchellh/packer/communicator/ssh"
	"io"
	"log"
	"net"
	"strings"
)

func sshAddress(state multistep.StateBag) (string, error) {
	sshIP := state.Get("ssh_address").(string)
	sshHostPort := 22
	return fmt.Sprintf("%s:%d", sshIP, sshHostPort), nil
}

func sshLocalAddress(state multistep.StateBag) (string, error) {
	sshLocalPort := state.Get("local_ssh_port").(uint)
	conn_str := fmt.Sprintf("%s:%d", "127.0.0.1", sshLocalPort)
	log.Printf("sshLocalAddress: %s", conn_str)
	return conn_str, nil
}

func sshConfig(state multistep.StateBag) (*gossh.ClientConfig, error) {
	config := state.Get("config").(config)

	auth := []gossh.AuthMethod{
		gossh.Password(config.SSHPassword),
		gossh.KeyboardInteractive(
			ssh.PasswordKeyboardInteractive(config.SSHPassword)),
	}

	if config.SSHKeyPath != "" {
		signer, err := commonssh.FileSigner(config.SSHKeyPath)
		if err != nil {
			return nil, err
		}

		auth = append(auth, gossh.PublicKeys(signer))
	}

	return &gossh.ClientConfig{
		User: config.SSHUser,
		Auth: auth,
	}, nil
}

func execute_ssh_cmd(cmd, host, port, username, password string) (stdout string, err error) {
	// Setup connection config
	config := &gossh.ClientConfig{
		User: username,
		Auth: []gossh.AuthMethod{
			gossh.Password(password),
		},
	}

	client, err := gossh.Dial("tcp", host+":"+port, config)

	if err != nil {
		return "", err
	}

	//Create session
	session, err := client.NewSession()

	if err != nil {
		return "", err
	}

	defer session.Close()

	var b bytes.Buffer
	session.Stdout = &b
	if err := session.Run(cmd); err != nil {
		return "", err
	}

	session.Close()
	return strings.Trim(b.String(), "\n"), nil
}

func forward(local_conn net.Conn, config *gossh.ClientConfig, server, remote_dest string, remote_port uint) error {
	ssh_client_conn, err := gossh.Dial("tcp", server+":22", config)
	if err != nil {
		log.Printf("local ssh.Dial error: %s", err)
		return err
	}

	remote_loc := fmt.Sprintf("%s:%d", remote_dest, remote_port)
	ssh_conn, err := ssh_client_conn.Dial("tcp", remote_loc)
	if err != nil {
		log.Printf("ssh.Dial error: %s", err)
		return err
	}

	go func() {
		_, err = io.Copy(ssh_conn, local_conn)
		if err != nil {
			log.Printf("io.copy failed: %v", err)
		}
	}()

	go func() {
		_, err = io.Copy(local_conn, ssh_conn)
		if err != nil {
			log.Printf("io.copy failed: %v", err)
		}
	}()

	return nil
}

func ssh_port_forward(local_port uint, remote_port uint, remote_dest, host, username, password string) error {

	config := &gossh.ClientConfig{
		User: username,
		Auth: []gossh.AuthMethod{
			gossh.Password(password),
		},
	}

	// Listen on a local port
	local_listener, err := net.Listen("tcp",
		fmt.Sprintf("%s:%d",
			"127.0.0.1",
			local_port))
	if err != nil {
		log.Printf("Local listen failed: %s", err)
		return err
	}

	for {
		local_connection, err := local_listener.Accept()

		if err != nil {
			log.Printf("Local accept failed: %s", err)
			return err
		}

		// Forward to a remote port
		go forward(local_connection, config, host, remote_dest, remote_port)
	}

	return nil
}
<commit_msg>Don't close session twice<commit_after>package xenserver

import (
	"bytes"
	gossh "code.google.com/p/go.crypto/ssh"
	"fmt"
	"github.com/mitchellh/multistep"
	commonssh "github.com/mitchellh/packer/common/ssh"
	"github.com/mitchellh/packer/communicator/ssh"
	"io"
	"log"
	"net"
	"strings"
)

func sshAddress(state multistep.StateBag) (string, error) {
	sshIP := state.Get("ssh_address").(string)
	sshHostPort := 22
	return fmt.Sprintf("%s:%d", sshIP, sshHostPort), nil
}

func sshLocalAddress(state multistep.StateBag) (string, error) {
	sshLocalPort := state.Get("local_ssh_port").(uint)
	conn_str := fmt.Sprintf("%s:%d", "127.0.0.1", sshLocalPort)
	log.Printf("sshLocalAddress: %s", conn_str)
	return conn_str, nil
}

func sshConfig(state multistep.StateBag) (*gossh.ClientConfig, error) {
	config := state.Get("config").(config)

	auth := []gossh.AuthMethod{
		gossh.Password(config.SSHPassword),
		gossh.KeyboardInteractive(
			ssh.PasswordKeyboardInteractive(config.SSHPassword)),
	}

	if config.SSHKeyPath != "" {
		signer, err := commonssh.FileSigner(config.SSHKeyPath)
		if err != nil {
			return nil, err
		}

		auth = append(auth, gossh.PublicKeys(signer))
	}

	return &gossh.ClientConfig{
		User: config.SSHUser,
		Auth: auth,
	}, nil
}

func execute_ssh_cmd(cmd, host, port, username, password string) (stdout string, err error) {
	// Setup connection config
	config := &gossh.ClientConfig{
		User: username,
		Auth: []gossh.AuthMethod{
			gossh.Password(password),
		},
	}

	client, err := gossh.Dial("tcp", host+":"+port, config)

	if err != nil {
		return "", err
	}

	//Create session
	session, err := client.NewSession()

	if err != nil {
		return "", err
	}

	defer session.Close()

	var b bytes.Buffer
	session.Stdout = &b
	if err := session.Run(cmd); err != nil {
		return "", err
	}

	return strings.Trim(b.String(), "\n"), nil
}

func forward(local_conn net.Conn, config *gossh.ClientConfig, server, remote_dest string, remote_port uint) error {
	ssh_client_conn, err := gossh.Dial("tcp", server+":22", config)
	if err != nil {
		log.Printf("local ssh.Dial error: %s", err)
		return err
	}

	remote_loc := fmt.Sprintf("%s:%d", remote_dest, remote_port)
	ssh_conn, err := ssh_client_conn.Dial("tcp", remote_loc)
	if err != nil {
		log.Printf("ssh.Dial error: %s", err)
		return err
	}

	go func() {
		_, err = io.Copy(ssh_conn, local_conn)
		if err != nil {
			log.Printf("io.copy failed: %v", err)
		}
	}()

	go func() {
		_, err = io.Copy(local_conn, ssh_conn)
		if err != nil {
			log.Printf("io.copy failed: %v", err)
		}
	}()

	return nil
}

func ssh_port_forward(local_port uint, remote_port uint, remote_dest, host, username, password string) error {

	config := &gossh.ClientConfig{
		User: username,
		Auth: []gossh.AuthMethod{
			gossh.Password(password),
		},
	}

	// Listen on a local port
	local_listener, err := net.Listen("tcp",
		fmt.Sprintf("%s:%d",
			"127.0.0.1",
			local_port))
	if err != nil {
		log.Printf("Local listen failed: %s", err)
		return err
	}

	for {
		local_connection, err := local_listener.Accept()

		if err != nil {
			log.Printf("Local accept failed: %s", err)
			return err
		}

		// Forward to a remote port
		go forward(local_connection, config, host, remote_dest, remote_port)
	}

	return nil
}
<|endoftext|>


<commit_before>package builtincmd

import "io"
import "os"
import "os/exec"
import "strings"
import "fmt"
import "bytes"
import "path/filepath"
import "bufio"

import "../interpreter"
import "../ls"

func cmd_exit(cmd *exec.Cmd) interpreter.WhatToDoAfterCmd {
	return interpreter.SHUTDOWN
}

func getHome() string {
	home := os.Getenv("HOME")
	if home != "" {
		return home
	}
	homeDrive := os.Getenv("HOMEDRIVE")
	if homeDrive != "" {
		homePath := os.Getenv("HOMEPATH")
		if homePath != "" {
			return homeDrive + homePath
		}
	}
	return ""
}

func cmd_pwd(cmd *exec.Cmd) interpreter.WhatToDoAfterCmd {
	wd, _ := os.Getwd()
	io.WriteString(cmd.Stdout, wd)
	io.WriteString(cmd.Stdout, "\n")
	return interpreter.CONTINUE
}

func cmd_cd(cmd *exec.Cmd) interpreter.WhatToDoAfterCmd {
	if len(cmd.Args) >= 2 {
		os.Chdir(cmd.Args[1])
		return interpreter.CONTINUE
	}
	home := getHome()
	if home != "" {
		os.Chdir(home)
		return interpreter.CONTINUE
	}
	return cmd_pwd(cmd)
}

func cmd_ls(cmd *exec.Cmd) interpreter.WhatToDoAfterCmd {
	ls.Main(cmd.Args[1:], cmd.Stdout)
	return interpreter.CONTINUE
}

func cmd_set(cmd *exec.Cmd) interpreter.WhatToDoAfterCmd {
	if len(cmd.Args) <= 1 {
		for _, val := range os.Environ() {
			fmt.Fprintf(cmd.Stdout, "%s\n", val)
		}
		return interpreter.CONTINUE
	}
	for _, arg := range cmd.Args[1:] {
		eqlPos := strings.Index(arg, "=")
		if eqlPos < 0 {
			fmt.Fprintf(cmd.Stdout, "%s=%s\n", arg, os.Getenv(arg))
		} else {
			os.Setenv(arg[:eqlPos], arg[eqlPos+1:])
		}
	}
	return interpreter.CONTINUE
}

func cmd_source(cmd *exec.Cmd) interpreter.WhatToDoAfterCmd {
	envTxtPath := filepath.Join(
		os.TempDir(),
		fmt.Sprintf("nyagos-%d.tmp", os.Getpid()))

	var buffer bytes.Buffer

	buffer.WriteString(cmd.Args[1])
	buffer.WriteString(" & set > ")
	buffer.WriteString(envTxtPath)

	args := make([]string, 3)
	args[0] = os.Getenv("COMSPEC")
	args[1] = "/c"
	args[2] = buffer.String()
	var cmd2 exec.Cmd
	cmd2.Path = args[0]
	cmd2.Args = args
	cmd2.Env = nil
	cmd2.Dir = ""
	err := cmd2.Run()
	if err != nil {
		fmt.Fprintf(cmd.Stderr, "%s\n", err.Error())
	} else {
		fp, err := os.Open(envTxtPath)
		if err != nil {
			fmt.Fprintf(cmd.Stderr, "%s\n", err.Error())
			return interpreter.CONTINUE
		}
		defer os.Remove(envTxtPath)
		defer fp.Close()

		scr := bufio.NewScanner(fp)
		for scr.Scan() {
			line := scr.Text()
			eqlPos := strings.Index(line, "=")
			if eqlPos > 0 {
				os.Setenv(line[:eqlPos], line[eqlPos+1:])
			}
		}
	}
	return interpreter.CONTINUE
}

var buildInCmd = map[string]func(cmd *exec.Cmd) interpreter.WhatToDoAfterCmd{
	"cd":     cmd_cd,
	"exit":   cmd_exit,
	"ls":     cmd_ls,
	"set":    cmd_set,
	".":      cmd_source,
	"source": cmd_source,
}

func Exec(cmd *exec.Cmd, IsBackground bool) (interpreter.WhatToDoAfterCmd, error) {
	name := strings.ToLower(cmd.Args[0])
	if len(name) == 2 && strings.HasSuffix(name, ":") {
		os.Chdir(name + ".")
		return interpreter.CONTINUE, nil
	}
	function, ok := buildInCmd[name]
	if ok {
		return function(cmd), nil
	} else {
		return interpreter.THROUGH, nil
	}
}
<commit_msg>ls で存在しないオプションがあった時にエラーを表示しない不具合を修正<commit_after>package builtincmd

import "io"
import "os"
import "os/exec"
import "strings"
import "fmt"
import "bytes"
import "path/filepath"
import "bufio"

import "../interpreter"
import "../ls"

func cmd_exit(cmd *exec.Cmd) interpreter.WhatToDoAfterCmd {
	return interpreter.SHUTDOWN
}

func getHome() string {
	home := os.Getenv("HOME")
	if home != "" {
		return home
	}
	homeDrive := os.Getenv("HOMEDRIVE")
	if homeDrive != "" {
		homePath := os.Getenv("HOMEPATH")
		if homePath != "" {
			return homeDrive + homePath
		}
	}
	return ""
}

func cmd_pwd(cmd *exec.Cmd) interpreter.WhatToDoAfterCmd {
	wd, _ := os.Getwd()
	io.WriteString(cmd.Stdout, wd)
	io.WriteString(cmd.Stdout, "\n")
	return interpreter.CONTINUE
}

func cmd_cd(cmd *exec.Cmd) interpreter.WhatToDoAfterCmd {
	if len(cmd.Args) >= 2 {
		os.Chdir(cmd.Args[1])
		return interpreter.CONTINUE
	}
	home := getHome()
	if home != "" {
		os.Chdir(home)
		return interpreter.CONTINUE
	}
	return cmd_pwd(cmd)
}

func cmd_ls(cmd *exec.Cmd) interpreter.WhatToDoAfterCmd {
	err := ls.Main(cmd.Args[1:], cmd.Stdout)
	if err != nil {
		io.WriteString( cmd.Stderr , err.Error() )
		io.WriteString( cmd.Stderr , "\n" )
	}
	return interpreter.CONTINUE
}

func cmd_set(cmd *exec.Cmd) interpreter.WhatToDoAfterCmd {
	if len(cmd.Args) <= 1 {
		for _, val := range os.Environ() {
			fmt.Fprintf(cmd.Stdout, "%s\n", val)
		}
		return interpreter.CONTINUE
	}
	for _, arg := range cmd.Args[1:] {
		eqlPos := strings.Index(arg, "=")
		if eqlPos < 0 {
			fmt.Fprintf(cmd.Stdout, "%s=%s\n", arg, os.Getenv(arg))
		} else {
			os.Setenv(arg[:eqlPos], arg[eqlPos+1:])
		}
	}
	return interpreter.CONTINUE
}

func cmd_source(cmd *exec.Cmd) interpreter.WhatToDoAfterCmd {
	envTxtPath := filepath.Join(
		os.TempDir(),
		fmt.Sprintf("nyagos-%d.tmp", os.Getpid()))

	var buffer bytes.Buffer

	buffer.WriteString(cmd.Args[1])
	buffer.WriteString(" & set > ")
	buffer.WriteString(envTxtPath)

	args := make([]string, 3)
	args[0] = os.Getenv("COMSPEC")
	args[1] = "/c"
	args[2] = buffer.String()
	var cmd2 exec.Cmd
	cmd2.Path = args[0]
	cmd2.Args = args
	cmd2.Env = nil
	cmd2.Dir = ""
	err := cmd2.Run()
	if err != nil {
		fmt.Fprintf(cmd.Stderr, "%s\n", err.Error())
	} else {
		fp, err := os.Open(envTxtPath)
		if err != nil {
			fmt.Fprintf(cmd.Stderr, "%s\n", err.Error())
			return interpreter.CONTINUE
		}
		defer os.Remove(envTxtPath)
		defer fp.Close()

		scr := bufio.NewScanner(fp)
		for scr.Scan() {
			line := scr.Text()
			eqlPos := strings.Index(line, "=")
			if eqlPos > 0 {
				os.Setenv(line[:eqlPos], line[eqlPos+1:])
			}
		}
	}
	return interpreter.CONTINUE
}

var buildInCmd = map[string]func(cmd *exec.Cmd) interpreter.WhatToDoAfterCmd{
	"cd":     cmd_cd,
	"exit":   cmd_exit,
	"ls":     cmd_ls,
	"set":    cmd_set,
	".":      cmd_source,
	"source": cmd_source,
}

func Exec(cmd *exec.Cmd, IsBackground bool) (interpreter.WhatToDoAfterCmd, error) {
	name := strings.ToLower(cmd.Args[0])
	if len(name) == 2 && strings.HasSuffix(name, ":") {
		os.Chdir(name + ".")
		return interpreter.CONTINUE, nil
	}
	function, ok := buildInCmd[name]
	if ok {
		return function(cmd), nil
	} else {
		return interpreter.THROUGH, nil
	}
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"fmt"
	"go/build"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"runtime"
	"strings"

	"github.com/mgutz/ansi"
	"golang.org/x/tools/cover"
)

const (
	usageMessage = `go-carpet - show test coverage for Go source files

usage: go-carpet [options] [paths]`

	appVersion = "1.8"

	// predefined go test options
	goTestCoverProfile = "-coverprofile"
	goTestCoverMode    = "-covermode"
)

var (
	reNewLine        = regexp.MustCompile("\n")
	reWindowsPathFix = regexp.MustCompile(`^_\\([A-Z])_`)

	// vendors directories for skip
	vendorDirs = []string{"Godeps", "vendor", ".vendor", "_vendor"}

	// directories for skip
	skipDirs = []string{"testdata"}

	errIsNotInGoMod = fmt.Errorf("is not in go modules")
)

func getDirsWithTests(includeVendor bool, roots ...string) (result []string, err error) {
	if len(roots) == 0 {
		roots = []string{"."}
	}

	dirs := map[string]struct{}{}
	for _, root := range roots {
		err = filepath.Walk(root, func(path string, _ os.FileInfo, _ error) error {
			if strings.HasSuffix(path, "_test.go") {
				dirs[filepath.Dir(path)] = struct{}{}
			}
			return nil
		})
		if err != nil {
			return result, err
		}
	}

	result = make([]string, 0, len(dirs))
	for dir := range dirs {
		if !includeVendor && isSliceInStringPrefix(dir, vendorDirs) || isSliceInStringPrefix(dir, skipDirs) {
			continue
		}
		result = append(result, "./"+dir)
	}

	return result, nil
}

func readFile(fileName string) (result []byte, err error) {
	fileReader, err := os.Open(fileName)
	if err != nil {
		return result, err
	}

	result, err = ioutil.ReadAll(fileReader)
	if err == nil {
		err = fileReader.Close()
	}

	return result, err
}

func getShadeOfGreen(normCover float64) string {
	/*
		Get all colors for 255-colors terminal:
			gommand 'for i := 0; i < 256; i++ {fmt.Println(i, ansi.ColorCode(strconv.Itoa(i)) + "String" + ansi.ColorCode("reset"))}'
	*/
	var tenShadesOfGreen = [...]string{
		"29",
		"30",
		"34",
		"36",
		"40",
		"42",
		"46",
		"48",
		"50",
		"51",
	}
	if normCover < 0 {
		normCover = 0
	}
	if normCover > 1 {
		normCover = 1
	}
	index := int((normCover - 0.00001) * float64(len(tenShadesOfGreen)))
	return tenShadesOfGreen[index]
}

func runGoTest(path string, coverFileName string, goTestArgs []string, hideStderr bool) error {
	args := []string{"test", goTestCoverProfile + "=" + coverFileName, goTestCoverMode + "=count"}
	args = append(args, goTestArgs...)
	args = append(args, path)
	osExec := exec.Command("go", args...) // #nosec
	if !hideStderr {
		osExec.Stderr = os.Stderr
	}

	if output, err := osExec.Output(); err != nil {
		fmt.Print(string(output))
		return err
	}

	return nil
}

func guessAbsPathInGOPATH(GOPATH, relPath string) (absPath string, err error) {
	if GOPATH == "" {
		GOPATH = build.Default.GOPATH
		if GOPATH == "" {
			return "", fmt.Errorf("GOPATH is not set")
		}
	}

	gopathChunks := strings.Split(GOPATH, string(os.PathListSeparator))
	for _, gopathChunk := range gopathChunks {
		guessAbsPath := filepath.Join(gopathChunk, "src", relPath)
		if _, err = os.Stat(guessAbsPath); err == nil {
			absPath = guessAbsPath
			break
		}
	}

	if absPath == "" {
		return "", fmt.Errorf("file '%s' not found in GOPATH", relPath)
	}

	return absPath, err
}

func getCoverForDir(coverFileName string, filesFilter []string, config Config) (result []byte, profileBlocks []cover.ProfileBlock, err error) {
	coverProfile, err := cover.ParseProfiles(coverFileName)
	if err != nil {
		return result, profileBlocks, err
	}

	for _, fileProfile := range coverProfile {
		var fileName string
		if strings.HasPrefix(fileProfile.FileName, "/") {
			// TODO: what about windows?
			fileName = fileProfile.FileName
		} else if strings.HasPrefix(fileProfile.FileName, "_") {
			// absolute path (or relative in tests)
			if runtime.GOOS != "windows" {
				fileName = strings.TrimLeft(fileProfile.FileName, "_")
			} else {
				// "_\C_\Users\..." -> "C:\Users\..."
				fileName = reWindowsPathFix.ReplaceAllString(fileProfile.FileName, "$1:")
			}
		} else if fileName, err = guessAbsPathInGoMod(fileProfile.FileName); err != errIsNotInGoMod {
			if err != nil {
				return result, profileBlocks, err
			}
		} else {
			// file in one dir in GOPATH
			fileName, err = guessAbsPathInGOPATH(os.Getenv("GOPATH"), fileProfile.FileName)
			if err != nil {
				return result, profileBlocks, err
			}
		}

		if len(filesFilter) > 0 && !isSliceInString(fileName, filesFilter) {
			continue
		}

		var fileBytes []byte
		fileBytes, err = readFile(fileName)
		if err != nil {
			return result, profileBlocks, err
		}

		result = append(result, getCoverForFile(fileProfile, fileBytes, config)...)
		profileBlocks = append(profileBlocks, fileProfile.Blocks...)
	}

	return result, profileBlocks, err
}

func getColorHeader(header string, addUnderiline bool) string {
	result := ansi.ColorCode("yellow") +
		header + ansi.ColorCode("reset") + "\n"

	if addUnderiline {
		result += ansi.ColorCode("black+h") +
			strings.Repeat("~", len(header)) +
			ansi.ColorCode("reset") + "\n"
	}

	return result
}

// algorithms from Go-sources:
//   src/cmd/cover/html.go::percentCovered()
//   src/testing/cover.go::coverReport()
func getStatForProfileBlocks(fileProfileBlocks []cover.ProfileBlock) (stat float64) {
	var total, covered int64
	for _, profileBlock := range fileProfileBlocks {
		total += int64(profileBlock.NumStmt)
		if profileBlock.Count > 0 {
			covered += int64(profileBlock.NumStmt)
		}
	}
	if total > 0 {
		stat = float64(covered) / float64(total) * 100.0
	}

	return stat
}

func getCoverForFile(fileProfile *cover.Profile, fileBytes []byte, config Config) (result []byte) {
	stat := getStatForProfileBlocks(fileProfile.Blocks)

	textRanges, err := getFileFuncRanges(fileBytes, config.funcFilter)
	if err != nil {
		return result
	}

	var fileNameDisplay string
	if len(config.funcFilter) == 0 {
		fileNameDisplay = fmt.Sprintf("%s - %.1f%%", strings.TrimLeft(fileProfile.FileName, "_"), stat)
	} else {
		fileNameDisplay = strings.TrimLeft(fileProfile.FileName, "_")
	}

	if config.summary {
		return []byte(fileNameDisplay + "\n")
	}

	result = append(result, []byte(getColorHeader(fileNameDisplay, true))...)

	boundaries := fileProfile.Boundaries(fileBytes)

	for _, textRange := range textRanges {
		fileBytesPart := fileBytes[textRange.begin:textRange.end]
		curOffset := 0
		coverColor := ""

		for _, boundary := range boundaries {
			if boundary.Offset < textRange.begin || boundary.Offset > textRange.end {
				// skip boundary which is not in filter function
				continue
			}

			boundaryOffset := boundary.Offset - textRange.begin

			if boundaryOffset > curOffset {
				nextChunk := fileBytesPart[curOffset:boundaryOffset]
				// Add ansi color code in begin of each line (this fixed view in "less -R")
				if coverColor != "" && coverColor != ansi.ColorCode("reset") {
					nextChunk = reNewLine.ReplaceAllLiteral(nextChunk, []byte(ansi.ColorCode("reset")+"\n"+coverColor))
				}
				result = append(result, nextChunk...)
			}

			switch {
			case boundary.Start && boundary.Count > 0:
				coverColor = ansi.ColorCode("green")
				if config.colors256 {
					coverColor = ansi.ColorCode(getShadeOfGreen(boundary.Norm))
				}
			case boundary.Start && boundary.Count == 0:
				coverColor = ansi.ColorCode("red")
			case !boundary.Start:
				coverColor = ansi.ColorCode("reset")
			}
			result = append(result, []byte(coverColor)...)

			curOffset = boundaryOffset
		}
		if curOffset < len(fileBytesPart) {
			result = append(result, fileBytesPart[curOffset:]...)
		}

		result = append(result, []byte("\n")...)
	}

	return result
}

type textRange struct {
	begin, end int
}

func getFileFuncRanges(fileBytes []byte, funcs []string) (result []textRange, err error) {
	if len(funcs) == 0 {
		return []textRange{{
			begin: 0,
			end:   len(fileBytes),
		}}, nil
	}

	golangFuncs, err := getGolangFuncs(fileBytes)
	if err != nil {
		return nil, err
	}

	for _, existsFunc := range golangFuncs {
		for _, filterFuncName := range funcs {
			if existsFunc.Name == filterFuncName {
				result = append(result, textRange{begin: existsFunc.Begin - 1, end: existsFunc.End - 1})
			}
		}
	}

	if len(result) == 0 {
		return nil, fmt.Errorf("filter by functions: %v - not found", funcs)
	}

	return result, nil
}

func getTempFileName() (string, error) {
	tmpFile, err := ioutil.TempFile(".", "go-carpet-coverage-out-")
	if err != nil {
		return "", err
	}
	err = tmpFile.Close()
	if err != nil {
		return "", err
	}

	return tmpFile.Name(), nil
}

// Config - application config
type Config struct {
	filesFilterRaw string
	filesFilter    []string
	funcFilterRaw  string
	funcFilter     []string
	argsRaw        string
	colors256      bool
	includeVendor  bool
	summary        bool
}

var config Config

func init() {
	flag.StringVar(&config.filesFilterRaw, "file", "", "comma-separated list of files to test (default: all)")
	flag.StringVar(&config.funcFilterRaw, "func", "", "comma-separated functions list (default: all functions)")
	flag.BoolVar(&config.colors256, "256colors", false, "use more colors on 256-color terminal (indicate the level of coverage)")
	flag.BoolVar(&config.summary, "summary", false, "only show summary for each file")
	flag.BoolVar(&config.includeVendor, "include-vendor", false, "include vendor directories for show coverage (Godeps, vendor)")
	flag.StringVar(&config.argsRaw, "args", "", "pass additional arguments for go test")
	flag.Usage = func() {
		fmt.Println(usageMessage)
		flag.PrintDefaults()
		os.Exit(0)
	}
}

func main() {
	versionFl := flag.Bool("version", false, "get version")
	flag.Parse()

	if *versionFl {
		fmt.Println(appVersion)
		os.Exit(0)
	}

	config.filesFilter = grepEmptyStringSlice(strings.Split(config.filesFilterRaw, ","))
	config.funcFilter = grepEmptyStringSlice(strings.Split(config.funcFilterRaw, ","))
	additionalArgs, err := parseAdditionalArgs(config.argsRaw, []string{goTestCoverProfile, goTestCoverMode})
	if err != nil {
		log.Fatal(err)
	}

	testDirs := flag.Args()

	coverFileName, err := getTempFileName()
	if err != nil {
		log.Fatal(err)
	}
	defer func() {
		err = os.RemoveAll(coverFileName)
		if err != nil {
			log.Fatal(err)
		}
	}()

	stdOut := getColorWriter()
	allProfileBlocks := []cover.ProfileBlock{}

	if len(testDirs) > 0 {
		testDirs, err = getDirsWithTests(config.includeVendor, testDirs...)
	} else {
		testDirs, err = getDirsWithTests(config.includeVendor, ".")
	}
	if err != nil {
		log.Fatal(err)
	}

	for _, path := range testDirs {
		if err = runGoTest(path, coverFileName, additionalArgs, false); err != nil {
			log.Print(err)
			continue
		}

		coverInBytes, profileBlocks, errCover := getCoverForDir(coverFileName, config.filesFilter, config)
		if errCover != nil {
			log.Print(errCover)
			continue
		}
		_, err = stdOut.Write(coverInBytes)
		if err != nil {
			log.Fatal(err)
		}

		allProfileBlocks = append(allProfileBlocks, profileBlocks...)
	}

	if len(allProfileBlocks) > 0 && len(config.funcFilter) == 0 {
		stat := getStatForProfileBlocks(allProfileBlocks)
		totalCoverage := fmt.Sprintf("Coverage: %.1f%% of statements", stat)
		_, err = stdOut.Write([]byte(getColorHeader(totalCoverage, false)))
		if err != nil {
			log.Fatal(err)
		}
	}
}
<commit_msg>Changed -help output<commit_after>package main

import (
	"flag"
	"fmt"
	"go/build"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"runtime"
	"strings"

	"github.com/mgutz/ansi"
	"golang.org/x/tools/cover"
)

const (
	usageMessage = `go-carpet - show test coverage for Go source files

usage: go-carpet [options] [paths]`

	appVersion = "1.8"

	// predefined go test options
	goTestCoverProfile = "-coverprofile"
	goTestCoverMode    = "-covermode"
)

var (
	reNewLine        = regexp.MustCompile("\n")
	reWindowsPathFix = regexp.MustCompile(`^_\\([A-Z])_`)

	// vendors directories for skip
	vendorDirs = []string{"Godeps", "vendor", ".vendor", "_vendor"}

	// directories for skip
	skipDirs = []string{"testdata"}

	errIsNotInGoMod = fmt.Errorf("is not in go modules")
)

func getDirsWithTests(includeVendor bool, roots ...string) (result []string, err error) {
	if len(roots) == 0 {
		roots = []string{"."}
	}

	dirs := map[string]struct{}{}
	for _, root := range roots {
		err = filepath.Walk(root, func(path string, _ os.FileInfo, _ error) error {
			if strings.HasSuffix(path, "_test.go") {
				dirs[filepath.Dir(path)] = struct{}{}
			}
			return nil
		})
		if err != nil {
			return result, err
		}
	}

	result = make([]string, 0, len(dirs))
	for dir := range dirs {
		if !includeVendor && isSliceInStringPrefix(dir, vendorDirs) || isSliceInStringPrefix(dir, skipDirs) {
			continue
		}
		result = append(result, "./"+dir)
	}

	return result, nil
}

func readFile(fileName string) (result []byte, err error) {
	fileReader, err := os.Open(fileName)
	if err != nil {
		return result, err
	}

	result, err = ioutil.ReadAll(fileReader)
	if err == nil {
		err = fileReader.Close()
	}

	return result, err
}

func getShadeOfGreen(normCover float64) string {
	/*
		Get all colors for 255-colors terminal:
			gommand 'for i := 0; i < 256; i++ {fmt.Println(i, ansi.ColorCode(strconv.Itoa(i)) + "String" + ansi.ColorCode("reset"))}'
	*/
	var tenShadesOfGreen = [...]string{
		"29",
		"30",
		"34",
		"36",
		"40",
		"42",
		"46",
		"48",
		"50",
		"51",
	}
	if normCover < 0 {
		normCover = 0
	}
	if normCover > 1 {
		normCover = 1
	}
	index := int((normCover - 0.00001) * float64(len(tenShadesOfGreen)))
	return tenShadesOfGreen[index]
}

func runGoTest(path string, coverFileName string, goTestArgs []string, hideStderr bool) error {
	args := []string{"test", goTestCoverProfile + "=" + coverFileName, goTestCoverMode + "=count"}
	args = append(args, goTestArgs...)
	args = append(args, path)
	osExec := exec.Command("go", args...) // #nosec
	if !hideStderr {
		osExec.Stderr = os.Stderr
	}

	if output, err := osExec.Output(); err != nil {
		fmt.Print(string(output))
		return err
	}

	return nil
}

func guessAbsPathInGOPATH(GOPATH, relPath string) (absPath string, err error) {
	if GOPATH == "" {
		GOPATH = build.Default.GOPATH
		if GOPATH == "" {
			return "", fmt.Errorf("GOPATH is not set")
		}
	}

	gopathChunks := strings.Split(GOPATH, string(os.PathListSeparator))
	for _, gopathChunk := range gopathChunks {
		guessAbsPath := filepath.Join(gopathChunk, "src", relPath)
		if _, err = os.Stat(guessAbsPath); err == nil {
			absPath = guessAbsPath
			break
		}
	}

	if absPath == "" {
		return "", fmt.Errorf("file '%s' not found in GOPATH", relPath)
	}

	return absPath, err
}

func getCoverForDir(coverFileName string, filesFilter []string, config Config) (result []byte, profileBlocks []cover.ProfileBlock, err error) {
	coverProfile, err := cover.ParseProfiles(coverFileName)
	if err != nil {
		return result, profileBlocks, err
	}

	for _, fileProfile := range coverProfile {
		var fileName string
		if strings.HasPrefix(fileProfile.FileName, "/") {
			// TODO: what about windows?
			fileName = fileProfile.FileName
		} else if strings.HasPrefix(fileProfile.FileName, "_") {
			// absolute path (or relative in tests)
			if runtime.GOOS != "windows" {
				fileName = strings.TrimLeft(fileProfile.FileName, "_")
			} else {
				// "_\C_\Users\..." -> "C:\Users\..."
				fileName = reWindowsPathFix.ReplaceAllString(fileProfile.FileName, "$1:")
			}
		} else if fileName, err = guessAbsPathInGoMod(fileProfile.FileName); err != errIsNotInGoMod {
			if err != nil {
				return result, profileBlocks, err
			}
		} else {
			// file in one dir in GOPATH
			fileName, err = guessAbsPathInGOPATH(os.Getenv("GOPATH"), fileProfile.FileName)
			if err != nil {
				return result, profileBlocks, err
			}
		}

		if len(filesFilter) > 0 && !isSliceInString(fileName, filesFilter) {
			continue
		}

		var fileBytes []byte
		fileBytes, err = readFile(fileName)
		if err != nil {
			return result, profileBlocks, err
		}

		result = append(result, getCoverForFile(fileProfile, fileBytes, config)...)
		profileBlocks = append(profileBlocks, fileProfile.Blocks...)
	}

	return result, profileBlocks, err
}

func getColorHeader(header string, addUnderiline bool) string {
	result := ansi.ColorCode("yellow") +
		header + ansi.ColorCode("reset") + "\n"

	if addUnderiline {
		result += ansi.ColorCode("black+h") +
			strings.Repeat("~", len(header)) +
			ansi.ColorCode("reset") + "\n"
	}

	return result
}

// algorithms from Go-sources:
//   src/cmd/cover/html.go::percentCovered()
//   src/testing/cover.go::coverReport()
func getStatForProfileBlocks(fileProfileBlocks []cover.ProfileBlock) (stat float64) {
	var total, covered int64
	for _, profileBlock := range fileProfileBlocks {
		total += int64(profileBlock.NumStmt)
		if profileBlock.Count > 0 {
			covered += int64(profileBlock.NumStmt)
		}
	}
	if total > 0 {
		stat = float64(covered) / float64(total) * 100.0
	}

	return stat
}

func getCoverForFile(fileProfile *cover.Profile, fileBytes []byte, config Config) (result []byte) {
	stat := getStatForProfileBlocks(fileProfile.Blocks)

	textRanges, err := getFileFuncRanges(fileBytes, config.funcFilter)
	if err != nil {
		return result
	}

	var fileNameDisplay string
	if len(config.funcFilter) == 0 {
		fileNameDisplay = fmt.Sprintf("%s - %.1f%%", strings.TrimLeft(fileProfile.FileName, "_"), stat)
	} else {
		fileNameDisplay = strings.TrimLeft(fileProfile.FileName, "_")
	}

	if config.summary {
		return []byte(fileNameDisplay + "\n")
	}

	result = append(result, []byte(getColorHeader(fileNameDisplay, true))...)

	boundaries := fileProfile.Boundaries(fileBytes)

	for _, textRange := range textRanges {
		fileBytesPart := fileBytes[textRange.begin:textRange.end]
		curOffset := 0
		coverColor := ""

		for _, boundary := range boundaries {
			if boundary.Offset < textRange.begin || boundary.Offset > textRange.end {
				// skip boundary which is not in filter function
				continue
			}

			boundaryOffset := boundary.Offset - textRange.begin

			if boundaryOffset > curOffset {
				nextChunk := fileBytesPart[curOffset:boundaryOffset]
				// Add ansi color code in begin of each line (this fixed view in "less -R")
				if coverColor != "" && coverColor != ansi.ColorCode("reset") {
					nextChunk = reNewLine.ReplaceAllLiteral(nextChunk, []byte(ansi.ColorCode("reset")+"\n"+coverColor))
				}
				result = append(result, nextChunk...)
			}

			switch {
			case boundary.Start && boundary.Count > 0:
				coverColor = ansi.ColorCode("green")
				if config.colors256 {
					coverColor = ansi.ColorCode(getShadeOfGreen(boundary.Norm))
				}
			case boundary.Start && boundary.Count == 0:
				coverColor = ansi.ColorCode("red")
			case !boundary.Start:
				coverColor = ansi.ColorCode("reset")
			}
			result = append(result, []byte(coverColor)...)

			curOffset = boundaryOffset
		}
		if curOffset < len(fileBytesPart) {
			result = append(result, fileBytesPart[curOffset:]...)
		}

		result = append(result, []byte("\n")...)
	}

	return result
}

type textRange struct {
	begin, end int
}

func getFileFuncRanges(fileBytes []byte, funcs []string) (result []textRange, err error) {
	if len(funcs) == 0 {
		return []textRange{{
			begin: 0,
			end:   len(fileBytes),
		}}, nil
	}

	golangFuncs, err := getGolangFuncs(fileBytes)
	if err != nil {
		return nil, err
	}

	for _, existsFunc := range golangFuncs {
		for _, filterFuncName := range funcs {
			if existsFunc.Name == filterFuncName {
				result = append(result, textRange{begin: existsFunc.Begin - 1, end: existsFunc.End - 1})
			}
		}
	}

	if len(result) == 0 {
		return nil, fmt.Errorf("filter by functions: %v - not found", funcs)
	}

	return result, nil
}

func getTempFileName() (string, error) {
	tmpFile, err := ioutil.TempFile(".", "go-carpet-coverage-out-")
	if err != nil {
		return "", err
	}
	err = tmpFile.Close()
	if err != nil {
		return "", err
	}

	return tmpFile.Name(), nil
}

// Config - application config
type Config struct {
	filesFilterRaw string
	filesFilter    []string
	funcFilterRaw  string
	funcFilter     []string
	argsRaw        string
	colors256      bool
	includeVendor  bool
	summary        bool
}

var config Config

func init() {
	flag.StringVar(&config.filesFilterRaw, "file", "", "comma-separated list of `files` to test (default: all)")
	flag.StringVar(&config.funcFilterRaw, "func", "", "comma-separated `functions` list (default: all functions)")
	flag.BoolVar(&config.colors256, "256colors", false, "use more colors on 256-color terminal (indicate the level of coverage)")
	flag.BoolVar(&config.summary, "summary", false, "only show summary for each file")
	flag.BoolVar(&config.includeVendor, "include-vendor", false, "include vendor directories for show coverage (Godeps, vendor)")
	flag.StringVar(&config.argsRaw, "args", "", "pass additional `arguments` for go test")
	flag.Usage = func() {
		fmt.Println(usageMessage)
		flag.PrintDefaults()
		os.Exit(0)
	}
}

func main() {
	versionFl := flag.Bool("version", false, "get version")
	flag.Parse()

	if *versionFl {
		fmt.Println(appVersion)
		os.Exit(0)
	}

	config.filesFilter = grepEmptyStringSlice(strings.Split(config.filesFilterRaw, ","))
	config.funcFilter = grepEmptyStringSlice(strings.Split(config.funcFilterRaw, ","))
	additionalArgs, err := parseAdditionalArgs(config.argsRaw, []string{goTestCoverProfile, goTestCoverMode})
	if err != nil {
		log.Fatal(err)
	}

	testDirs := flag.Args()

	coverFileName, err := getTempFileName()
	if err != nil {
		log.Fatal(err)
	}
	defer func() {
		err = os.RemoveAll(coverFileName)
		if err != nil {
			log.Fatal(err)
		}
	}()

	stdOut := getColorWriter()
	allProfileBlocks := []cover.ProfileBlock{}

	if len(testDirs) > 0 {
		testDirs, err = getDirsWithTests(config.includeVendor, testDirs...)
	} else {
		testDirs, err = getDirsWithTests(config.includeVendor, ".")
	}
	if err != nil {
		log.Fatal(err)
	}

	for _, path := range testDirs {
		if err = runGoTest(path, coverFileName, additionalArgs, false); err != nil {
			log.Print(err)
			continue
		}

		coverInBytes, profileBlocks, errCover := getCoverForDir(coverFileName, config.filesFilter, config)
		if errCover != nil {
			log.Print(errCover)
			continue
		}
		_, err = stdOut.Write(coverInBytes)
		if err != nil {
			log.Fatal(err)
		}

		allProfileBlocks = append(allProfileBlocks, profileBlocks...)
	}

	if len(allProfileBlocks) > 0 && len(config.funcFilter) == 0 {
		stat := getStatForProfileBlocks(allProfileBlocks)
		totalCoverage := fmt.Sprintf("Coverage: %.1f%% of statements", stat)
		_, err = stdOut.Write([]byte(getColorHeader(totalCoverage, false)))
		if err != nil {
			log.Fatal(err)
		}
	}
}
<|endoftext|>


<commit_before>/*
Copyright 2015 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 e2e

import (
	"fmt"
	"path/filepath"
	"time"

	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/apiserver/pkg/authentication/serviceaccount"
	rbacv1beta1 "k8s.io/kubernetes/pkg/apis/rbac/v1beta1"
	"k8s.io/kubernetes/test/e2e/framework"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

const (
	// parent path to yaml test manifests.
	ingressManifestPath = "test/e2e/testing-manifests/ingress"

	// timeout on a single http request.
	reqTimeout = 10 * time.Second

	// healthz port used to verify glbc restarted correctly on the master.
	glbcHealthzPort = 8086

	// General cloud resource poll timeout (eg: create static ip, firewall etc)
	cloudResourcePollTimeout = 5 * time.Minute

	// Name of the config-map and key the ingress controller stores its uid in.
	uidConfigMap = "ingress-uid"
	uidKey       = "uid"

	// GCE only allows names < 64 characters, and the loadbalancer controller inserts
	// a single character of padding.
	nameLenLimit = 62
)

var _ = framework.KubeDescribe("Loadbalancing: L7", func() {
	defer GinkgoRecover()
	var (
		ns               string
		jig              *testJig
		conformanceTests []conformanceTests
	)
	f := framework.NewDefaultFramework("ingress")

	BeforeEach(func() {
		f.BeforeEach()
		jig = newTestJig(f.ClientSet)
		ns = f.Namespace.Name

		// this test wants powerful permissions.  Since the namespace names are unique, we can leave this
		// lying around so we don't have to race any caches
		framework.BindClusterRole(jig.client.Rbac(), "cluster-admin", f.Namespace.Name,
			rbacv1beta1.Subject{Kind: rbacv1beta1.ServiceAccountKind, Namespace: f.Namespace.Name, Name: "default"})

		err := framework.WaitForAuthorizationUpdate(jig.client.AuthorizationV1beta1(),
			serviceaccount.MakeUsername(f.Namespace.Name, "default"),
			"", "create", schema.GroupResource{Resource: "pods"}, true)
		framework.ExpectNoError(err)
	})

	// Before enabling this loadbalancer test in any other test list you must
	// make sure the associated project has enough quota. At the time of this
	// writing a GCE project is allowed 3 backend services by default. This
	// test requires at least 5.
	//
	// Slow by design ~10m for each "It" block dominated by loadbalancer setup time
	// TODO: write similar tests for nginx, haproxy and AWS Ingress.
	framework.KubeDescribe("GCE [Slow] [Feature:Ingress]", func() {
		var gceController *GCEIngressController

		// Platform specific setup
		BeforeEach(func() {
			framework.SkipUnlessProviderIs("gce", "gke")
			By("Initializing gce controller")
			gceController = &GCEIngressController{
				ns:    ns,
				c:     jig.client,
				cloud: framework.TestContext.CloudConfig,
			}
			gceController.init()
		})

		// Platform specific cleanup
		AfterEach(func() {
			if CurrentGinkgoTestDescription().Failed {
				framework.DescribeIng(ns)
			}
			if jig.ing == nil {
				By("No ingress created, no cleanup necessary")
				return
			}
			By("Deleting ingress")
			jig.deleteIngress()

			By("Cleaning up cloud resources")
			cleanupGCE(gceController)
		})

		It("should conform to Ingress spec", func() {
			conformanceTests = createComformanceTests(jig, ns)
			for _, t := range conformanceTests {
				By(t.entryLog)
				t.execute()
				By(t.exitLog)
				jig.waitForIngress(true)
			}
		})

		It("shoud create ingress with given static-ip", func() {
			// ip released when the rest of lb resources are deleted in cleanupGCE
			ip := gceController.createStaticIP(ns)
			By(fmt.Sprintf("allocated static ip %v: %v through the GCE cloud provider", ns, ip))

			jig.createIngress(filepath.Join(ingressManifestPath, "static-ip"), ns, map[string]string{
				"kubernetes.io/ingress.global-static-ip-name": ns,
				"kubernetes.io/ingress.allow-http":            "false",
			})

			By("waiting for Ingress to come up with ip: " + ip)
			httpClient := buildInsecureClient(reqTimeout)
			framework.ExpectNoError(framework.PollURL(fmt.Sprintf("https://%v/", ip), "", framework.LoadBalancerPollTimeout, jig.pollInterval, httpClient, false))

			By("should reject HTTP traffic")
			framework.ExpectNoError(framework.PollURL(fmt.Sprintf("http://%v/", ip), "", framework.LoadBalancerPollTimeout, jig.pollInterval, httpClient, true))

			By("should have correct firewall rule for ingress")
			fw := gceController.getFirewallRule()
			expFw := jig.constructFirewallForIngress(gceController)
			// Passed the last argument as `true` to verify the backend ports is a subset
			// of the allowed ports in firewall rule, given there may be other existing
			// ingress resources and backends we are not aware of.
			Expect(framework.VerifyFirewallRule(fw, expFw, gceController.cloud.Network, true)).NotTo(HaveOccurred())

			// TODO: uncomment the restart test once we have a way to synchronize
			// and know that the controller has resumed watching. If we delete
			// the ingress before the controller is ready we will leak.
			// By("restaring glbc")
			// restarter := NewRestartConfig(
			//	 framework.GetMasterHost(), "glbc", glbcHealthzPort, restartPollInterval, restartTimeout)
			// restarter.restart()
			// By("should continue serving on provided static-ip for 30 seconds")
			// ExpectNoError(jig.verifyURL(fmt.Sprintf("https://%v/", ip), "", 30, 1*time.Second, httpClient))
		})

		// TODO: Implement a multizone e2e that verifies traffic reaches each
		// zone based on pod labels.
	})

	// Time: borderline 5m, slow by design
	framework.KubeDescribe("Nginx", func() {
		var nginxController *NginxIngressController

		BeforeEach(func() {
			framework.SkipUnlessProviderIs("gce", "gke")
			By("Initializing nginx controller")
			jig.class = "nginx"
			nginxController = &NginxIngressController{ns: ns, c: jig.client}

			// TODO: This test may fail on other platforms. We can simply skip it
			// but we want to allow easy testing where a user might've hand
			// configured firewalls.
			if framework.ProviderIs("gce", "gke") {
				framework.ExpectNoError(gcloudCreate("firewall-rules", fmt.Sprintf("ingress-80-443-%v", ns), framework.TestContext.CloudConfig.ProjectID, "--allow", "tcp:80,tcp:443", "--network", framework.TestContext.CloudConfig.Network))
			} else {
				framework.Logf("WARNING: Not running on GCE/GKE, cannot create firewall rules for :80, :443. Assuming traffic can reach the external ips of all nodes in cluster on those ports.")
			}

			nginxController.init()
		})

		AfterEach(func() {
			if framework.ProviderIs("gce", "gke") {
				framework.ExpectNoError(gcloudDelete("firewall-rules", fmt.Sprintf("ingress-80-443-%v", ns), framework.TestContext.CloudConfig.ProjectID))
			}
			if CurrentGinkgoTestDescription().Failed {
				framework.DescribeIng(ns)
			}
			if jig.ing == nil {
				By("No ingress created, no cleanup necessary")
				return
			}
			By("Deleting ingress")
			jig.deleteIngress()
		})

		It("should conform to Ingress spec", func() {
			// Poll more frequently to reduce e2e completion time.
			// This test runs in presubmit.
			jig.pollInterval = 5 * time.Second
			conformanceTests = createComformanceTests(jig, ns)
			for _, t := range conformanceTests {
				By(t.entryLog)
				t.execute()
				By(t.exitLog)
				jig.waitForIngress(false)
			}
		})
	})
})
<commit_msg>fix missing package in commented out code<commit_after>/*
Copyright 2015 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 e2e

import (
	"fmt"
	"path/filepath"
	"time"

	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/apiserver/pkg/authentication/serviceaccount"
	rbacv1beta1 "k8s.io/kubernetes/pkg/apis/rbac/v1beta1"
	"k8s.io/kubernetes/test/e2e/framework"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

const (
	// parent path to yaml test manifests.
	ingressManifestPath = "test/e2e/testing-manifests/ingress"

	// timeout on a single http request.
	reqTimeout = 10 * time.Second

	// healthz port used to verify glbc restarted correctly on the master.
	glbcHealthzPort = 8086

	// General cloud resource poll timeout (eg: create static ip, firewall etc)
	cloudResourcePollTimeout = 5 * time.Minute

	// Name of the config-map and key the ingress controller stores its uid in.
	uidConfigMap = "ingress-uid"
	uidKey       = "uid"

	// GCE only allows names < 64 characters, and the loadbalancer controller inserts
	// a single character of padding.
	nameLenLimit = 62
)

var _ = framework.KubeDescribe("Loadbalancing: L7", func() {
	defer GinkgoRecover()
	var (
		ns               string
		jig              *testJig
		conformanceTests []conformanceTests
	)
	f := framework.NewDefaultFramework("ingress")

	BeforeEach(func() {
		f.BeforeEach()
		jig = newTestJig(f.ClientSet)
		ns = f.Namespace.Name

		// this test wants powerful permissions.  Since the namespace names are unique, we can leave this
		// lying around so we don't have to race any caches
		framework.BindClusterRole(jig.client.Rbac(), "cluster-admin", f.Namespace.Name,
			rbacv1beta1.Subject{Kind: rbacv1beta1.ServiceAccountKind, Namespace: f.Namespace.Name, Name: "default"})

		err := framework.WaitForAuthorizationUpdate(jig.client.AuthorizationV1beta1(),
			serviceaccount.MakeUsername(f.Namespace.Name, "default"),
			"", "create", schema.GroupResource{Resource: "pods"}, true)
		framework.ExpectNoError(err)
	})

	// Before enabling this loadbalancer test in any other test list you must
	// make sure the associated project has enough quota. At the time of this
	// writing a GCE project is allowed 3 backend services by default. This
	// test requires at least 5.
	//
	// Slow by design ~10m for each "It" block dominated by loadbalancer setup time
	// TODO: write similar tests for nginx, haproxy and AWS Ingress.
	framework.KubeDescribe("GCE [Slow] [Feature:Ingress]", func() {
		var gceController *GCEIngressController

		// Platform specific setup
		BeforeEach(func() {
			framework.SkipUnlessProviderIs("gce", "gke")
			By("Initializing gce controller")
			gceController = &GCEIngressController{
				ns:    ns,
				c:     jig.client,
				cloud: framework.TestContext.CloudConfig,
			}
			gceController.init()
		})

		// Platform specific cleanup
		AfterEach(func() {
			if CurrentGinkgoTestDescription().Failed {
				framework.DescribeIng(ns)
			}
			if jig.ing == nil {
				By("No ingress created, no cleanup necessary")
				return
			}
			By("Deleting ingress")
			jig.deleteIngress()

			By("Cleaning up cloud resources")
			cleanupGCE(gceController)
		})

		It("should conform to Ingress spec", func() {
			conformanceTests = createComformanceTests(jig, ns)
			for _, t := range conformanceTests {
				By(t.entryLog)
				t.execute()
				By(t.exitLog)
				jig.waitForIngress(true)
			}
		})

		It("shoud create ingress with given static-ip", func() {
			// ip released when the rest of lb resources are deleted in cleanupGCE
			ip := gceController.createStaticIP(ns)
			By(fmt.Sprintf("allocated static ip %v: %v through the GCE cloud provider", ns, ip))

			jig.createIngress(filepath.Join(ingressManifestPath, "static-ip"), ns, map[string]string{
				"kubernetes.io/ingress.global-static-ip-name": ns,
				"kubernetes.io/ingress.allow-http":            "false",
			})

			By("waiting for Ingress to come up with ip: " + ip)
			httpClient := buildInsecureClient(reqTimeout)
			framework.ExpectNoError(framework.PollURL(fmt.Sprintf("https://%v/", ip), "", framework.LoadBalancerPollTimeout, jig.pollInterval, httpClient, false))

			By("should reject HTTP traffic")
			framework.ExpectNoError(framework.PollURL(fmt.Sprintf("http://%v/", ip), "", framework.LoadBalancerPollTimeout, jig.pollInterval, httpClient, true))

			By("should have correct firewall rule for ingress")
			fw := gceController.getFirewallRule()
			expFw := jig.constructFirewallForIngress(gceController)
			// Passed the last argument as `true` to verify the backend ports is a subset
			// of the allowed ports in firewall rule, given there may be other existing
			// ingress resources and backends we are not aware of.
			Expect(framework.VerifyFirewallRule(fw, expFw, gceController.cloud.Network, true)).NotTo(HaveOccurred())

			// TODO: uncomment the restart test once we have a way to synchronize
			// and know that the controller has resumed watching. If we delete
			// the ingress before the controller is ready we will leak.
			// By("restaring glbc")
			// restarter := NewRestartConfig(
			//	 framework.GetMasterHost(), "glbc", glbcHealthzPort, restartPollInterval, restartTimeout)
			// restarter.restart()
			// By("should continue serving on provided static-ip for 30 seconds")
			// framework.ExpectNoError(jig.verifyURL(fmt.Sprintf("https://%v/", ip), "", 30, 1*time.Second, httpClient))
		})

		// TODO: Implement a multizone e2e that verifies traffic reaches each
		// zone based on pod labels.
	})

	// Time: borderline 5m, slow by design
	framework.KubeDescribe("Nginx", func() {
		var nginxController *NginxIngressController

		BeforeEach(func() {
			framework.SkipUnlessProviderIs("gce", "gke")
			By("Initializing nginx controller")
			jig.class = "nginx"
			nginxController = &NginxIngressController{ns: ns, c: jig.client}

			// TODO: This test may fail on other platforms. We can simply skip it
			// but we want to allow easy testing where a user might've hand
			// configured firewalls.
			if framework.ProviderIs("gce", "gke") {
				framework.ExpectNoError(gcloudCreate("firewall-rules", fmt.Sprintf("ingress-80-443-%v", ns), framework.TestContext.CloudConfig.ProjectID, "--allow", "tcp:80,tcp:443", "--network", framework.TestContext.CloudConfig.Network))
			} else {
				framework.Logf("WARNING: Not running on GCE/GKE, cannot create firewall rules for :80, :443. Assuming traffic can reach the external ips of all nodes in cluster on those ports.")
			}

			nginxController.init()
		})

		AfterEach(func() {
			if framework.ProviderIs("gce", "gke") {
				framework.ExpectNoError(gcloudDelete("firewall-rules", fmt.Sprintf("ingress-80-443-%v", ns), framework.TestContext.CloudConfig.ProjectID))
			}
			if CurrentGinkgoTestDescription().Failed {
				framework.DescribeIng(ns)
			}
			if jig.ing == nil {
				By("No ingress created, no cleanup necessary")
				return
			}
			By("Deleting ingress")
			jig.deleteIngress()
		})

		It("should conform to Ingress spec", func() {
			// Poll more frequently to reduce e2e completion time.
			// This test runs in presubmit.
			jig.pollInterval = 5 * time.Second
			conformanceTests = createComformanceTests(jig, ns)
			for _, t := range conformanceTests {
				By(t.entryLog)
				t.execute()
				By(t.exitLog)
				jig.waitForIngress(false)
			}
		})
	})
})
<|endoftext|>


<commit_before>package pmc

import (
	"errors"
	"fmt"
	"math"

	"github.com/dgryski/go-farm"

	"github.com/lazybeaver/xorshift"
	"github.com/willf/bitset"
)

var (
	xor64s = xorshift.NewXorShift64Star(42)
	// Use const due to quick conversion against 0.78 (n = 1000000.0)
	// Actual implementation => n := -2 * sketch.m * math.Log(k) / (m * (1 - p))
	n = 10000000.0
)

// non-receiver methods

func georand(w uint) uint {
	val := xor64s.Next()
	// Calculate the position of the leftmost 1-bit.
	for r := uint(0); r < w-1; r++ {
		if val&0x8000000000000000 != 0 {
			return r
		}
		val <<= 1
	}
	return w - 1
}

func rand(m uint) uint {
	return uint(xor64s.Next()) % m
}

/*
We start with the probability qk(n) that at least the first k bits in a sketch row are set after n additions as given in (4).
We observe that qk is now also a function of p, and obtain a modified version of (4) as follows:
*/
func qk(k, n, p float64) float64 {
	result := 1.0
	for i := 1.0; i <= k; i++ {
		result *= (1.0 - math.Pow(1.0-math.Pow(2, -i), n)*(1.0-p))
	}
	return result
}

/*
Sketch is a Probabilistic Multiplicity Counting Sketch, a novel data structure
that is capable of accounting traffic per flow probabilistically, that can be
used as an alternative to Count-min sketch.
*/
type Sketch struct {
	l      float64
	m      float64
	w      float64
	bitmap *bitset.BitSet // FIXME: Get Rid of bitmap and use uint32 array
	p      float64
}

/*
New returns a PMC Sketch with the properties:
l = total number of bits for sketch
m = total number of rows for each flow
w = total number of columns for each flow
*/
func New(l uint, m uint, w uint) (*Sketch, error) {
	if l == 0 {
		return nil, errors.New("Expected l > 0, got 0")
	}
	if m == 0 {
		return nil, errors.New("Expected m > 0, got 0")
	}
	if w == 0 {
		return nil, errors.New("Expected w > 0, got 0")
	}
	return &Sketch{l: float64(l), m: float64(m), w: float64(w), bitmap: bitset.New(l)}, nil
}

/*
NewForMaxFlows returns a PMC Sketch adapted to the size of the max number of
flows expected.
*/
func NewForMaxFlows(maxFlows uint) (*Sketch, error) {
	l := maxFlows * 32
	return New(l, 256, 32)
}

func (sketch *Sketch) printVirtualMatrix(flow []byte) {
	for i := 0.0; i < sketch.m; i++ {
		for j := 0.0; j < sketch.w; j++ {
			pos := sketch.getPos(flow, i, j)
			if sketch.bitmap.Test(pos) == false {
				fmt.Print(0)
			} else {
				fmt.Print(1)
			}
		}
		fmt.Println("")
	}
}

/*
GetFillRate ...
*/
func (sketch *Sketch) GetFillRate() float64 {
	return sketch.getP() * 100
}

/*
It is straightforward to use any uniformly distributed hash function with
sufficiently random output in the role of H: the input parameters can
simply be concatenated to a single bit string.
*/
func (sketch *Sketch) getPos(f []byte, i, j float64) uint {
	hash := farm.Hash64WithSeeds(f, uint64(i), uint64(j))
	return uint(hash) % uint(sketch.l)
}

/*
Increment the count of the flow by 1
*/
func (sketch *Sketch) Increment(flow []byte) {
	sketch.p = 0
	i := rand(uint(sketch.m))
	j := georand(uint(sketch.w))
	pos := sketch.getPos(flow, float64(i), float64(j))
	sketch.bitmap.Set(pos)
}

func (sketch *Sketch) getZSum(flow []byte) float64 {
	z := 0.0
	for i := 0.0; i < sketch.m; i++ {
		j := 0.0
		for j < sketch.w {
			pos := sketch.getPos(flow, i, j)
			if sketch.bitmap.Test(pos) == false {
				break
			}
			j++
		}
		z += j
	}
	return z
}

func (sketch *Sketch) getEmptyRows(flow []byte) float64 {
	k := 0.0
	for i := 0.0; i < sketch.m; i++ {
		pos := sketch.getPos(flow, i, 0)
		if sketch.bitmap.Test(pos) == false {
			k++
		}
	}
	return k
}

func (sketch *Sketch) getP() float64 {
	ones := 0.0
	for i := uint(0); i < uint(sketch.l); i++ {
		if sketch.bitmap.Test(i) == true {
			ones++
		}
	}
	return ones / sketch.l
}

func (sketch *Sketch) getE(n, p float64) float64 {
	result := 0.0
	for k := 1.0; k <= sketch.w; k++ {
		result += (k * (qk(k, n, p) - qk(k+1, n, p)))
	}
	return result
}

func (sketch *Sketch) rho(n, p float64) float64 {
	return math.Pow(2, sketch.getE(n, p)) / n
}

/*
GetEstimate returns the estimated count of a given flow
*/
func (sketch *Sketch) GetEstimate(flow []byte) float64 {
	if sketch.p == 0 {
		sketch.p = sketch.getP()
	}
	k := sketch.getEmptyRows(flow)

	e := 0.0
	// Dealing with small multiplicities
	if k/(1-sketch.p) > 0.3*sketch.m {
		e = -2 * sketch.m * math.Log(k/(sketch.m*(1-sketch.p)))
	} else {
		z := sketch.getZSum(flow)
		e = sketch.m * math.Pow(2, z/sketch.m) / sketch.rho(n, sketch.p)
	}

	return math.Abs(e)
}
<commit_msg>Use pcgr instead of xorshift<commit_after>package pmc

import (
	"errors"
	"fmt"
	"math"

	"github.com/dgryski/go-farm"

	"github.com/dgryski/go-pcgr"
	"github.com/willf/bitset"
)

var (
	rnd = pcgr.Rand{State: 42, Inc: 0xcafebabe}
	// Use const due to quick conversion against 0.78 (n = 1000000.0)
	// Actual implementation => n := -2 * sketch.m * math.Log(k) / (m * (1 - p))
	n = 10000000.0
)

// non-receiver methods
func georand(w uint) uint {
	val := rnd.Next()
	// Calculate the position of the leftmost 1-bit.
	for r := uint(0); r < w-1; r++ {
		if val&0x80000000 != 0 {
			return r
		}
		val <<= 1
	}
	return w - 1
}

func rand(m uint) uint {
	return uint(rnd.Next()) % m
}

/*
We start with the probability qk(n) that at least the first k bits in a sketch row are set after n additions as given in (4).
We observe that qk is now also a function of p, and obtain a modified version of (4) as follows:
*/
func qk(k, n, p float64) float64 {
	result := 1.0
	for i := 1.0; i <= k; i++ {
		result *= (1.0 - math.Pow(1.0-math.Pow(2, -i), n)*(1.0-p))
	}
	return result
}

/*
Sketch is a Probabilistic Multiplicity Counting Sketch, a novel data structure
that is capable of accounting traffic per flow probabilistically, that can be
used as an alternative to Count-min sketch.
*/
type Sketch struct {
	l      float64
	m      float64
	w      float64
	bitmap *bitset.BitSet // FIXME: Get Rid of bitmap and use uint32 array
	p      float64
}

/*
New returns a PMC Sketch with the properties:
l = total number of bits for sketch
m = total number of rows for each flow
w = total number of columns for each flow
*/
func New(l uint, m uint, w uint) (*Sketch, error) {
	if l == 0 {
		return nil, errors.New("Expected l > 0, got 0")
	}
	if m == 0 {
		return nil, errors.New("Expected m > 0, got 0")
	}
	if w == 0 {
		return nil, errors.New("Expected w > 0, got 0")
	}
	return &Sketch{l: float64(l), m: float64(m), w: float64(w), bitmap: bitset.New(l)}, nil
}

/*
NewForMaxFlows returns a PMC Sketch adapted to the size of the max number of
flows expected.
*/
func NewForMaxFlows(maxFlows uint) (*Sketch, error) {
	l := maxFlows * 32
	return New(l, 256, 32)
}

func (sketch *Sketch) printVirtualMatrix(flow []byte) {
	for i := 0.0; i < sketch.m; i++ {
		for j := 0.0; j < sketch.w; j++ {
			pos := sketch.getPos(flow, i, j)
			if sketch.bitmap.Test(pos) == false {
				fmt.Print(0)
			} else {
				fmt.Print(1)
			}
		}
		fmt.Println("")
	}
}

/*
GetFillRate ...
*/
func (sketch *Sketch) GetFillRate() float64 {
	return sketch.getP() * 100
}

/*
It is straightforward to use any uniformly distributed hash function with
sufficiently random output in the role of H: the input parameters can
simply be concatenated to a single bit string.
*/
func (sketch *Sketch) getPos(f []byte, i, j float64) uint {
	hash := farm.Hash64WithSeeds(f, uint64(i), uint64(j))
	return uint(hash) % uint(sketch.l)
}

/*
Increment the count of the flow by 1
*/
func (sketch *Sketch) Increment(flow []byte) {
	sketch.p = 0
	i := rand(uint(sketch.m))
	j := georand(uint(sketch.w))
	pos := sketch.getPos(flow, float64(i), float64(j))
	sketch.bitmap.Set(pos)
}

func (sketch *Sketch) getZSum(flow []byte) float64 {
	z := 0.0
	for i := 0.0; i < sketch.m; i++ {
		j := 0.0
		for j < sketch.w {
			pos := sketch.getPos(flow, i, j)
			if sketch.bitmap.Test(pos) == false {
				break
			}
			j++
		}
		z += j
	}
	return z
}

func (sketch *Sketch) getEmptyRows(flow []byte) float64 {
	k := 0.0
	for i := 0.0; i < sketch.m; i++ {
		pos := sketch.getPos(flow, i, 0)
		if sketch.bitmap.Test(pos) == false {
			k++
		}
	}
	return k
}

func (sketch *Sketch) getP() float64 {
	ones := 0.0
	for i := uint(0); i < uint(sketch.l); i++ {
		if sketch.bitmap.Test(i) == true {
			ones++
		}
	}
	return ones / sketch.l
}

func (sketch *Sketch) getE(n, p float64) float64 {
	result := 0.0
	for k := 1.0; k <= sketch.w; k++ {
		result += (k * (qk(k, n, p) - qk(k+1, n, p)))
	}
	return result
}

func (sketch *Sketch) rho(n, p float64) float64 {
	return math.Pow(2, sketch.getE(n, p)) / n
}

/*
GetEstimate returns the estimated count of a given flow
*/
func (sketch *Sketch) GetEstimate(flow []byte) float64 {
	if sketch.p == 0 {
		sketch.p = sketch.getP()
	}
	k := sketch.getEmptyRows(flow)

	e := 0.0
	// Dealing with small multiplicities
	if k/(1-sketch.p) > 0.3*sketch.m {
		e = -2 * sketch.m * math.Log(k/(sketch.m*(1-sketch.p)))
	} else {
		z := sketch.getZSum(flow)
		e = sketch.m * math.Pow(2, z/sketch.m) / sketch.rho(n, sketch.p)
	}

	return math.Abs(e)
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"image"
	"image/png"
	"net/http"
	"strconv"
	"time"

	pb "github.com/dgryski/carbonzipper/carbonzipperpb"

	"code.google.com/p/plotinum/plot"
	"code.google.com/p/plotinum/plotter"
	"code.google.com/p/plotinum/plotutil"
	"code.google.com/p/plotinum/vg/vgimg"
)

var linesColors = `blue,green,red,purple,brown,yellow,aqua,grey,magenta,pink,gold,rose`

func marshalPNG(r *http.Request, results []*pb.FetchResponse) []byte {

	p, err := plot.New()
	if err != nil {
		panic(err)
	}

	// need different timeMarker's based on step size
	p.Title.Text = results[0].GetName()
	p.X.Tick.Marker = timeMarker

	p.Add(plotter.NewGrid())

	var lines []plot.Plotter
	for i, r := range results {

		t := resultXYs(r)

		l, _ := plotter.NewLine(t)
		l.Color = plotutil.Color(i)

		lines = append(lines, l)
	}
	p.Add(lines...)

	height := getInt(r.FormValue("height"), 300)
	width := getInt(r.FormValue("width"), 400)

	// Draw the plot to an in-memory image.
	img := image.NewRGBA(image.Rect(0, 0, width, height))
	da := plot.MakeDrawArea(vgimg.NewImage(img))
	p.Draw(da)

	var b bytes.Buffer
	if err := png.Encode(&b, img); err != nil {
		panic(err)
	}

	return b.Bytes()
}

func timeMarker(min, max float64) []plot.Tick {
	ticks := plot.DefaultTicks(min, max)

	for i, t := range ticks {
		if !t.IsMinor() {
			t0 := time.Unix(int64(t.Value), 0)
			ticks[i].Label = t0.Format("15:04:05")
		}
	}

	return ticks
}

func resultXYs(r *pb.FetchResponse) plotter.XYs {
	pts := make(plotter.XYs, len(r.GetValues()))
	start := float64(r.GetStartTime())
	step := float64(r.GetStepTime())
	for i, v := range r.GetValues() {
		pts[i].X = start + float64(i)*step
		pts[i].Y = v
	}
	return pts
}

func getInt(s string, def int) int {

	if s == "" {
		return def
	}

	n, err := strconv.Atoi(s)
	if err != nil {
		return def
	}

	return n

}
<commit_msg>use title from URL<commit_after>package main

import (
	"bytes"
	"image"
	"image/png"
	"net/http"
	"strconv"
	"time"

	pb "github.com/dgryski/carbonzipper/carbonzipperpb"

	"code.google.com/p/plotinum/plot"
	"code.google.com/p/plotinum/plotter"
	"code.google.com/p/plotinum/plotutil"
	"code.google.com/p/plotinum/vg/vgimg"
)

var linesColors = `blue,green,red,purple,brown,yellow,aqua,grey,magenta,pink,gold,rose`

func marshalPNG(r *http.Request, results []*pb.FetchResponse) []byte {

	p, err := plot.New()
	if err != nil {
		panic(err)
	}

	// need different timeMarker's based on step size
	p.Title.Text = r.FormValue("title")
	p.X.Tick.Marker = timeMarker

	p.Add(plotter.NewGrid())

	var lines []plot.Plotter
	for i, r := range results {

		t := resultXYs(r)

		l, _ := plotter.NewLine(t)
		l.Color = plotutil.Color(i)

		lines = append(lines, l)
	}
	p.Add(lines...)

	height := getInt(r.FormValue("height"), 300)
	width := getInt(r.FormValue("width"), 400)

	// Draw the plot to an in-memory image.
	img := image.NewRGBA(image.Rect(0, 0, width, height))
	da := plot.MakeDrawArea(vgimg.NewImage(img))
	p.Draw(da)

	var b bytes.Buffer
	if err := png.Encode(&b, img); err != nil {
		panic(err)
	}

	return b.Bytes()
}

func timeMarker(min, max float64) []plot.Tick {
	ticks := plot.DefaultTicks(min, max)

	for i, t := range ticks {
		if !t.IsMinor() {
			t0 := time.Unix(int64(t.Value), 0)
			ticks[i].Label = t0.Format("15:04:05")
		}
	}

	return ticks
}

func resultXYs(r *pb.FetchResponse) plotter.XYs {
	pts := make(plotter.XYs, len(r.GetValues()))
	start := float64(r.GetStartTime())
	step := float64(r.GetStepTime())
	for i, v := range r.GetValues() {
		pts[i].X = start + float64(i)*step
		pts[i].Y = v
	}
	return pts
}

func getInt(s string, def int) int {

	if s == "" {
		return def
	}

	n, err := strconv.Atoi(s)
	if err != nil {
		return def
	}

	return n

}
<|endoftext|>


<commit_before>package cloud

import (
	"context"
	"errors"
	"fmt"
	"net/http"
)

// StatusCategoryService handles status categories for the Jira instance / API.
//
// Use it to obtain a list of all status categories and the details of a category.
// Status categories provided a mechanism for categorizing statuses.
//
// Jira API docs: https://developer.atlassian.com/cloud/jira/platform/rest/v3/api-group-workflow-status-categories/#api-group-workflow-status-categories
type StatusCategoryService service

// StatusCategory represents the category a status belongs to.
// Those categories can be user defined in every Jira instance.
type StatusCategory struct {
	Self      string `json:"self" structs:"self"`
	ID        int    `json:"id" structs:"id"`
	Name      string `json:"name" structs:"name"`
	Key       string `json:"key" structs:"key"`
	ColorName string `json:"colorName" structs:"colorName"`
}

// These constants are the keys of the default Jira status categories
const (
	StatusCategoryComplete   = "done"
	StatusCategoryInProgress = "indeterminate"
	StatusCategoryToDo       = "new"
	StatusCategoryUndefined  = "undefined"
)

// GetList returns a list of all status categories.
//
// Jira API docs: https://developer.atlassian.com/cloud/jira/platform/rest/v3/api-group-workflow-status-categories/#api-rest-api-3-statuscategory-get
func (s *StatusCategoryService) GetList(ctx context.Context) ([]StatusCategory, *Response, error) {
	apiEndpoint := "/rest/api/3/statuscategory"
	req, err := s.client.NewRequest(ctx, http.MethodGet, apiEndpoint, nil)
	if err != nil {
		return nil, nil, err
	}

	var statusCategories []StatusCategory
	resp, err := s.client.Do(req, &statusCategories)
	if err != nil {
		return nil, resp, NewJiraError(resp, err)
	}

	return statusCategories, resp, nil
}

// Get returns a status category.
// Status categories provided a mechanism for categorizing statuses.
//
// statusCategoryID represents the ID or key of the status category.
//
// Jira API docs: https://developer.atlassian.com/cloud/jira/platform/rest/v3/api-group-workflow-status-categories/#api-rest-api-3-statuscategory-idorkey-get
func (s *StatusCategoryService) Get(ctx context.Context, statusCategoryID string) (*StatusCategory, *Response, error) {
	if statusCategoryID == "" {
		return nil, nil, errors.New("jira: not status category set")
	}

	apiEndpoint := fmt.Sprintf("/rest/api/3/statuscategory/%v", statusCategoryID)
	req, err := s.client.NewRequest(ctx, http.MethodGet, apiEndpoint, nil)
	if err != nil {
		return nil, nil, err
	}

	statusCategory := new(StatusCategory)
	resp, err := s.client.Do(req, statusCategory)
	if err != nil {
		return nil, resp, NewJiraError(resp, err)
	}

	return statusCategory, resp, nil
}
<commit_msg>Cloud/Status category: fixed error message if no status category id is given<commit_after>package cloud

import (
	"context"
	"errors"
	"fmt"
	"net/http"
)

// StatusCategoryService handles status categories for the Jira instance / API.
//
// Use it to obtain a list of all status categories and the details of a category.
// Status categories provided a mechanism for categorizing statuses.
//
// Jira API docs: https://developer.atlassian.com/cloud/jira/platform/rest/v3/api-group-workflow-status-categories/#api-group-workflow-status-categories
type StatusCategoryService service

// StatusCategory represents the category a status belongs to.
// Those categories can be user defined in every Jira instance.
type StatusCategory struct {
	Self      string `json:"self" structs:"self"`
	ID        int    `json:"id" structs:"id"`
	Name      string `json:"name" structs:"name"`
	Key       string `json:"key" structs:"key"`
	ColorName string `json:"colorName" structs:"colorName"`
}

// These constants are the keys of the default Jira status categories
const (
	StatusCategoryComplete   = "done"
	StatusCategoryInProgress = "indeterminate"
	StatusCategoryToDo       = "new"
	StatusCategoryUndefined  = "undefined"
)

// GetList returns a list of all status categories.
//
// Jira API docs: https://developer.atlassian.com/cloud/jira/platform/rest/v3/api-group-workflow-status-categories/#api-rest-api-3-statuscategory-get
func (s *StatusCategoryService) GetList(ctx context.Context) ([]StatusCategory, *Response, error) {
	apiEndpoint := "/rest/api/3/statuscategory"
	req, err := s.client.NewRequest(ctx, http.MethodGet, apiEndpoint, nil)
	if err != nil {
		return nil, nil, err
	}

	var statusCategories []StatusCategory
	resp, err := s.client.Do(req, &statusCategories)
	if err != nil {
		return nil, resp, NewJiraError(resp, err)
	}

	return statusCategories, resp, nil
}

// Get returns a status category.
// Status categories provided a mechanism for categorizing statuses.
//
// statusCategoryID represents the ID or key of the status category.
//
// Jira API docs: https://developer.atlassian.com/cloud/jira/platform/rest/v3/api-group-workflow-status-categories/#api-rest-api-3-statuscategory-idorkey-get
func (s *StatusCategoryService) Get(ctx context.Context, statusCategoryID string) (*StatusCategory, *Response, error) {
	if statusCategoryID == "" {
		return nil, nil, errors.New("no status category id set")
	}

	apiEndpoint := fmt.Sprintf("/rest/api/3/statuscategory/%v", statusCategoryID)
	req, err := s.client.NewRequest(ctx, http.MethodGet, apiEndpoint, nil)
	if err != nil {
		return nil, nil, err
	}

	statusCategory := new(StatusCategory)
	resp, err := s.client.Do(req, statusCategory)
	if err != nil {
		return nil, resp, NewJiraError(resp, err)
	}

	return statusCategory, resp, nil
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"math/rand"
)

func main() {
	distance := 57600000
	company := ""
	trip := ""

	fmt.Printf("%-18v %4v %v %7v\n", "Spaceline", "Days", "Round-trip", "Price")
	fmt.Println("===============================================")
	//fmt.Println(distance / speed, days)
	for count :=0; count < 10; count++ {
		switch rand.Intn(3) {
		case 0:
			company = "Space Adventures"
		case 1:
			company = "SpaceX"
		case 2:
			company = "Virgin Galactic"
		}
		speed := rand.Intn(16) + 15
		days := (distance / speed) / 86164
		price := days / 2

		switch rand.Intn(2) {
		case 0:
			trip = "One Way"
		case 1:
			trip = "Round Trip"
		}
		fmt.Printf("%-18v %4v %v $%4v\n", company, days, trip, price)
	}
}
<commit_msg>Added if statement to adjust cost for round trip, changed distance to const.<commit_after>package main

import (
	"fmt"
	"math/rand"
	"strings"
)

func main() {
	const distance = 57600000
	company := ""
	trip := ""

	fmt.Printf("%-18v %4v %v %7v\n", "Spaceline", "Days", "Round-trip", "Price")
	fmt.Println("===============================================")
	for count :=0; count < 10; count++ {

		switch rand.Intn(3) {
		case 0:
			company = "Space Adventures"
		case 1:
			company = "SpaceX"
		case 2:
			company = "Virgin Galactic"
		}

		speed := rand.Intn(16) + 15
		days := (distance / speed) / 86164
		price := days / 2

		switch rand.Intn(2) {
		case 0:
			trip = "One Way"
		case 1:
			trip = "Round Trip"
		}

		if strings.Contains(trip, "Round") {
			price = price * 2
		}

		fmt.Printf("%-18v %4v %v $%4v\n", company, days, trip, price)
	}
}
<|endoftext|>


<commit_before>package tiff

import (
	"bytes"
	"encoding/binary"
	"encoding/hex"
	"os"
	"testing"
)

func data() []byte {
	s1 := "49492A000800000002001A0105000100"
	s1 += "00002600000069870400010000001102"
	s1 += "0000000000004800000001000000"

	dat, err := hex.DecodeString(s1)
	if err != nil {
		panic("invalid string fixture")
	}
	return dat
}

func TestDecode(t *testing.T) {
	name := "sample1.tif"
	f, err := os.Open(name)
	if err != nil {
		t.Fatalf("%v\n", err)
	}

	tif, err := Decode(f)
	if err != nil {
		t.Fatal(err)
	}

	t.Log(tif)
}

func TestDecodeTag(t *testing.T) {
	buf := bytes.NewReader(data())
	buf.Seek(10, 1)
	tg, err := DecodeTag(buf, binary.LittleEndian)
	if err != nil {
		t.Fatalf("tag decode failed: %v", err)
	}

	t.Logf("tag: %v+\n", tg)
	n, d := tg.Rat2(0)
	t.Logf("tag rat val: %v\n", n, d)
}
<commit_msg>working on table-driven tiff tests<commit_after>package tiff

import (
	"bytes"
	"encoding/binary"
	"encoding/hex"
	"os"
	"testing"
)

//   {"TgId", "TYPE", "N-VALUES", "VALUE---"},
type input [4]string

type output struct {
  id uint16
  format uint16
  count uint32
  offset uint32
  val []byte
}

type tagTest struct {
  in input
  out output
}

///////////////////////////////////////////////
//// Big endian Tests /////////////////////////
///////////////////////////////////////////////

var set1 = []tagTest{
  tagTest{
    //   {"TgId", "TYPE", "N-VALUES", "VALUE---"},
    input{"0001", "0001", "00000001", "11000000"},
    output{0x0001, 0x0001, 0x0001, 0x11},
  }
  tagTest{
    //   {"TgId", "TYPE", "N-VALUES", "VALUE---"},
    input{"0001", "0001", "00000002", "11120000"},
    output{0x0001, 0x0001, 0x0001, 0000},
  }

  input{"0002", "0002", "00000002", "61000000"},
  input{"0002", "0002", "00000003", "61000000"},
  input{"0002", "0002", "00000004", "61000000"},
  input{"0002", "0002", "00000005", "61000000"},

  input{"0003", "0003", "00000001", "00000000"},
  input{"0004", "0004", "00000001", "00000000"},
  input{"0005", "0005", "00000001", "00000000"},
  input{"0006", "0006", "00000001", "00000000"},
  input{"0007", "0007", "00000001", "00000000"},
  input{"0008", "0008", "00000001", "00000000"},
  input{"0009", "0009", "00000001", "00000000"},
  input{"000A", "000A", "00000001", "00000000"},
  input{"000B", "000B", "00000001", "00000000"},
  input{"000C", "000C", "00000001", "00000000"},
}

var littleEndianEnts = []entry{
  //   {"TgId", "TYPE", "N-VALUES", "VALUE---"},
  entry{"0101", "0100", "00001111", "00001111"},
  entry{"0201", "0200", "00001111", "00001111"},
  entry{"0301", "0300", "00001111", "00001111"},
  entry{"0401", "0400", "00001111", "00001111"},
  entry{"0501", "0500", "00001111", "00001111"},
  entry{"0601", "0600", "00001111", "00001111"},
  entry{"0701", "0700", "00001111", "00001111"},
  entry{"0801", "0800", "00001111", "00001111"},
  entry{"0901", "0900", "00001111", "00001111"},
  entry{"0A01", "0A00", "00001111", "00001111"},
  entry{"0B01", "0B00", "00001111", "00001111"},
  entry{"0C01", "0C00", "00001111", "00001111"},
}

func data() []byte {
	s1 := "49492A000800000002001A0105000100"
	s1 += "00002600000069870400010000001102"
	s1 += "0000000000004800000001000000"

	dat, err := hex.DecodeString(s1)
	if err != nil {
		panic("invalid string fixture")
	}
	return dat
}

func TestDecode(t *testing.T) {
	name := "sample1.tif"
	f, err := os.Open(name)
	if err != nil {
		t.Fatalf("%v\n", err)
	}

	tif, err := Decode(f)
	if err != nil {
		t.Fatal(err)
	}

	t.Log(tif)
}

func TestDecodeTag(t *testing.T) {
	buf := bytes.NewReader(data())
	buf.Seek(10, 1)
	tg, err := DecodeTag(buf, binary.LittleEndian)
	if err != nil {
		t.Fatalf("tag decode failed: %v", err)
	}

	t.Logf("tag: %v+\n", tg)
	n, d := tg.Rat2(0)
	t.Logf("tag rat val: %v\n", n, d)
}
<|endoftext|>