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

package testutil

import (
	"fmt"
	"net/http"
	"os"
	"regexp"
	"runtime"
	"sort"
	"strings"
	"testing"
	"time"
)

/*
CheckLeakedGoroutine verifies tests do not leave any leaky
goroutines. It returns true when there are goroutines still
running(leaking) after all tests.

	import "github.com/coreos/etcd/pkg/testutil"

	func TestMain(m *testing.M) {
		v := m.Run()
		if v == 0 && testutil.CheckLeakedGoroutine() {
			os.Exit(1)
		}
		os.Exit(v)
	}

	func TestSample(t *testing.T) {
		defer testutil.AfterTest(t)
		...
	}

*/
func CheckLeakedGoroutine() bool {
	if testing.Short() {
		// not counting goroutines for leakage in -short mode
		return false
	}
	gs := interestingGoroutines()
	if len(gs) == 0 {
		return false
	}

	stackCount := make(map[string]int)
	re := regexp.MustCompile(`\(0[0-9a-fx, ]*\)`)
	for _, g := range gs {
		// strip out pointer arguments in first function of stack dump
		normalized := string(re.ReplaceAll([]byte(g), []byte("(...)")))
		stackCount[normalized]++
	}

	fmt.Fprintf(os.Stderr, "Too many goroutines running after all test(s).\n")
	for stack, count := range stackCount {
		fmt.Fprintf(os.Stderr, "%d instances of:\n%s\n", count, stack)
	}
	return true
}

// CheckAfterTest returns an error if AfterTest would fail with an error.
func CheckAfterTest(d time.Duration) error {
	http.DefaultTransport.(*http.Transport).CloseIdleConnections()
	if testing.Short() {
		return nil
	}
	var bad string
	badSubstring := map[string]string{
		").writeLoop(":                                 "a Transport",
		"created by net/http/httptest.(*Server).Start": "an httptest.Server",
		"timeoutHandler":                               "a TimeoutHandler",
		"net.(*netFD).connect(":                        "a timing out dial",
		").noteClientGone(":                            "a closenotifier sender",
		").readLoop(":                                  "a Transport",
		".grpc":                                        "a gRPC resource",
	}

	var stacks string
	begin := time.Now()
	for time.Since(begin) < d {
		bad = ""
		stacks = strings.Join(interestingGoroutines(), "\n\n")
		for substr, what := range badSubstring {
			if strings.Contains(stacks, substr) {
				bad = what
			}
		}
		if bad == "" {
			return nil
		}
		// Bad stuff found, but goroutines might just still be
		// shutting down, so give it some time.
		time.Sleep(50 * time.Millisecond)
	}
	return fmt.Errorf("appears to have leaked %s:\n%s", bad, stacks)
}

// AfterTest is meant to run in a defer that executes after a test completes.
// It will detect common goroutine leaks, retrying in case there are goroutines
// not synchronously torn down, and fail the test if any goroutines are stuck.
func AfterTest(t *testing.T) {
	if err := CheckAfterTest(300 * time.Millisecond); err != nil {
		t.Errorf("Test %v", err)
	}
}

func interestingGoroutines() (gs []string) {
	buf := make([]byte, 2<<20)
	buf = buf[:runtime.Stack(buf, true)]
	for _, g := range strings.Split(string(buf), "\n\n") {
		sl := strings.SplitN(g, "\n", 2)
		if len(sl) != 2 {
			continue
		}
		stack := strings.TrimSpace(sl[1])
		if stack == "" ||
			strings.Contains(stack, "sync.(*WaitGroup).Done") ||
			strings.Contains(stack, "created by os/signal.init") ||
			strings.Contains(stack, "runtime/panic.go") ||
			strings.Contains(stack, "created by testing.RunTests") ||
			strings.Contains(stack, "testing.Main(") ||
			strings.Contains(stack, "runtime.goexit") ||
			strings.Contains(stack, "github.com/coreos/etcd/pkg/testutil.interestingGoroutines") ||
			strings.Contains(stack, "github.com/coreos/etcd/pkg/logutil.(*MergeLogger).outputLoop") ||
			strings.Contains(stack, "github.com/golang/glog.(*loggingT).flushDaemon") ||
			strings.Contains(stack, "created by runtime.gc") ||
			strings.Contains(stack, "runtime.MHeap_Scavenger") {
			continue
		}
		gs = append(gs, stack)
	}
	sort.Strings(gs)
	return
}
<commit_msg>testutil: whitelist os.(*file).close<commit_after>// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package testutil

import (
	"fmt"
	"net/http"
	"os"
	"regexp"
	"runtime"
	"sort"
	"strings"
	"testing"
	"time"
)

/*
CheckLeakedGoroutine verifies tests do not leave any leaky
goroutines. It returns true when there are goroutines still
running(leaking) after all tests.

	import "github.com/coreos/etcd/pkg/testutil"

	func TestMain(m *testing.M) {
		v := m.Run()
		if v == 0 && testutil.CheckLeakedGoroutine() {
			os.Exit(1)
		}
		os.Exit(v)
	}

	func TestSample(t *testing.T) {
		defer testutil.AfterTest(t)
		...
	}

*/
func CheckLeakedGoroutine() bool {
	if testing.Short() {
		// not counting goroutines for leakage in -short mode
		return false
	}
	gs := interestingGoroutines()
	if len(gs) == 0 {
		return false
	}

	stackCount := make(map[string]int)
	re := regexp.MustCompile(`\(0[0-9a-fx, ]*\)`)
	for _, g := range gs {
		// strip out pointer arguments in first function of stack dump
		normalized := string(re.ReplaceAll([]byte(g), []byte("(...)")))
		stackCount[normalized]++
	}

	fmt.Fprintf(os.Stderr, "Too many goroutines running after all test(s).\n")
	for stack, count := range stackCount {
		fmt.Fprintf(os.Stderr, "%d instances of:\n%s\n", count, stack)
	}
	return true
}

// CheckAfterTest returns an error if AfterTest would fail with an error.
func CheckAfterTest(d time.Duration) error {
	http.DefaultTransport.(*http.Transport).CloseIdleConnections()
	if testing.Short() {
		return nil
	}
	var bad string
	badSubstring := map[string]string{
		").writeLoop(":                                 "a Transport",
		"created by net/http/httptest.(*Server).Start": "an httptest.Server",
		"timeoutHandler":                               "a TimeoutHandler",
		"net.(*netFD).connect(":                        "a timing out dial",
		").noteClientGone(":                            "a closenotifier sender",
		").readLoop(":                                  "a Transport",
		".grpc":                                        "a gRPC resource",
	}

	var stacks string
	begin := time.Now()
	for time.Since(begin) < d {
		bad = ""
		stacks = strings.Join(interestingGoroutines(), "\n\n")
		for substr, what := range badSubstring {
			if strings.Contains(stacks, substr) {
				bad = what
			}
		}
		if bad == "" {
			return nil
		}
		// Bad stuff found, but goroutines might just still be
		// shutting down, so give it some time.
		time.Sleep(50 * time.Millisecond)
	}
	return fmt.Errorf("appears to have leaked %s:\n%s", bad, stacks)
}

// AfterTest is meant to run in a defer that executes after a test completes.
// It will detect common goroutine leaks, retrying in case there are goroutines
// not synchronously torn down, and fail the test if any goroutines are stuck.
func AfterTest(t *testing.T) {
	if err := CheckAfterTest(300 * time.Millisecond); err != nil {
		t.Errorf("Test %v", err)
	}
}

func interestingGoroutines() (gs []string) {
	buf := make([]byte, 2<<20)
	buf = buf[:runtime.Stack(buf, true)]
	for _, g := range strings.Split(string(buf), "\n\n") {
		sl := strings.SplitN(g, "\n", 2)
		if len(sl) != 2 {
			continue
		}
		stack := strings.TrimSpace(sl[1])
		if stack == "" ||
			strings.Contains(stack, "sync.(*WaitGroup).Done") ||
			strings.Contains(stack, "os.(*file).close") ||
			strings.Contains(stack, "created by os/signal.init") ||
			strings.Contains(stack, "runtime/panic.go") ||
			strings.Contains(stack, "created by testing.RunTests") ||
			strings.Contains(stack, "testing.Main(") ||
			strings.Contains(stack, "runtime.goexit") ||
			strings.Contains(stack, "github.com/coreos/etcd/pkg/testutil.interestingGoroutines") ||
			strings.Contains(stack, "github.com/coreos/etcd/pkg/logutil.(*MergeLogger).outputLoop") ||
			strings.Contains(stack, "github.com/golang/glog.(*loggingT).flushDaemon") ||
			strings.Contains(stack, "created by runtime.gc") ||
			strings.Contains(stack, "runtime.MHeap_Scavenger") {
			continue
		}
		gs = append(gs, stack)
	}
	sort.Strings(gs)
	return
}
<|endoftext|>


<commit_before>package true_git

import (
	"bytes"
	"errors"
	"fmt"
	"io"
	"os"
	"os/exec"
	"strings"

	"github.com/Masterminds/semver"
)

const (
	MinGitVersionConstraintValue               = "1.9"
	MinGitVersionWithSubmodulesConstraintValue = "2.14"
)

var (
	gitVersion *semver.Version

	minGitVersionErrorMsg     = fmt.Sprintf("Git version >= %s required", MinGitVersionConstraintValue)
	submodulesVersionErrorMsg = fmt.Sprintf("To use git submodules install git >= %s", MinGitVersionWithSubmodulesConstraintValue)

	outStream, errStream io.Writer
)

type Options struct {
	Out, Err io.Writer
}

func Init(opts Options) error {
	outStream = os.Stdout
	errStream = os.Stderr
	if opts.Out != nil {
		outStream = opts.Out
	}
	if opts.Err != nil {
		errStream = opts.Err
	}

	var err error

	v, err := getGitCliVersion()
	if err != nil {
		return err
	}

	vObj, err := semver.NewVersion(v)
	if err != nil {
		errMsg := strings.Join([]string{
			fmt.Sprintf("unexpected git version spec %s", v),
			minGitVersionErrorMsg,
			submodulesVersionErrorMsg,
		}, ".\n")

		return errors.New(errMsg)
	}
	gitVersion = vObj

	if err := checkMinVersionConstraint(); err != nil {
		return err
	}

	return nil
}

func getGitCliVersion() (string, error) {
	cmd := exec.Command("git", "version")

	out := bytes.Buffer{}
	cmd.Stdout = &out
	cmd.Stderr = &out

	err := cmd.Run()
	if err != nil {
		errMsg := strings.Join([]string{
			fmt.Sprintf("git version command failed: %s", err),
			minGitVersionErrorMsg,
			submodulesVersionErrorMsg,
		}, ".\n")

		return "", errors.New(errMsg)
	}

	strippedOut := strings.TrimSpace(out.String())
	rightPart := strings.TrimLeft(strippedOut, "git version ")
	fullVersion := strings.Split(rightPart, " ")[0]
	fullVersionParts := strings.Split(fullVersion, ".")

	lowestVersionPartInd := 3
	if len(fullVersionParts) < lowestVersionPartInd {
		lowestVersionPartInd = len(fullVersionParts)
	}

	version := strings.Join(fullVersionParts[0:lowestVersionPartInd], ".")

	return version, nil
}

func checkMinVersionConstraint() error {
	constraint, err := semver.NewConstraint(fmt.Sprintf(">= %s", MinGitVersionConstraintValue))
	if err != nil {
		panic(err)
	}

	if !constraint.Check(gitVersion) {
		errMsg := strings.Join([]string{
			strings.ToLower(minGitVersionErrorMsg),
			submodulesVersionErrorMsg,
			fmt.Sprintf("Your git version is %s", gitVersion.String()),
		}, ".\n")

		return errors.New(errMsg)
	}

	return nil
}

func checkSubmoduleConstraint() error {
	constraint, err := semver.NewConstraint(fmt.Sprintf(">= %s", MinGitVersionWithSubmodulesConstraintValue))
	if err != nil {
		panic(err)
	}

	if !constraint.Check(gitVersion) {
		errMsg := strings.Join([]string{
			strings.ToLower(submodulesVersionErrorMsg),
			fmt.Sprintf("Your git version is %s", gitVersion.String()),
		}, ".\n")

		return errors.New(errMsg)
	}

	return nil
}
<commit_msg>[git] Forbidden 2.22.0 git version check<commit_after>package true_git

import (
	"bytes"
	"errors"
	"fmt"
	"io"
	"os"
	"os/exec"
	"strings"

	"github.com/Masterminds/semver"
)

const (
	MinGitVersionConstraintValue               = "1.9"
	MinGitVersionWithSubmodulesConstraintValue = "2.14"
)

var (
	ForbiddenGitVersionsConstraintValues = []string{"2.22.0"}
)

var (
	gitVersion *semver.Version

	minGitVersionErrorMsg       = fmt.Sprintf("Git version >= %s required", MinGitVersionConstraintValue)
	forbiddenGitVersionErrorMsg = fmt.Sprintf("Forbidden git versions: %s", strings.Join(ForbiddenGitVersionsConstraintValues, ", "))
	submodulesVersionErrorMsg   = fmt.Sprintf("To use git submodules install git >= %s", MinGitVersionWithSubmodulesConstraintValue)

	outStream, errStream io.Writer
)

type Options struct {
	Out, Err io.Writer
}

func Init(opts Options) error {
	outStream = os.Stdout
	errStream = os.Stderr
	if opts.Out != nil {
		outStream = opts.Out
	}
	if opts.Err != nil {
		errStream = opts.Err
	}

	var err error

	v, err := getGitCliVersion()
	if err != nil {
		return err
	}

	vObj, err := semver.NewVersion(v)
	if err != nil {
		errMsg := strings.Join([]string{
			fmt.Sprintf("Unexpected git version spec %s", v),
			minGitVersionErrorMsg,
			forbiddenGitVersionErrorMsg,
			submodulesVersionErrorMsg,
		}, ".\n")

		return errors.New(errMsg)
	}
	gitVersion = vObj

	if err := checkVersionConstraints(); err != nil {
		return err
	}

	return nil
}

func getGitCliVersion() (string, error) {
	cmd := exec.Command("git", "version")

	out := bytes.Buffer{}
	cmd.Stdout = &out
	cmd.Stderr = &out

	err := cmd.Run()
	if err != nil {
		errMsg := strings.Join([]string{
			fmt.Sprintf("Git version command failed: %s", err),
			minGitVersionErrorMsg,
			forbiddenGitVersionErrorMsg,
			submodulesVersionErrorMsg,
		}, ".\n")

		return "", errors.New(errMsg)
	}

	strippedOut := strings.TrimSpace(out.String())
	rightPart := strings.TrimLeft(strippedOut, "git version ")
	fullVersion := strings.Split(rightPart, " ")[0]
	fullVersionParts := strings.Split(fullVersion, ".")

	lowestVersionPartInd := 3
	if len(fullVersionParts) < lowestVersionPartInd {
		lowestVersionPartInd = len(fullVersionParts)
	}

	version := strings.Join(fullVersionParts[0:lowestVersionPartInd], ".")

	return version, nil
}

func checkVersionConstraints() error {
	constraints := []*semver.Constraints{}

	minVersionConstraints, err := semver.NewConstraint(fmt.Sprintf(">= %s", MinGitVersionConstraintValue))
	if err != nil {
		panic(err)
	}
	constraints = append(constraints, minVersionConstraints)

	for _, cv := range ForbiddenGitVersionsConstraintValues {
		forbiddenVersionsConstraints, err := semver.NewConstraint(fmt.Sprintf("!= %s", cv))
		if err != nil {
			panic(err)
		}
		constraints = append(constraints, forbiddenVersionsConstraints)
	}

	for i := range constraints {
		if !constraints[i].Check(gitVersion) {
			errMsg := strings.Join([]string{
				minGitVersionErrorMsg,
				forbiddenGitVersionErrorMsg,
				submodulesVersionErrorMsg,
				fmt.Sprintf("Your git version is %s", gitVersion.String()),
			}, ".\n")

			return errors.New(errMsg)
		}
	}

	return nil
}

func checkSubmoduleConstraint() error {
	constraint, err := semver.NewConstraint(fmt.Sprintf(">= %s", MinGitVersionWithSubmodulesConstraintValue))
	if err != nil {
		panic(err)
	}

	if !constraint.Check(gitVersion) {
		errMsg := strings.Join([]string{
			strings.ToLower(submodulesVersionErrorMsg),
			fmt.Sprintf("Your git version is %s", gitVersion.String()),
		}, ".\n")

		return errors.New(errMsg)
	}

	return nil
}
<|endoftext|>


<commit_before>package digitalocean

import (
	"fmt"
	"log"

	"github.com/digitalocean/godo"
	"github.com/hashicorp/terraform/helper/schema"
)

func resourceDigitalOceanFloatingIp() *schema.Resource {
	return &schema.Resource{
		Create: resourceDigitalOceanFloatingIpCreate,
		Read:   resourceDigitalOceanFloatingIpRead,
		Delete: resourceDigitalOceanFloatingIpDelete,

		Schema: map[string]*schema.Schema{
			"ip_address": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
			},

			"region": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
			},

			"droplet_id": &schema.Schema{
				Type:     schema.TypeInt,
				Optional: true,
				ForceNew: true,
			},
		},
	}
}

func resourceDigitalOceanFloatingIpCreate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*godo.Client)

	// Build up our creation options
	opts := &godo.FloatingIPCreateRequest{}

	if v, ok := d.GetOk("droplet_id"); ok {
		log.Printf("[INFO] Found a droplet_id to try and attach to the FloatingIP")
		opts.DropletID = v.(int)
	} else if d.Get("region").(string) != "" {
		opts.Region = d.Get("region").(string)
	} else {
		return fmt.Errorf("You must specify either a Droplet ID or a Region for a FloatingIP")
	}

	log.Printf("[DEBUG] FloatingIP Create: %#v", opts)
	floatingIp, _, err := client.FloatingIPs.Create(opts)
	if err != nil {
		return fmt.Errorf("Error creating FloatingIP: %s", err)
	}

	d.SetId(floatingIp.IP)
	log.Printf("[INFO] Floating IP: %s", floatingIp.IP)

	return resourceDigitalOceanFloatingIpRead(d, meta)
}

func resourceDigitalOceanFloatingIpRead(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*godo.Client)

	floatingIp, _, err := client.FloatingIPs.Get(d.Id())
	if err != nil {
		return fmt.Errorf("Error retrieving FloatingIP: %s", err)
	}

	d.Set("region", floatingIp.Region)
	d.Set("ip_address", floatingIp.IP)

	return nil
}

func resourceDigitalOceanFloatingIpDelete(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*godo.Client)

	log.Printf("[INFO] Deleting FloatingIP: %s", d.Id())
	_, err := client.FloatingIPs.Delete(d.Id())
	if err != nil {
		return fmt.Errorf("Error deleting FloatingIP: %s", err)
	}

	d.SetId("")
	return nil
}
<commit_msg>Reording the code for the creation of a Floating IP for a droplet. The call to the DO api takes a few seconds to propagate so I had to sacriface some kittens and added a short 10 second sleep<commit_after>package digitalocean

import (
	"fmt"
	"log"
	"time"

	"github.com/digitalocean/godo"
	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/helper/schema"
)

func resourceDigitalOceanFloatingIp() *schema.Resource {
	return &schema.Resource{
		Create: resourceDigitalOceanFloatingIpCreate,
		Read:   resourceDigitalOceanFloatingIpRead,
		Delete: resourceDigitalOceanFloatingIpDelete,

		Schema: map[string]*schema.Schema{
			"ip_address": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
			},

			"region": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
				ForceNew: true,
			},

			"droplet_id": &schema.Schema{
				Type:     schema.TypeInt,
				Optional: true,
				ForceNew: true,
			},
		},
	}
}

func resourceDigitalOceanFloatingIpCreate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*godo.Client)

	// Build up our creation options
	opts := &godo.FloatingIPCreateRequest{}

	if v, ok := d.GetOk("region"); ok {
		log.Printf("[INFO] Create a FloatingIP for a region")
		opts.Region = v.(string)
	}

	if v, ok := d.GetOk("droplet_id"); ok {
		log.Printf("[INFO] Found a droplet_id to try and attach to the FloatingIP")
		opts.DropletID = v.(int)
	}

	log.Printf("[DEBUG] FloatingIP Create: %#v", opts)
	floatingIp, _, err := client.FloatingIPs.Create(opts)
	if err != nil {
		return fmt.Errorf("Error creating FloatingIP: %s", err)
	}
	d.SetId(floatingIp.IP)

	return resourceDigitalOceanFloatingIpRead(d, meta)
}

func resourceDigitalOceanFloatingIpRead(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*godo.Client)

	time.Sleep(7 * time.Second)
	log.Printf("[INFO] Reading the details of the FloatingIP %s", d.Id())
	floatingIp, _, err := client.FloatingIPs.Get(d.Id())
	if err != nil {
		return fmt.Errorf("Error retrieving FloatingIP: %s", err)
	}

	if _, ok := d.GetOk("droplet_id"); ok {
		log.Printf("[INFO] The region of the Droplet is %s", floatingIp.Droplet.Region)
		d.Set("region", floatingIp.Droplet.Region.Slug)
	} else {
		d.Set("region", floatingIp.Region.Slug)
	}

	d.Set("ip_address", floatingIp.IP)

	return nil
}

func resourceDigitalOceanFloatingIpDelete(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*godo.Client)

	if _, ok := d.GetOk("droplet_id"); ok {
		log.Printf("[INFO] Unassigning the Floating IP from the Droplet")
		action, _, err := client.FloatingIPActions.Unassign(d.Id())
		if err != nil {
			return fmt.Errorf(
				"Error Unassigning FloatingIP (%s) from the droplet: %s", d.Id(), err)
		}

		_, unassignedErr := waitForFloatingIPReady(d, "completed", []string{"new"}, "status", meta, action.ID)
		if unassignedErr != nil {
			return fmt.Errorf(
				"Error waiting for FloatingIP (%s) to be unassigned: %s", d.Id(), unassignedErr)
		}
	}

	log.Printf("[INFO] Deleting FloatingIP: %s", d.Id())
	_, err := client.FloatingIPs.Delete(d.Id())
	if err != nil {
		return fmt.Errorf("Error deleting FloatingIP: %s", err)
	}

	d.SetId("")
	return nil
}

func waitForFloatingIPReady(
	d *schema.ResourceData, target string, pending []string, attribute string, meta interface{}, action int) (interface{}, error) {
	log.Printf(
		"[INFO] Waiting for FloatingIP (%s) to have %s of %s",
		d.Id(), attribute, target)

	stateConf := &resource.StateChangeConf{
		Pending:    pending,
		Target:     target,
		Refresh:    newFloatingIPStateRefreshFunc(d, attribute, meta, action),
		Timeout:    60 * time.Minute,
		Delay:      10 * time.Second,
		MinTimeout: 3 * time.Second,

		NotFoundChecks: 60,
	}

	return stateConf.WaitForState()
}

func newFloatingIPStateRefreshFunc(
	d *schema.ResourceData, attribute string, meta interface{}, action int) resource.StateRefreshFunc {
	client := meta.(*godo.Client)
	return func() (interface{}, string, error) {
		floatingIP, _, err := client.FloatingIPActions.Get(d.Id(), action)
		if err != nil {
			return nil, "", fmt.Errorf("Error retrieving FloatingIP Action: %s", err)
		}

		log.Printf("[INFO] The FloatingIP Assigned Status is %s", floatingIP.Status)
		return &floatingIP, floatingIP.Status, nil
	}
}
<|endoftext|>


<commit_before>package models

import (
	"net"
	"socialapi/request"

	"github.com/koding/logging"
	"github.com/koding/redis"
)

type Client struct {
	Account *Account
	IP      net.IP
}

type Context struct {
	GroupName string
	Client    *Client
	redis     *redis.RedisSession
	log       logging.Logger
}

func NewContext(redis *redis.RedisSession, log logging.Logger) *Context {
	return &Context{
		redis: redis,
		log:   log,
	}
}

func (c *Context) OverrideQuery(q *request.Query) *request.Query {
	// get group name from context
	q.GroupName = c.GroupName
	if c.IsLoggedIn() {
		q.AccountId = c.Client.Account.Id
	} else {
		q.AccountId = 0
	}

	return q
}

func (c *Context) IsLoggedIn() bool {
	if c.Client == nil {
		return false
	}

	if c.Client.Account == nil {
		return false
	}

	if c.Client.Account.Id == 0 {
		return false
	}

	return true
}

// IsAdmin checks if the current requester is an admin or not, this part is just
// a stub and temproray solution for moderation security, when we implement the
// permission system fully, this should be the first function to remove.
func (c *Context) IsAdmin() bool {
	if !c.IsLoggedIn() {
		return false
	}

	return IsIn(c.Client.Account.Nick, superAdmins...)
}

func (c *Context) MustGetLogger() logging.Logger {
	if c.log == nil {
		panic(ErrLoggerNotExist)
	}

	return c.log
}

func (c *Context) MustGetRedisConn() *redis.RedisSession {
	if c.redis == nil {
		panic(ErrRedisNotExist)
	}

	return c.redis
}

// c/p from account.coffee
var superAdmins = []string{
	"sinan", "devrim", "gokmen", "fatihacet", "arslan",
	"sent-hil", "cihangirsavas", "leeolayvar", "stefanbc",
	"szkl", "nitin", "usirin",
}
<commit_msg>socialapi: added documentation and session id into Client context<commit_after>package models

import (
	"net"
	"socialapi/request"

	"github.com/koding/logging"
	"github.com/koding/redis"
)

// Client holds the contextual requester/client info
type Client struct {
	// Account holds the requester info
	Account *Account

	// IP is remote IP of the requester
	IP net.IP

	// SessionID is session cookie id
	SessionID string
}

// Context holds contextual info regarding a REST query
type Context struct {
	GroupName string
	Client    *Client
	redis     *redis.RedisSession
	log       logging.Logger
}

// NewContext creates a new context
func NewContext(redis *redis.RedisSession, log logging.Logger) *Context {
	return &Context{
		redis: redis,
		log:   log,
	}
}

// OverrideQuery overrides Query with context info
func (c *Context) OverrideQuery(q *request.Query) *request.Query {
	// get group name from context
	q.GroupName = c.GroupName
	if c.IsLoggedIn() {
		q.AccountId = c.Client.Account.Id
	} else {
		q.AccountId = 0
	}

	return q
}

// IsLoggedIn checks if the request is an authenticated one
func (c *Context) IsLoggedIn() bool {
	if c.Client == nil {
		return false
	}

	if c.Client.Account == nil {
		return false
	}

	if c.Client.Account.Id == 0 {
		return false
	}

	return true
}

// IsAdmin checks if the current requester is an admin or not, this part is just
// a stub and temproray solution for moderation security, when we implement the
// permission system fully, this should be the first function to remove.
func (c *Context) IsAdmin() bool {
	if !c.IsLoggedIn() {
		return false
	}

	return IsIn(c.Client.Account.Nick, superAdmins...)
}

// MustGetLogger gets the logger from context, otherwise panics
func (c *Context) MustGetLogger() logging.Logger {
	if c.log == nil {
		panic(ErrLoggerNotExist)
	}

	return c.log
}

// MustGetRedisConn gets the logger from context, otherwise panics
func (c *Context) MustGetRedisConn() *redis.RedisSession {
	if c.redis == nil {
		panic(ErrRedisNotExist)
	}

	return c.redis
}

// c/p from account.coffee
var superAdmins = []string{
	"sinan", "devrim", "gokmen", "fatihacet", "arslan",
	"sent-hil", "cihangirsavas", "leeolayvar", "stefanbc",
	"szkl", "nitin", "usirin",
}
<|endoftext|>


<commit_before>// Copyright 2019 The OpenSDS 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 pwd

import (
	"fmt"
)

type PwdEncrypter interface {
	Encrypter(password string) (string, error)
	Decrypter(code string) (string, error)
}

func NewPwdEncrypter(encrypter string) PwdEncrypter {
	switch encrypter {
	case "aes":
		return NewAES()
	default:
		fmt.Println("Use default encryption tool: aes.")
		return NewAES()
	}
}
<commit_msg>Remove unneeded log to avoid duplicate log (#16)<commit_after>// Copyright 2019 The OpenSDS 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 pwd

type PwdEncrypter interface {
	Encrypter(password string) (string, error)
	Decrypter(code string) (string, error)
}

func NewPwdEncrypter(encrypter string) PwdEncrypter {
	switch encrypter {
	case "aes":
		return NewAES()
	default:
		return NewAES()
	}
}
<|endoftext|>


<commit_before>// Copyright 2015 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package migrations

import (
	"fmt"
	"strings"
	"time"

	"github.com/Unknwon/com"
	"github.com/go-xorm/xorm"

	"github.com/gogits/gogs/modules/log"
	"github.com/gogits/gogs/modules/setting"
)

const _MIN_DB_VER = 0

type Migration interface {
	Description() string
	Migrate(*xorm.Engine) error
}

type migration struct {
	description string
	migrate     func(*xorm.Engine) error
}

func NewMigration(desc string, fn func(*xorm.Engine) error) Migration {
	return &migration{desc, fn}
}

func (m *migration) Description() string {
	return m.description
}

func (m *migration) Migrate(x *xorm.Engine) error {
	return m.migrate(x)
}

// The version table. Should have only one row with id==1
type Version struct {
	Id      int64
	Version int64
}

// This is a sequence of migrations. Add new migrations to the bottom of the list.
// If you want to "retire" a migration, remove it from the top of the list and
// update _MIN_VER_DB accordingly
var migrations = []Migration{
	NewMigration("generate collaboration from access", accessToCollaboration), // V0 -> V1
	NewMigration("make authorize 4 if team is owners", ownerTeamUpdate),       // V1 -> V2
	NewMigration("refactor access table to use id's", accessRefactor),         // V2 -> V3
	NewMigration("generate team-repo from team", teamToTeamRepo),              // V3 -> V4
}

// Migrate database to current version
func Migrate(x *xorm.Engine) error {
	if err := x.Sync(new(Version)); err != nil {
		return fmt.Errorf("sync: %v", err)
	}

	currentVersion := &Version{Id: 1}
	has, err := x.Get(currentVersion)
	if err != nil {
		return fmt.Errorf("get: %v", err)
	} else if !has {
		// If the user table does not exist it is a fresh installation and we
		// can skip all migrations.
		needsMigration, err := x.IsTableExist("user")
		if err != nil {
			return err
		}
		if needsMigration {
			isEmpty, err := x.IsTableEmpty("user")
			if err != nil {
				return err
			}
			// If the user table is empty it is a fresh installation and we can
			// skip all migrations.
			needsMigration = !isEmpty
		}
		if !needsMigration {
			currentVersion.Version = int64(_MIN_DB_VER + len(migrations))
		}

		if _, err = x.InsertOne(currentVersion); err != nil {
			return fmt.Errorf("insert: %v", err)
		}
	}

	v := currentVersion.Version
	for i, m := range migrations[v-_MIN_DB_VER:] {
		log.Info("Migration: %s", m.Description())
		if err = m.Migrate(x); err != nil {
			return fmt.Errorf("do migrate: %v", err)
		}
		currentVersion.Version = v + int64(i) + 1
		if _, err = x.Id(1).Update(currentVersion); err != nil {
			return err
		}
	}
	return nil
}

func sessionRelease(sess *xorm.Session) {
	if !sess.IsCommitedOrRollbacked {
		sess.Rollback()
	}
	sess.Close()
}

func accessToCollaboration(x *xorm.Engine) (err error) {
	type Collaboration struct {
		ID      int64 `xorm:"pk autoincr"`
		RepoID  int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
		UserID  int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
		Created time.Time
	}

	if err = x.Sync(new(Collaboration)); err != nil {
		return fmt.Errorf("sync: %v", err)
	}

	results, err := x.Query("SELECT u.id AS `uid`, a.repo_name AS `repo`, a.mode AS `mode`, a.created as `created` FROM `access` a JOIN `user` u ON a.user_name=u.lower_name")
	if err != nil {
		return err
	}

	sess := x.NewSession()
	defer sessionRelease(sess)
	if err = sess.Begin(); err != nil {
		return err
	}

	offset := strings.Split(time.Now().String(), " ")[2]
	for _, result := range results {
		mode := com.StrTo(result["mode"]).MustInt64()
		// Collaborators must have write access.
		if mode < 2 {
			continue
		}

		userID := com.StrTo(result["uid"]).MustInt64()
		repoRefName := string(result["repo"])

		var created time.Time
		switch {
		case setting.UseSQLite3:
			created, _ = time.Parse(time.RFC3339, string(result["created"]))
		case setting.UseMySQL:
			created, _ = time.Parse("2006-01-02 15:04:05-0700", string(result["created"])+offset)
		case setting.UsePostgreSQL:
			created, _ = time.Parse("2006-01-02T15:04:05Z-0700", string(result["created"])+offset)
		}

		// find owner of repository
		parts := strings.SplitN(repoRefName, "/", 2)
		ownerName := parts[0]
		repoName := parts[1]

		results, err := sess.Query("SELECT u.id as `uid`, ou.uid as `memberid` FROM `user` u LEFT JOIN org_user ou ON ou.org_id=u.id WHERE u.lower_name=?", ownerName)
		if err != nil {
			return err
		}
		if len(results) < 1 {
			continue
		}

		ownerID := com.StrTo(results[0]["uid"]).MustInt64()
		if ownerID == userID {
			continue
		}

		// test if user is member of owning organization
		isMember := false
		for _, member := range results {
			memberID := com.StrTo(member["memberid"]).MustInt64()
			// We can skip all cases that a user is member of the owning organization
			if memberID == userID {
				isMember = true
			}
		}
		if isMember {
			continue
		}

		results, err = sess.Query("SELECT id FROM `repository` WHERE owner_id=? AND lower_name=?", ownerID, repoName)
		if err != nil {
			return err
		} else if len(results) < 1 {
			continue
		}

		collaboration := &Collaboration{
			UserID: userID,
			RepoID: com.StrTo(results[0]["id"]).MustInt64(),
		}
		has, err := sess.Get(collaboration)
		if err != nil {
			return err
		} else if has {
			continue
		}

		collaboration.Created = created
		if _, err = sess.InsertOne(collaboration); err != nil {
			return err
		}
	}

	return sess.Commit()
}

func ownerTeamUpdate(x *xorm.Engine) (err error) {
	if _, err := x.Exec("UPDATE `team` SET authorize=4 WHERE lower_name=?", "owners"); err != nil {
		return fmt.Errorf("update owner team table: %v", err)
	}
	return nil
}

func accessRefactor(x *xorm.Engine) (err error) {
	type (
		AccessMode int
		Access     struct {
			ID     int64 `xorm:"pk autoincr"`
			UserID int64 `xorm:"UNIQUE(s)"`
			RepoID int64 `xorm:"UNIQUE(s)"`
			Mode   AccessMode
		}
		UserRepo struct {
			UserID int64
			RepoID int64
		}
	)

	// We consiously don't start a session yet as we make only reads for now, no writes

	accessMap := make(map[UserRepo]AccessMode, 50)

	results, err := x.Query("SELECT r.id AS `repo_id`, r.is_private AS `is_private`, r.owner_id AS `owner_id`, u.type AS `owner_type` FROM `repository` r LEFT JOIN `user` u ON r.owner_id=u.id")
	if err != nil {
		return fmt.Errorf("select repositories: %v", err)
	}
	for _, repo := range results {
		repoID := com.StrTo(repo["repo_id"]).MustInt64()
		isPrivate := com.StrTo(repo["is_private"]).MustInt() > 0
		ownerID := com.StrTo(repo["owner_id"]).MustInt64()
		ownerIsOrganization := com.StrTo(repo["owner_type"]).MustInt() > 0

		results, err := x.Query("SELECT `user_id` FROM `collaboration` WHERE repo_id=?", repoID)
		if err != nil {
			return fmt.Errorf("select collaborators: %v", err)
		}
		for _, user := range results {
			userID := com.StrTo(user["user_id"]).MustInt64()
			accessMap[UserRepo{userID, repoID}] = 2 // WRITE ACCESS
		}

		if !ownerIsOrganization {
			continue
		}

		// The minimum level to add a new access record,
		// because public repository has implicit open access.
		minAccessLevel := AccessMode(0)
		if !isPrivate {
			minAccessLevel = 1
		}

		repoString := "$" + string(repo["repo_id"]) + "|"

		results, err = x.Query("SELECT `id`,`authorize`,`repo_ids` FROM `team` WHERE org_id=? AND authorize>? ORDER BY `authorize` ASC", ownerID, int(minAccessLevel))
		if err != nil {
			return fmt.Errorf("select teams from org: %v", err)
		}

		for _, team := range results {
			if !strings.Contains(string(team["repo_ids"]), repoString) {
				continue
			}
			teamID := com.StrTo(team["id"]).MustInt64()
			mode := AccessMode(com.StrTo(team["authorize"]).MustInt())

			results, err := x.Query("SELECT `uid` FROM `team_user` WHERE team_id=?", teamID)
			if err != nil {
				return fmt.Errorf("select users from team: %v", err)
			}
			for _, user := range results {
				userID := com.StrTo(user["user_id"]).MustInt64()
				accessMap[UserRepo{userID, repoID}] = mode
			}
		}
	}

	// Drop table can't be in a session (at least not in sqlite)
	if _, err = x.Exec("DROP TABLE `access`"); err != nil {
		return fmt.Errorf("drop access table: %v", err)
	}

	// Now we start writing so we make a session
	sess := x.NewSession()
	defer sessionRelease(sess)
	if err = sess.Begin(); err != nil {
		return err
	}

	if err = sess.Sync2(new(Access)); err != nil {
		return fmt.Errorf("sync: %v", err)
	}

	accesses := make([]*Access, 0, len(accessMap))
	for ur, mode := range accessMap {
		accesses = append(accesses, &Access{UserID: ur.UserID, RepoID: ur.RepoID, Mode: mode})
	}

	if _, err = sess.Insert(accesses); err != nil {
		return fmt.Errorf("insert accesses: %v", err)
	}

	return sess.Commit()
}

func teamToTeamRepo(x *xorm.Engine) error {
	type TeamRepo struct {
		ID     int64 `xorm:"pk autoincr"`
		OrgID  int64 `xorm:"INDEX"`
		TeamID int64 `xorm:"UNIQUE(s)"`
		RepoID int64 `xorm:"UNIQUE(s)"`
	}

	teamRepos := make([]*TeamRepo, 0, 50)

	results, err := x.Query("SELECT `id`,`org_id`,`repo_ids` FROM `team`")
	if err != nil {
		return fmt.Errorf("select teams: %v", err)
	}
	for _, team := range results {
		orgID := com.StrTo(team["org_id"]).MustInt64()
		teamID := com.StrTo(team["id"]).MustInt64()

		for _, idStr := range strings.Split(string(team["repo_ids"]), "|") {
			repoID := com.StrTo(strings.TrimPrefix(idStr, "$")).MustInt64()
			if repoID == 0 {
				continue
			}

			teamRepos = append(teamRepos, &TeamRepo{
				OrgID:  orgID,
				TeamID: teamID,
				RepoID: repoID,
			})
		}
	}

	sess := x.NewSession()
	defer sessionRelease(sess)
	if err = sess.Begin(); err != nil {
		return err
	}

	if err = sess.Sync2(new(TeamRepo)); err != nil {
		return fmt.Errorf("sync: %v", err)
	} else if _, err = sess.Insert(teamRepos); err != nil {
		return fmt.Errorf("insert team-repos: %v", err)
	}

	return sess.Commit()
}
<commit_msg>Migration<commit_after>// Copyright 2015 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package migrations

import (
	"fmt"
	"strings"
	"time"

	"github.com/Unknwon/com"
	"github.com/go-xorm/xorm"

	"github.com/gogits/gogs/modules/log"
	"github.com/gogits/gogs/modules/setting"
)

const _MIN_DB_VER = 0

type Migration interface {
	Description() string
	Migrate(*xorm.Engine) error
}

type migration struct {
	description string
	migrate     func(*xorm.Engine) error
}

func NewMigration(desc string, fn func(*xorm.Engine) error) Migration {
	return &migration{desc, fn}
}

func (m *migration) Description() string {
	return m.description
}

func (m *migration) Migrate(x *xorm.Engine) error {
	return m.migrate(x)
}

// The version table. Should have only one row with id==1
type Version struct {
	Id      int64
	Version int64
}

// This is a sequence of migrations. Add new migrations to the bottom of the list.
// If you want to "retire" a migration, remove it from the top of the list and
// update _MIN_VER_DB accordingly
var migrations = []Migration{
	NewMigration("generate collaboration from access", accessToCollaboration), // V0 -> V1
	NewMigration("make authorize 4 if team is owners", ownerTeamUpdate),       // V1 -> V2
	NewMigration("refactor access table to use id's", accessRefactor),         // V2 -> V3
	NewMigration("generate team-repo from team", teamToTeamRepo),              // V3 -> V4
	NewMigration("change comment table", prepareToCommitComments),             // V4 -> V5
}

// Migrate database to current version
func Migrate(x *xorm.Engine) error {
	if err := x.Sync(new(Version)); err != nil {
		return fmt.Errorf("sync: %v", err)
	}

	currentVersion := &Version{Id: 1}
	has, err := x.Get(currentVersion)
	if err != nil {
		return fmt.Errorf("get: %v", err)
	} else if !has {
		// If the user table does not exist it is a fresh installation and we
		// can skip all migrations.
		needsMigration, err := x.IsTableExist("user")
		if err != nil {
			return err
		}
		if needsMigration {
			isEmpty, err := x.IsTableEmpty("user")
			if err != nil {
				return err
			}
			// If the user table is empty it is a fresh installation and we can
			// skip all migrations.
			needsMigration = !isEmpty
		}
		if !needsMigration {
			currentVersion.Version = int64(_MIN_DB_VER + len(migrations))
		}

		if _, err = x.InsertOne(currentVersion); err != nil {
			return fmt.Errorf("insert: %v", err)
		}
	}

	v := currentVersion.Version
	for i, m := range migrations[v-_MIN_DB_VER:] {
		log.Info("Migration: %s", m.Description())
		if err = m.Migrate(x); err != nil {
			return fmt.Errorf("do migrate: %v", err)
		}
		currentVersion.Version = v + int64(i) + 1
		if _, err = x.Id(1).Update(currentVersion); err != nil {
			return err
		}
	}
	return nil
}

func sessionRelease(sess *xorm.Session) {
	if !sess.IsCommitedOrRollbacked {
		sess.Rollback()
	}
	sess.Close()
}

func accessToCollaboration(x *xorm.Engine) (err error) {
	type Collaboration struct {
		ID      int64 `xorm:"pk autoincr"`
		RepoID  int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
		UserID  int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
		Created time.Time
	}

	if err = x.Sync(new(Collaboration)); err != nil {
		return fmt.Errorf("sync: %v", err)
	}

	results, err := x.Query("SELECT u.id AS `uid`, a.repo_name AS `repo`, a.mode AS `mode`, a.created as `created` FROM `access` a JOIN `user` u ON a.user_name=u.lower_name")
	if err != nil {
		return err
	}

	sess := x.NewSession()
	defer sessionRelease(sess)
	if err = sess.Begin(); err != nil {
		return err
	}

	offset := strings.Split(time.Now().String(), " ")[2]
	for _, result := range results {
		mode := com.StrTo(result["mode"]).MustInt64()
		// Collaborators must have write access.
		if mode < 2 {
			continue
		}

		userID := com.StrTo(result["uid"]).MustInt64()
		repoRefName := string(result["repo"])

		var created time.Time
		switch {
		case setting.UseSQLite3:
			created, _ = time.Parse(time.RFC3339, string(result["created"]))
		case setting.UseMySQL:
			created, _ = time.Parse("2006-01-02 15:04:05-0700", string(result["created"])+offset)
		case setting.UsePostgreSQL:
			created, _ = time.Parse("2006-01-02T15:04:05Z-0700", string(result["created"])+offset)
		}

		// find owner of repository
		parts := strings.SplitN(repoRefName, "/", 2)
		ownerName := parts[0]
		repoName := parts[1]

		results, err := sess.Query("SELECT u.id as `uid`, ou.uid as `memberid` FROM `user` u LEFT JOIN org_user ou ON ou.org_id=u.id WHERE u.lower_name=?", ownerName)
		if err != nil {
			return err
		}
		if len(results) < 1 {
			continue
		}

		ownerID := com.StrTo(results[0]["uid"]).MustInt64()
		if ownerID == userID {
			continue
		}

		// test if user is member of owning organization
		isMember := false
		for _, member := range results {
			memberID := com.StrTo(member["memberid"]).MustInt64()
			// We can skip all cases that a user is member of the owning organization
			if memberID == userID {
				isMember = true
			}
		}
		if isMember {
			continue
		}

		results, err = sess.Query("SELECT id FROM `repository` WHERE owner_id=? AND lower_name=?", ownerID, repoName)
		if err != nil {
			return err
		} else if len(results) < 1 {
			continue
		}

		collaboration := &Collaboration{
			UserID: userID,
			RepoID: com.StrTo(results[0]["id"]).MustInt64(),
		}
		has, err := sess.Get(collaboration)
		if err != nil {
			return err
		} else if has {
			continue
		}

		collaboration.Created = created
		if _, err = sess.InsertOne(collaboration); err != nil {
			return err
		}
	}

	return sess.Commit()
}

func ownerTeamUpdate(x *xorm.Engine) (err error) {
	if _, err := x.Exec("UPDATE `team` SET authorize=4 WHERE lower_name=?", "owners"); err != nil {
		return fmt.Errorf("update owner team table: %v", err)
	}
	return nil
}

func accessRefactor(x *xorm.Engine) (err error) {
	type (
		AccessMode int
		Access     struct {
			ID     int64 `xorm:"pk autoincr"`
			UserID int64 `xorm:"UNIQUE(s)"`
			RepoID int64 `xorm:"UNIQUE(s)"`
			Mode   AccessMode
		}
		UserRepo struct {
			UserID int64
			RepoID int64
		}
	)

	// We consiously don't start a session yet as we make only reads for now, no writes

	accessMap := make(map[UserRepo]AccessMode, 50)

	results, err := x.Query("SELECT r.id AS `repo_id`, r.is_private AS `is_private`, r.owner_id AS `owner_id`, u.type AS `owner_type` FROM `repository` r LEFT JOIN `user` u ON r.owner_id=u.id")
	if err != nil {
		return fmt.Errorf("select repositories: %v", err)
	}
	for _, repo := range results {
		repoID := com.StrTo(repo["repo_id"]).MustInt64()
		isPrivate := com.StrTo(repo["is_private"]).MustInt() > 0
		ownerID := com.StrTo(repo["owner_id"]).MustInt64()
		ownerIsOrganization := com.StrTo(repo["owner_type"]).MustInt() > 0

		results, err := x.Query("SELECT `user_id` FROM `collaboration` WHERE repo_id=?", repoID)
		if err != nil {
			return fmt.Errorf("select collaborators: %v", err)
		}
		for _, user := range results {
			userID := com.StrTo(user["user_id"]).MustInt64()
			accessMap[UserRepo{userID, repoID}] = 2 // WRITE ACCESS
		}

		if !ownerIsOrganization {
			continue
		}

		// The minimum level to add a new access record,
		// because public repository has implicit open access.
		minAccessLevel := AccessMode(0)
		if !isPrivate {
			minAccessLevel = 1
		}

		repoString := "$" + string(repo["repo_id"]) + "|"

		results, err = x.Query("SELECT `id`,`authorize`,`repo_ids` FROM `team` WHERE org_id=? AND authorize>? ORDER BY `authorize` ASC", ownerID, int(minAccessLevel))
		if err != nil {
			return fmt.Errorf("select teams from org: %v", err)
		}

		for _, team := range results {
			if !strings.Contains(string(team["repo_ids"]), repoString) {
				continue
			}
			teamID := com.StrTo(team["id"]).MustInt64()
			mode := AccessMode(com.StrTo(team["authorize"]).MustInt())

			results, err := x.Query("SELECT `uid` FROM `team_user` WHERE team_id=?", teamID)
			if err != nil {
				return fmt.Errorf("select users from team: %v", err)
			}
			for _, user := range results {
				userID := com.StrTo(user["user_id"]).MustInt64()
				accessMap[UserRepo{userID, repoID}] = mode
			}
		}
	}

	// Drop table can't be in a session (at least not in sqlite)
	if _, err = x.Exec("DROP TABLE `access`"); err != nil {
		return fmt.Errorf("drop access table: %v", err)
	}

	// Now we start writing so we make a session
	sess := x.NewSession()
	defer sessionRelease(sess)
	if err = sess.Begin(); err != nil {
		return err
	}

	if err = sess.Sync2(new(Access)); err != nil {
		return fmt.Errorf("sync: %v", err)
	}

	accesses := make([]*Access, 0, len(accessMap))
	for ur, mode := range accessMap {
		accesses = append(accesses, &Access{UserID: ur.UserID, RepoID: ur.RepoID, Mode: mode})
	}

	if _, err = sess.Insert(accesses); err != nil {
		return fmt.Errorf("insert accesses: %v", err)
	}

	return sess.Commit()
}

func teamToTeamRepo(x *xorm.Engine) error {
	type TeamRepo struct {
		ID     int64 `xorm:"pk autoincr"`
		OrgID  int64 `xorm:"INDEX"`
		TeamID int64 `xorm:"UNIQUE(s)"`
		RepoID int64 `xorm:"UNIQUE(s)"`
	}

	teamRepos := make([]*TeamRepo, 0, 50)

	results, err := x.Query("SELECT `id`,`org_id`,`repo_ids` FROM `team`")
	if err != nil {
		return fmt.Errorf("select teams: %v", err)
	}
	for _, team := range results {
		orgID := com.StrTo(team["org_id"]).MustInt64()
		teamID := com.StrTo(team["id"]).MustInt64()

		for _, idStr := range strings.Split(string(team["repo_ids"]), "|") {
			repoID := com.StrTo(strings.TrimPrefix(idStr, "$")).MustInt64()
			if repoID == 0 {
				continue
			}

			teamRepos = append(teamRepos, &TeamRepo{
				OrgID:  orgID,
				TeamID: teamID,
				RepoID: repoID,
			})
		}
	}

	sess := x.NewSession()
	defer sessionRelease(sess)
	if err = sess.Begin(); err != nil {
		return err
	}

	if err = sess.Sync2(new(TeamRepo)); err != nil {
		return fmt.Errorf("sync: %v", err)
	} else if _, err = sess.Insert(teamRepos); err != nil {
		return fmt.Errorf("insert team-repos: %v", err)
	}

	return sess.Commit()
}

func prepareToCommitComments(x *xorm.Engine) error {

	sql := `ALTER TABLE comment MODIFY commit_id VARCHAR(50) NULL DEFAULT NULL`
	_, err := x.Exec(sql)
	if err != nil {
		return err
	}

	sql = `ALTER TABLE comment MODIFY line VARCHAR(50) NULL DEFAULT NULL;`
	_, err = x.Exec(sql)
	if err != nil {
		return err
	}

	sql = `UPDATE comment SET commit_id = '', line = '' WHERE commit_id = '0' AND line = '0'`
	_, err = x.Exec(sql)
	if err != nil {
		return err
	}
	return nil
}
<|endoftext|>


<commit_before>// Copyright 2015, Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package tabletserver

import (
	"fmt"
	"math/rand"
	"strings"
	"testing"
	"time"

	"golang.org/x/net/context"

	"github.com/youtube/vitess/go/mysqlconn/fakesqldb"
	"github.com/youtube/vitess/go/sqltypes"
	"github.com/youtube/vitess/go/vt/tabletserver/tabletenv"
)

func TestTxPoolExecuteRollback(t *testing.T) {
	sql := "alter table test_table add test_column int"
	db := fakesqldb.New(t)
	defer db.Close()
	db.AddQuery(sql, &sqltypes.Result{})
	db.AddQuery("begin", &sqltypes.Result{})
	db.AddQuery("rollback", &sqltypes.Result{})

	txPool := newTxPool()
	txPool.Open(db.ConnParams(), db.ConnParams())
	defer txPool.Close()
	ctx := context.Background()
	transactionID, err := txPool.Begin(ctx)
	if err != nil {
		t.Fatal(err)
	}
	txConn, err := txPool.Get(transactionID, "for query")
	if err != nil {
		t.Fatal(err)
	}
	defer txPool.Rollback(ctx, transactionID)
	txConn.RecordQuery(sql)
	_, err = txConn.Exec(ctx, sql, 1, true)
	txConn.Recycle()
	if err != nil {
		t.Fatalf("got error: %v", err)
	}
}

func TestTxPoolRollbackNonBusy(t *testing.T) {
	db := fakesqldb.New(t)
	defer db.Close()
	db.AddQuery("begin", &sqltypes.Result{})
	db.AddQuery("rollback", &sqltypes.Result{})

	txPool := newTxPool()
	txPool.Open(db.ConnParams(), db.ConnParams())
	defer txPool.Close()
	ctx := context.Background()
	txid1, err := txPool.Begin(ctx)
	if err != nil {
		t.Fatal(err)
	}
	_, err = txPool.Begin(ctx)
	if err != nil {
		t.Fatal(err)
	}
	conn1, err := txPool.Get(txid1, "for query")
	if err != nil {
		t.Fatal(err)
	}
	// This should rollback only txid2.
	txPool.RollbackNonBusy(ctx)
	if sz := txPool.activePool.Size(); sz != 1 {
		t.Errorf("txPool.activePool.Size(): %d, want 1", sz)
	}
	conn1.Recycle()
	// This should rollback txid1.
	txPool.RollbackNonBusy(ctx)
	if sz := txPool.activePool.Size(); sz != 0 {
		t.Errorf("txPool.activePool.Size(): %d, want 0", sz)
	}
}

func TestTxPoolTransactionKiller(t *testing.T) {
	sql := "alter table test_table add test_column int"
	db := fakesqldb.New(t)
	defer db.Close()
	db.AddQuery(sql, &sqltypes.Result{})
	db.AddQuery("begin", &sqltypes.Result{})

	txPool := newTxPool()
	// make sure transaction killer will run frequent enough
	txPool.SetTimeout(1 * time.Millisecond)
	txPool.Open(db.ConnParams(), db.ConnParams())
	defer txPool.Close()
	ctx := context.Background()
	killCount := tabletenv.KillStats.Counts()["Transactions"]
	transactionID, err := txPool.Begin(ctx)
	if err != nil {
		t.Fatal(err)
	}
	txConn, err := txPool.Get(transactionID, "for query")
	if err != nil {
		t.Fatal(err)
	}
	txConn.RecordQuery(sql)
	txConn.Recycle()
	// transaction killer should kill the query
	txPool.WaitForEmpty()
	killCountDiff := tabletenv.KillStats.Counts()["Transactions"] - killCount
	if killCountDiff != 1 {
		t.Fatalf("query: %s should be killed by transaction killer", sql)
	}
}

func TestTxPoolBeginAfterConnPoolClosed(t *testing.T) {
	db := fakesqldb.New(t)
	defer db.Close()
	txPool := newTxPool()
	txPool.SetTimeout(time.Duration(10))
	txPool.Open(db.ConnParams(), db.ConnParams())
	txPool.Close()
	ctx := context.Background()
	_, err := txPool.Begin(ctx)
	if err == nil {
		t.Fatalf("expect to get an error")
	}
	terr, ok := err.(*tabletenv.TabletError)
	if !ok || terr != tabletenv.ErrConnPoolClosed {
		t.Fatalf("get error: %v, but expect: %v", terr, tabletenv.ErrConnPoolClosed)
	}
}

func TestTxPoolBeginWithPoolConnectionError(t *testing.T) {
	db := fakesqldb.New(t)
	db.Close()
	//	db.EnableConnFail()
	txPool := newTxPool()
	txPool.Open(db.ConnParams(), db.ConnParams())
	defer txPool.Close()
	ctx := context.Background()
	_, err := txPool.Begin(ctx)
	want := "errno 2003"
	if err == nil || !strings.Contains(err.Error(), want) {
		t.Errorf("Begin: %v, want %s", err, want)
	}
}

func TestTxPoolBeginWithExecError(t *testing.T) {
	db := fakesqldb.New(t)
	defer db.Close()
	db.AddRejectedQuery("begin", errRejected)
	txPool := newTxPool()
	txPool.Open(db.ConnParams(), db.ConnParams())
	defer txPool.Close()
	ctx := context.Background()
	_, err := txPool.Begin(ctx)
	want := "error: rejected"
	if err == nil || !strings.Contains(err.Error(), want) {
		t.Errorf("Begin: %v, want %s", err, want)
	}
}

func TestTxPoolRollbackFail(t *testing.T) {
	sql := "alter table test_table add test_column int"
	db := fakesqldb.New(t)
	defer db.Close()
	db.AddQuery(sql, &sqltypes.Result{})
	db.AddQuery("begin", &sqltypes.Result{})
	db.AddRejectedQuery("rollback", errRejected)

	txPool := newTxPool()
	txPool.Open(db.ConnParams(), db.ConnParams())
	defer txPool.Close()
	ctx := context.Background()
	transactionID, err := txPool.Begin(ctx)
	if err != nil {
		t.Fatal(err)
	}
	txConn, err := txPool.Get(transactionID, "for query")
	if err != nil {
		t.Fatal(err)
	}
	txConn.RecordQuery(sql)
	_, err = txConn.Exec(ctx, sql, 1, true)
	txConn.Recycle()
	if err != nil {
		t.Fatalf("got error: %v", err)
	}
	err = txPool.Rollback(ctx, transactionID)
	want := "error: rejected"
	if err == nil || !strings.Contains(err.Error(), want) {
		t.Errorf("Begin: %v, want %s", err, want)
	}
}

func TestTxPoolGetConnFail(t *testing.T) {
	db := fakesqldb.New(t)
	defer db.Close()
	txPool := newTxPool()
	txPool.Open(db.ConnParams(), db.ConnParams())
	defer txPool.Close()
	_, err := txPool.Get(12345, "for query")
	want := "not_in_tx: Transaction 12345: not found"
	if err == nil || err.Error() != want {
		t.Errorf("Get: %v, want %s", err, want)
	}
}

func TestTxPoolExecFailDueToConnFail(t *testing.T) {
	db := fakesqldb.New(t)
	defer db.Close()
	db.AddQuery("begin", &sqltypes.Result{})

	txPool := newTxPool()
	txPool.Open(db.ConnParams(), db.ConnParams())
	defer txPool.Close()
	ctx := context.Background()
	sql := "alter table test_table add test_column int"

	transactionID, err := txPool.Begin(ctx)
	if err != nil {
		t.Fatal(err)
	}
	txConn, err := txPool.Get(transactionID, "for query")
	if err != nil {
		t.Fatal(err)
	}
	db.EnableConnFail()
	_, err = txConn.Exec(ctx, sql, 1, true)
	txConn.Recycle()
	if err == nil {
		t.Fatalf("exec should fail because of a conn error")
	}
}

func TestTxPoolCloseKillsStrayTransactions(t *testing.T) {
	db := fakesqldb.New(t)
	defer db.Close()
	db.AddQuery("begin", &sqltypes.Result{})

	txPool := newTxPool()
	txPool.Open(db.ConnParams(), db.ConnParams())

	// Start stray transaction.
	_, err := txPool.Begin(context.Background())
	if err != nil {
		t.Fatal(err)
	}

	// Close kills stray transaction.
	txPool.Close()
	if got, want := tabletenv.InternalErrors.Counts()["StrayTransactions"], int64(1); got != want {
		t.Fatalf("internal error count for stray transactions not increased: got = %v, want = %v", got, want)
	}
	if got, want := txPool.conns.Capacity(), int64(0); got != want {
		t.Fatalf("resource pool was not closed. capacity: got = %v, want = %v", got, want)
	}
}

func newTxPool() *TxPool {
	randID := rand.Int63()
	poolName := fmt.Sprintf("TestTransactionPool-%d", randID)
	transactionCap := 300
	transactionTimeout := time.Duration(30 * time.Second)
	idleTimeout := time.Duration(30 * time.Second)
	return NewTxPool(
		poolName,
		transactionCap,
		transactionTimeout,
		idleTimeout,
		DummyChecker,
	)
}
<commit_msg>tabletserver: Add newlines to make it easier to read the test.<commit_after>// Copyright 2015, Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package tabletserver

import (
	"fmt"
	"math/rand"
	"strings"
	"testing"
	"time"

	"golang.org/x/net/context"

	"github.com/youtube/vitess/go/mysqlconn/fakesqldb"
	"github.com/youtube/vitess/go/sqltypes"
	"github.com/youtube/vitess/go/vt/tabletserver/tabletenv"
)

func TestTxPoolExecuteRollback(t *testing.T) {
	sql := "alter table test_table add test_column int"
	db := fakesqldb.New(t)
	defer db.Close()
	db.AddQuery(sql, &sqltypes.Result{})
	db.AddQuery("begin", &sqltypes.Result{})
	db.AddQuery("rollback", &sqltypes.Result{})

	txPool := newTxPool()
	txPool.Open(db.ConnParams(), db.ConnParams())
	defer txPool.Close()
	ctx := context.Background()
	transactionID, err := txPool.Begin(ctx)
	if err != nil {
		t.Fatal(err)
	}
	txConn, err := txPool.Get(transactionID, "for query")
	if err != nil {
		t.Fatal(err)
	}
	defer txPool.Rollback(ctx, transactionID)
	txConn.RecordQuery(sql)
	_, err = txConn.Exec(ctx, sql, 1, true)
	txConn.Recycle()
	if err != nil {
		t.Fatalf("got error: %v", err)
	}
}

func TestTxPoolRollbackNonBusy(t *testing.T) {
	db := fakesqldb.New(t)
	defer db.Close()
	db.AddQuery("begin", &sqltypes.Result{})
	db.AddQuery("rollback", &sqltypes.Result{})

	txPool := newTxPool()
	txPool.Open(db.ConnParams(), db.ConnParams())
	defer txPool.Close()
	ctx := context.Background()
	txid1, err := txPool.Begin(ctx)
	if err != nil {
		t.Fatal(err)
	}
	_, err = txPool.Begin(ctx)
	if err != nil {
		t.Fatal(err)
	}
	conn1, err := txPool.Get(txid1, "for query")
	if err != nil {
		t.Fatal(err)
	}
	// This should rollback only txid2.
	txPool.RollbackNonBusy(ctx)
	if sz := txPool.activePool.Size(); sz != 1 {
		t.Errorf("txPool.activePool.Size(): %d, want 1", sz)
	}
	conn1.Recycle()
	// This should rollback txid1.
	txPool.RollbackNonBusy(ctx)
	if sz := txPool.activePool.Size(); sz != 0 {
		t.Errorf("txPool.activePool.Size(): %d, want 0", sz)
	}
}

func TestTxPoolTransactionKiller(t *testing.T) {
	sql := "alter table test_table add test_column int"
	db := fakesqldb.New(t)
	defer db.Close()
	db.AddQuery(sql, &sqltypes.Result{})
	db.AddQuery("begin", &sqltypes.Result{})

	txPool := newTxPool()
	// make sure transaction killer will run frequent enough
	txPool.SetTimeout(1 * time.Millisecond)
	txPool.Open(db.ConnParams(), db.ConnParams())
	defer txPool.Close()
	ctx := context.Background()
	killCount := tabletenv.KillStats.Counts()["Transactions"]
	transactionID, err := txPool.Begin(ctx)
	if err != nil {
		t.Fatal(err)
	}
	txConn, err := txPool.Get(transactionID, "for query")
	if err != nil {
		t.Fatal(err)
	}
	txConn.RecordQuery(sql)
	txConn.Recycle()
	// transaction killer should kill the query
	txPool.WaitForEmpty()
	killCountDiff := tabletenv.KillStats.Counts()["Transactions"] - killCount
	if killCountDiff != 1 {
		t.Fatalf("query: %s should be killed by transaction killer", sql)
	}
}

func TestTxPoolBeginAfterConnPoolClosed(t *testing.T) {
	db := fakesqldb.New(t)
	defer db.Close()
	txPool := newTxPool()
	txPool.SetTimeout(time.Duration(10))
	txPool.Open(db.ConnParams(), db.ConnParams())

	txPool.Close()

	_, err := txPool.Begin(context.Background())
	if err == nil {
		t.Fatalf("expect to get an error")
	}
	terr, ok := err.(*tabletenv.TabletError)
	if !ok || terr != tabletenv.ErrConnPoolClosed {
		t.Fatalf("get error: %v, but expect: %v", terr, tabletenv.ErrConnPoolClosed)
	}
}

func TestTxPoolBeginWithPoolConnectionError(t *testing.T) {
	db := fakesqldb.New(t)
	db.Close()
	//	db.EnableConnFail()
	txPool := newTxPool()
	txPool.Open(db.ConnParams(), db.ConnParams())
	defer txPool.Close()
	ctx := context.Background()
	_, err := txPool.Begin(ctx)
	want := "errno 2003"
	if err == nil || !strings.Contains(err.Error(), want) {
		t.Errorf("Begin: %v, want %s", err, want)
	}
}

func TestTxPoolBeginWithExecError(t *testing.T) {
	db := fakesqldb.New(t)
	defer db.Close()
	db.AddRejectedQuery("begin", errRejected)
	txPool := newTxPool()
	txPool.Open(db.ConnParams(), db.ConnParams())
	defer txPool.Close()
	ctx := context.Background()
	_, err := txPool.Begin(ctx)
	want := "error: rejected"
	if err == nil || !strings.Contains(err.Error(), want) {
		t.Errorf("Begin: %v, want %s", err, want)
	}
}

func TestTxPoolRollbackFail(t *testing.T) {
	sql := "alter table test_table add test_column int"
	db := fakesqldb.New(t)
	defer db.Close()
	db.AddQuery(sql, &sqltypes.Result{})
	db.AddQuery("begin", &sqltypes.Result{})
	db.AddRejectedQuery("rollback", errRejected)

	txPool := newTxPool()
	txPool.Open(db.ConnParams(), db.ConnParams())
	defer txPool.Close()
	ctx := context.Background()
	transactionID, err := txPool.Begin(ctx)
	if err != nil {
		t.Fatal(err)
	}
	txConn, err := txPool.Get(transactionID, "for query")
	if err != nil {
		t.Fatal(err)
	}
	txConn.RecordQuery(sql)
	_, err = txConn.Exec(ctx, sql, 1, true)
	txConn.Recycle()
	if err != nil {
		t.Fatalf("got error: %v", err)
	}
	err = txPool.Rollback(ctx, transactionID)
	want := "error: rejected"
	if err == nil || !strings.Contains(err.Error(), want) {
		t.Errorf("Begin: %v, want %s", err, want)
	}
}

func TestTxPoolGetConnFail(t *testing.T) {
	db := fakesqldb.New(t)
	defer db.Close()
	txPool := newTxPool()
	txPool.Open(db.ConnParams(), db.ConnParams())
	defer txPool.Close()
	_, err := txPool.Get(12345, "for query")
	want := "not_in_tx: Transaction 12345: not found"
	if err == nil || err.Error() != want {
		t.Errorf("Get: %v, want %s", err, want)
	}
}

func TestTxPoolExecFailDueToConnFail(t *testing.T) {
	db := fakesqldb.New(t)
	defer db.Close()
	db.AddQuery("begin", &sqltypes.Result{})

	txPool := newTxPool()
	txPool.Open(db.ConnParams(), db.ConnParams())
	defer txPool.Close()
	ctx := context.Background()
	sql := "alter table test_table add test_column int"

	transactionID, err := txPool.Begin(ctx)
	if err != nil {
		t.Fatal(err)
	}
	txConn, err := txPool.Get(transactionID, "for query")
	if err != nil {
		t.Fatal(err)
	}
	db.EnableConnFail()
	_, err = txConn.Exec(ctx, sql, 1, true)
	txConn.Recycle()
	if err == nil {
		t.Fatalf("exec should fail because of a conn error")
	}
}

func TestTxPoolCloseKillsStrayTransactions(t *testing.T) {
	db := fakesqldb.New(t)
	defer db.Close()
	db.AddQuery("begin", &sqltypes.Result{})

	txPool := newTxPool()
	txPool.Open(db.ConnParams(), db.ConnParams())

	// Start stray transaction.
	_, err := txPool.Begin(context.Background())
	if err != nil {
		t.Fatal(err)
	}

	// Close kills stray transaction.
	txPool.Close()
	if got, want := tabletenv.InternalErrors.Counts()["StrayTransactions"], int64(1); got != want {
		t.Fatalf("internal error count for stray transactions not increased: got = %v, want = %v", got, want)
	}
	if got, want := txPool.conns.Capacity(), int64(0); got != want {
		t.Fatalf("resource pool was not closed. capacity: got = %v, want = %v", got, want)
	}
}

func newTxPool() *TxPool {
	randID := rand.Int63()
	poolName := fmt.Sprintf("TestTransactionPool-%d", randID)
	transactionCap := 300
	transactionTimeout := time.Duration(30 * time.Second)
	idleTimeout := time.Duration(30 * time.Second)
	return NewTxPool(
		poolName,
		transactionCap,
		transactionTimeout,
		idleTimeout,
		DummyChecker,
	)
}
<|endoftext|>


<commit_before>package platform

import (
	"os"
)

type Platform struct{}

const name = "platform"

func (self *Platform) Name() string {
	return name
}

func (self *Platform) Collect() (result interface{}, err error) {
    result, err = getPlatformInfo()
    return
}

func getPlatformInfo() (platformInfo map[string]interface{}, err error) {
    platformInfo = make(map[string]interface{})

    hostname, err := os.Hostname()
    if err != nil {
        return platformInfo, err
    }
    platformInfo["hostname"] = hostname

    return
}
<commit_msg>Add python version to platform collector<commit_after>package platform

import (
	"os"
    "runtime"
    "os/exec"
    "fmt"
    "regexp"
    // "strings"
)

type Platform struct{}

const name = "platform"

func (self *Platform) Name() string {
	return name
}

func (self *Platform) Collect() (result interface{}, err error) {
    result, err = getPlatformInfo()
    return
}

func getPlatformInfo() (platformInfo map[string]interface{}, err error) {
    platformInfo = make(map[string]interface{})

    hostname, err := os.Hostname()
    if err != nil {
        return platformInfo, err
    }
    platformInfo["hostname"] = hostname

    platformInfo["os"] = runtime.GOOS
    platformInfo["goV"] = runtime.Version()
    pythonV, err := getPythonVersion()
    if err != nil {
        return platformInfo, err
    }
    platformInfo["pythonV"] = pythonV

    return
}

func getPythonVersion() (string, error) {
    out, err := exec.Command("python", "-V").CombinedOutput()
    if err != nil {
        return "", err
    }
    version := fmt.Sprintf("%s", out)
    values := regexp.MustCompile("Python (.*)\n").FindStringSubmatch(version)
    return values[1], nil
}
<|endoftext|>


<commit_before>package daemon

import (
	"fmt"

	"github.com/docker/docker/container"
)

// ContainerUnpause unpauses a container
func (daemon *Daemon) ContainerUnpause(name string) error {
	container, err := daemon.GetContainer(name)
	if err != nil {
		return err
	}

	if err := daemon.containerUnpause(container); err != nil {
		return err
	}

	return nil
}

// containerUnpause resumes the container execution after the container is paused.
func (daemon *Daemon) containerUnpause(container *container.Container) error {
	container.Lock()
	defer container.Unlock()

	// We cannot unpause the container which is not running
	if !container.Running {
		return errNotRunning{container.ID}
	}

	// We cannot unpause the container which is not paused
	if !container.Paused {
		return fmt.Errorf("Container %s is not paused", container.ID)
	}

	if err := daemon.containerd.Resume(container.ID); err != nil {
		return fmt.Errorf("Cannot unpause container %s: %s", container.ID, err)
	}

	return nil
}
<commit_msg>remove running judgement when unpause container<commit_after>package daemon

import (
	"fmt"

	"github.com/docker/docker/container"
)

// ContainerUnpause unpauses a container
func (daemon *Daemon) ContainerUnpause(name string) error {
	container, err := daemon.GetContainer(name)
	if err != nil {
		return err
	}

	if err := daemon.containerUnpause(container); err != nil {
		return err
	}

	return nil
}

// containerUnpause resumes the container execution after the container is paused.
func (daemon *Daemon) containerUnpause(container *container.Container) error {
	container.Lock()
	defer container.Unlock()

	// We cannot unpause the container which is not paused
	if !container.Paused {
		return fmt.Errorf("Container %s is not paused", container.ID)
	}

	if err := daemon.containerd.Resume(container.ID); err != nil {
		return fmt.Errorf("Cannot unpause container %s: %s", container.ID, err)
	}

	return nil
}
<|endoftext|>


<commit_before>package immortal

import (
	"fmt"
	"os"
	"path/filepath"
	"testing"
	"time"
)

func TestHelperProcess(t *testing.T) {
	if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" {
		return
	}
	time.Sleep(10 * time.Second)
}

func TestDaemonRun(t *testing.T) {
	base := filepath.Base(os.Args[0]) // "exec.test"
	dir := filepath.Dir(os.Args[0])   // "/tmp/go-buildNNNN/os/exec/_test"
	if dir == "." {
		t.Skip("skipping; running test at root somehow")
	}
	parentDir := filepath.Dir(dir) // "/tmp/go-buildNNNN/os/exec"
	dirBase := filepath.Base(dir)  // "_test"
	if dirBase == "." {
		t.Skipf("skipping; unexpected shallow dir of %q", dir)
	}

	cfg := &Config{
		Env:     map[string]string{"GO_WANT_HELPER_PROCESS": "1"},
		command: []string{filepath.Join(dirBase, base), "-test.run=TestHelperProcess"},
		Cwd:     parentDir,
		Pid: Pid{
			Parent: filepath.Join(parentDir, "parent.pid"),
			Child:  filepath.Join(parentDir, "child.pid"),
		},
		Wait: 1,
	}
	d := &Daemon{
		Config: cfg,
		Control: &Control{
			fifo:  make(chan Return),
			quit:  make(chan struct{}),
			state: make(chan error),
		},
		Forker: &myFork{},
		Logger: &LogWriter{
			logger: NewLogger(cfg),
		},
	}
	d.Run()
	sup := new(Sup)
	defer func() {
		d.process.Kill()
	}()
	for {
		select {
		case err := <-d.Control.state:
			if err == nil {
				t.Error("Expecting error: signal: Killed")
			}
			return
		case <-time.After(1 * time.Second):
			if pid, err := sup.ReadPidFile(filepath.Join(parentDir, "parent.pid")); err != nil {
				t.Error(err)
			} else {
				expect(t, os.Getpid(), pid)
			}
			if pid, err := sup.ReadPidFile(filepath.Join(parentDir, "child.pid")); err != nil {
				t.Error(err)
			} else {
				expect(t, d.process.Pid, pid)
			}
			expect(t, fmt.Sprintf("%s", d), fmt.Sprintf("%d", d.process.Pid))
			d.process.Kill()
			for d.process.Pid == 0 {
			}
			expect(t, 2, int(time.Since(d.start).Seconds()))
		}
	}
}
<commit_msg>	modified:   daemonrun_test.go<commit_after>package immortal

import (
	"fmt"
	"os"
	"path/filepath"
	"testing"
	"time"
)

func TestHelperProcess(t *testing.T) {
	if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" {
		return
	}
	time.Sleep(10 * time.Second)
}

func TestDaemonRun(t *testing.T) {
	base := filepath.Base(os.Args[0]) // "exec.test"
	dir := filepath.Dir(os.Args[0])   // "/tmp/go-buildNNNN/os/exec/_test"
	if dir == "." {
		t.Skip("skipping; running test at root somehow")
	}
	parentDir := filepath.Dir(dir) // "/tmp/go-buildNNNN/os/exec"
	dirBase := filepath.Base(dir)  // "_test"
	if dirBase == "." {
		t.Skipf("skipping; unexpected shallow dir of %q", dir)
	}

	cfg := &Config{
		Env:     map[string]string{"GO_WANT_HELPER_PROCESS": "1"},
		command: []string{filepath.Join(dirBase, base), "-test.run=TestHelperProcess"},
		Cwd:     parentDir,
		Pid: Pid{
			Parent: filepath.Join(parentDir, "parent.pid"),
			Child:  filepath.Join(parentDir, "child.pid"),
		},
		Wait: 1,
	}
	d := &Daemon{
		Config: cfg,
		Control: &Control{
			fifo:  make(chan Return),
			quit:  make(chan struct{}),
			state: make(chan error),
		},
		Forker: &myFork{},
		Logger: &LogWriter{
			logger: NewLogger(cfg),
		},
	}
	d.Run()
	sup := new(Sup)
	defer func() {
		d.process.Kill()
	}()
	for {
		select {
		case err := <-d.Control.state:
			if err == nil {
				t.Error("Expecting error: signal: Killed")
			}
			return
		case <-time.After(1 * time.Second):
			if pid, err := sup.ReadPidFile(filepath.Join(parentDir, "parent.pid")); err != nil {
				t.Error(err)
			} else {
				expect(t, os.Getpid(), pid)
			}
			if pid, err := sup.ReadPidFile(filepath.Join(parentDir, "child.pid")); err != nil {
				t.Error(err)
			} else {
				expect(t, d.process.Pid, pid)
			}
			expect(t, fmt.Sprintf("%s", d), fmt.Sprintf("%d", d.process.Pid))
			d.process.Kill()
			expect(t, 2, int(time.Since(d.start).Seconds()))
		}
	}
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"github.com/jyggen/pingu/pingu"
	"github.com/nlopes/slack"
	"github.com/spf13/viper"
	"regexp"
)

type plugin struct{}

var version string

func New(c *viper.Viper) pingu.Plugin {
	return pingu.Plugin(&plugin{})
}

func (pl *plugin) Author() pingu.Author {
	return pingu.Author{
		Email: "jonas@stendahl.me",
		Name:  "Jonas Stendahl",
	}
}

func (pl *plugin) Commands() pingu.Commands {
	return pingu.Commands{
		&pingu.Command{
			Description: "Lists all available commands.",
			Func: func(pi *pingu.Pingu, ev *slack.MessageEvent) {
				pi.Reply(ev, generateHelpOutput(pi))
			},
			Trigger: regexp.MustCompile("^!help$"),
		},
	}
}

func (pl *plugin) Name() string {
	return "Help"
}

func (pl *plugin) Tasks() pingu.Tasks {
	return pingu.Tasks{}
}

func (pl *plugin) Version() string {
	return version
}

func generateHelpOutput(pi *pingu.Pingu) string {
	output := "Here's a list of all available commands:\n\n```\n"

	for _, pl := range pi.Plugins() {
		output += fmt.Sprintf("%s (%s):\n", pl.Name(), pl.Version())

		for _, cmd := range pl.Commands() {
			trigger := cmd.Trigger.String()
			output += fmt.Sprintf("%s: %s\n", trigger[1:len(trigger)-1], cmd.Description)
		}

		output += "\n"
	}

	return output[:len(output)-1] + "```\n"
}
<commit_msg>Don't substring triggers<commit_after>package main

import (
	"fmt"
	"github.com/jyggen/pingu/pingu"
	"github.com/nlopes/slack"
	"github.com/spf13/viper"
	"regexp"
)

type plugin struct{}

var version string

func New(c *viper.Viper) pingu.Plugin {
	return pingu.Plugin(&plugin{})
}

func (pl *plugin) Author() pingu.Author {
	return pingu.Author{
		Email: "jonas@stendahl.me",
		Name:  "Jonas Stendahl",
	}
}

func (pl *plugin) Commands() pingu.Commands {
	return pingu.Commands{
		&pingu.Command{
			Description: "Lists all available commands.",
			Func: func(pi *pingu.Pingu, ev *slack.MessageEvent) {
				pi.Reply(ev, generateHelpOutput(pi))
			},
			Trigger: regexp.MustCompile("^!help$"),
		},
	}
}

func (pl *plugin) Name() string {
	return "Help"
}

func (pl *plugin) Tasks() pingu.Tasks {
	return pingu.Tasks{}
}

func (pl *plugin) Version() string {
	return version
}

func generateHelpOutput(pi *pingu.Pingu) string {
	output := "Here's a list of all available commands:\n\n```\n"

	for _, pl := range pi.Plugins() {
		output += fmt.Sprintf("%s (%s):\n", pl.Name(), pl.Version())

		for _, cmd := range pl.Commands() {
			trigger := cmd.Trigger.String()
			output += fmt.Sprintf("%s: %s\n", trigger, cmd.Description)
		}

		output += "\n"
	}

	return output[:len(output)-1] + "```\n"
}
<|endoftext|>


<commit_before>// Package json add some json-related commands to the command loop.
//
// The new commands are:
//
//   json : creates a json object out of key/value pairs or lists
//   jsonpath : parses a json object and extract specified fields
//   format : pretty-print specified json object
//
package json

import (
	"fmt"
	"regexp"
	"strconv"
	"strings"

	"github.com/gobs/args"
	"github.com/gobs/cmd"
	"github.com/gobs/cmd/internal"
	"github.com/gobs/jsonpath"
	"github.com/gobs/simplejson"
)

type jsonPlugin struct {
	cmd.Plugin
}

var (
	Plugin = &jsonPlugin{}

	reFieldValue = regexp.MustCompile(`(\w[\d\w-]*)(=(.*))?`) // field-name=value
)

func unquote(s string, q byte) (string, error) {
	l := len(s)
	if l == 1 {
		return s, fmt.Errorf("tooshort")
	}

	if s[l-1] == q {
		return s[1 : l-1], nil
	}

	return s, fmt.Errorf("unbalanced")
}

func parseValue(v string) (interface{}, error) {
	switch {
	case strings.HasPrefix(v, "{") || strings.HasPrefix(v, "["):
		j, err := simplejson.LoadString(v)
		if err != nil {
			return nil, fmt.Errorf("error parsing %q", v)
		} else {
			return j.Data(), nil
		}

	case strings.HasPrefix(v, `"`):
		return unquote(v, '"')

	case strings.HasPrefix(v, `'`):
		return unquote(v, '\'')

	case v == "":
		return v, nil

	case v == "true":
		return true, nil

	case v == "false":
		return false, nil

	case v == "null":
		return nil, nil

	default:
		if i, err := strconv.ParseInt(v, 10, 64); err == nil {
			return i, nil
		}
		if f, err := strconv.ParseFloat(v, 64); err == nil {
			return f, nil
		}

		return v, nil
	}
}

// Function PrintJson prints the specified object formatted as a JSON object
func PrintJson(v interface{}) {
	fmt.Println(simplejson.MustDumpString(v, simplejson.Indent("  ")))
}

// Function StringJson return the specified object as a JSON string
func StringJson(v interface{}, unq bool) (ret string) {
	ret = simplejson.MustDumpString(v)
	if unq {
		ret, _ = unquote(strings.TrimSpace(ret), '"')
	}

	return
}

//
// PluginInit initialize this plugin
//
func (p *jsonPlugin) PluginInit(commander *cmd.Cmd, _ *internal.Context) error {

	commander.Add(cmd.Command{"json",
		`
                json field1=value1 field2=value2...       // json object
                json {"name1":"value1", "name2":"value2"}
                json [value1 value2...]                   // json array
                json [value1, value2...]`,
		func(line string) (stop bool) {
			var res interface{}

			if strings.HasPrefix(line, "{") { // assume is already a JSON object

				if jbody, err := simplejson.LoadString(line); err != nil {
					err = fmt.Errorf("error parsing object %q", line)
					commander.SetVar("error", err, true)
					fmt.Println(err)
					return
				} else {
					res = jbody.Data()
				}
			} else if strings.HasPrefix(line, "[") { // could be a JSON array

				if jbody, err := simplejson.LoadString(line); err == nil {
					res = jbody.Data()
				} else { // try a sequence of values (that need to be parsed)
					line = strings.TrimPrefix(line, "[")
					line = strings.TrimSuffix(line, "]")
					line = strings.TrimSpace(line)

					var ares []interface{}

					for _, f := range args.GetArgs(line) {
						v, err := parseValue(f)
						if err != nil {
							fmt.Println(err)
							commander.SetVar("error", err, true)
							return
						}

						ares = append(ares, v)
					}

					res = ares
				}
			} else { // a sequence of name=value pairs
				var err error
				mres := map[string]interface{}{}

				for _, f := range args.GetArgs(line, args.InfieldBrackets()) {
					matches := reFieldValue.FindStringSubmatch(f)
					if len(matches) > 0 { // [field=value field =value value]
						name, value := matches[1], matches[3]
						mres[name], err = parseValue(value)

						if err != nil {
							fmt.Println(err)
							commander.SetVar("error", err, true)
							return
						}
					} else {
						fmt.Println("invalid name=value pair:", f)
						commander.SetVar("error", "invalid name=value pair", true)
						return
					}
				}

				res = mres
			}

			if commander.GetBoolVar("print") {
				PrintJson(res)
			}

			commander.SetVar("error", "", true)
			commander.SetVar("json", StringJson(res, true), true)
			return
		},
		nil})

	commander.Add(cmd.Command{
		"jsonpath",
		`jsonpath [-e] [-c] path {json}`,
		func(line string) (stop bool) {
			var joptions jsonpath.ProcessOptions

			options, line := args.GetOptions(line)
			for _, o := range options {
				if o == "-e" || o == "--enhanced" {
					joptions |= jsonpath.Enhanced
				} else if o == "-c" || o == "--collapse" {
					joptions |= jsonpath.Collapse
				} else {
					line = "" // to force an error
					break
				}
			}

			parts := args.GetArgsN(line, 2)
			if len(parts) != 2 {
				fmt.Println("use: jsonpath [-e|--enhanced] path {json}")
				commander.SetVar("error", "invalid-usage", true)
				return
			}

			path := parts[0]
			if !(strings.HasPrefix(path, "$.") || strings.HasPrefix(path, "$[")) {
				path = "$." + path
			}

			jbody, err := simplejson.LoadString(parts[1])
			if err != nil {
				fmt.Println("json:", err)
				commander.SetVar("error", err, true)
				return
			}

			jp := jsonpath.NewProcessor()
			if !jp.Parse(path) {
				commander.SetVar("error", fmt.Sprintf("failed to parse %q", path), true)
				return // syntax error
			}

			res := jp.Process(jbody, joptions)
			if commander.GetBoolVar("print") {
				PrintJson(res)
			}
			commander.SetVar("error", "", true)
			commander.SetVar("json", StringJson(res, true), true)
			return
		},
		nil})

	commander.Add(cmd.Command{
		"format",
		`format object`,
		func(line string) (stop bool) {
			jbody, err := simplejson.LoadString(line)
			if err != nil {
				fmt.Println("format:", err)
				fmt.Println("input:", line)
				commander.SetVar("error", err, true)
				return
			}

			PrintJson(jbody.Data())
			return
		},
		nil})

	return nil
}
<commit_msg>add backquotes for raw strings<commit_after>// Package json add some json-related commands to the command loop.
//
// The new commands are:
//
//   json : creates a json object out of key/value pairs or lists
//   jsonpath : parses a json object and extract specified fields
//   format : pretty-print specified json object
//
package json

import (
	"fmt"
	"regexp"
	"strconv"
	"strings"

	"github.com/gobs/args"
	"github.com/gobs/cmd"
	"github.com/gobs/cmd/internal"
	"github.com/gobs/jsonpath"
	"github.com/gobs/simplejson"
)

type jsonPlugin struct {
	cmd.Plugin
}

var (
	Plugin = &jsonPlugin{}

	reFieldValue = regexp.MustCompile(`(\w[\d\w-]*)(=(.*))?`) // field-name=value
)

func unquote(s string, q byte) (string, error) {
	l := len(s)
	if l == 1 {
		return s, fmt.Errorf("tooshort")
	}

	if s[l-1] == q {
		return s[1 : l-1], nil
	}

	return s, fmt.Errorf("unbalanced")
}

func parseValue(v string) (interface{}, error) {
	switch {
	case strings.HasPrefix(v, "{") || strings.HasPrefix(v, "["):
		j, err := simplejson.LoadString(v)
		if err != nil {
			return nil, fmt.Errorf("error parsing %q", v)
		} else {
			return j.Data(), nil
		}

	case strings.HasPrefix(v, `"`):
		return unquote(v, '"')

	case strings.HasPrefix(v, `'`):
		return unquote(v, '\'')

	case strings.HasPrefix(v, "`"):
		return unquote(v, '`')

	case v == "":
		return v, nil

	case v == "true":
		return true, nil

	case v == "false":
		return false, nil

	case v == "null":
		return nil, nil

	default:
		if i, err := strconv.ParseInt(v, 10, 64); err == nil {
			return i, nil
		}
		if f, err := strconv.ParseFloat(v, 64); err == nil {
			return f, nil
		}

		return v, nil
	}
}

// Function PrintJson prints the specified object formatted as a JSON object
func PrintJson(v interface{}) {
	fmt.Println(simplejson.MustDumpString(v, simplejson.Indent("  ")))
}

// Function StringJson return the specified object as a JSON string
func StringJson(v interface{}, unq bool) (ret string) {
	ret = simplejson.MustDumpString(v)
	if unq {
		ret, _ = unquote(strings.TrimSpace(ret), '"')
	}

	return
}

//
// PluginInit initialize this plugin
//
func (p *jsonPlugin) PluginInit(commander *cmd.Cmd, _ *internal.Context) error {

	commander.Add(cmd.Command{"json",
		`
                json field1=value1 field2=value2...       // json object
                json {"name1":"value1", "name2":"value2"}
                json [value1 value2...]                   // json array
                json [value1, value2...]`,
		func(line string) (stop bool) {
			var res interface{}

			if strings.HasPrefix(line, "{") { // assume is already a JSON object

				if jbody, err := simplejson.LoadString(line); err != nil {
					err = fmt.Errorf("error parsing object %q", line)
					commander.SetVar("error", err, true)
					fmt.Println(err)
					return
				} else {
					res = jbody.Data()
				}
			} else if strings.HasPrefix(line, "[") { // could be a JSON array

				if jbody, err := simplejson.LoadString(line); err == nil {
					res = jbody.Data()
				} else { // try a sequence of values (that need to be parsed)
					line = strings.TrimPrefix(line, "[")
					line = strings.TrimSuffix(line, "]")
					line = strings.TrimSpace(line)

					var ares []interface{}

					for _, f := range args.GetArgs(line) {
						v, err := parseValue(f)
						if err != nil {
							fmt.Println(err)
							commander.SetVar("error", err, true)
							return
						}

						ares = append(ares, v)
					}

					res = ares
				}
			} else { // a sequence of name=value pairs
				var err error
				mres := map[string]interface{}{}

				for _, f := range args.GetArgs(line, args.InfieldBrackets()) {
					matches := reFieldValue.FindStringSubmatch(f)
					if len(matches) > 0 { // [field=value field =value value]
						name, value := matches[1], matches[3]
						mres[name], err = parseValue(value)

						if err != nil {
							fmt.Println(err)
							commander.SetVar("error", err, true)
							return
						}
					} else {
						fmt.Println("invalid name=value pair:", f)
						commander.SetVar("error", "invalid name=value pair", true)
						return
					}
				}

				res = mres
			}

			if commander.GetBoolVar("print") {
				PrintJson(res)
			}

			commander.SetVar("error", "", true)
			commander.SetVar("json", StringJson(res, true), true)
			return
		},
		nil})

	commander.Add(cmd.Command{
		"jsonpath",
		`jsonpath [-e] [-c] path {json}`,
		func(line string) (stop bool) {
			var joptions jsonpath.ProcessOptions

			options, line := args.GetOptions(line)
			for _, o := range options {
				if o == "-e" || o == "--enhanced" {
					joptions |= jsonpath.Enhanced
				} else if o == "-c" || o == "--collapse" {
					joptions |= jsonpath.Collapse
				} else {
					line = "" // to force an error
					break
				}
			}

			parts := args.GetArgsN(line, 2)
			if len(parts) != 2 {
				fmt.Println("use: jsonpath [-e|--enhanced] path {json}")
				commander.SetVar("error", "invalid-usage", true)
				return
			}

			path := parts[0]
			if !(strings.HasPrefix(path, "$.") || strings.HasPrefix(path, "$[")) {
				path = "$." + path
			}

			jbody, err := simplejson.LoadString(parts[1])
			if err != nil {
				fmt.Println("json:", err)
				commander.SetVar("error", err, true)
				return
			}

			jp := jsonpath.NewProcessor()
			if !jp.Parse(path) {
				commander.SetVar("error", fmt.Sprintf("failed to parse %q", path), true)
				return // syntax error
			}

			res := jp.Process(jbody, joptions)
			if commander.GetBoolVar("print") {
				PrintJson(res)
			}
			commander.SetVar("error", "", true)
			commander.SetVar("json", StringJson(res, true), true)
			return
		},
		nil})

	commander.Add(cmd.Command{
		"format",
		`format object`,
		func(line string) (stop bool) {
			jbody, err := simplejson.LoadString(line)
			if err != nil {
				fmt.Println("format:", err)
				fmt.Println("input:", line)
				commander.SetVar("error", err, true)
				return
			}

			PrintJson(jbody.Data())
			return
		},
		nil})

	return nil
}
<|endoftext|>


<commit_before>// Package ping implements a plugin to ping a host or IP using system ping.
// It is made for ping from iputils (options and output parsing).
package ping

import (
	"errors"
	"fmt"
	bot "github.com/StalkR/goircbot"
	"os/exec"
	"regexp"
	"strings"
)

// Ping runs ping against given host and returns its output.
func Ping(host string) (string, error) {
	matched, err := regexp.Match("^[\\w._-]+$", []byte(host))
	if err != nil {
		return "", err
	}
	if !matched {
		return "", errors.New("invalid host/IP")
	}
	// -c: packet count, -w: timeout in seconds
	out, err := exec.Command("ping", "-c", "1", "-w", "3", "--", host).Output()
	if err != nil {
		if fmt.Sprintf("%s", err) == "exit status 2" {
			return "", errors.New("unknown host")
		}
		return "", err
	}
	r, err := regexp.Compile("\\d+ bytes from .*")
	if err != nil {
		return "", err
	}
	line := r.Find(out)
	if line == nil {
		return "", errors.New("timeout")
	}
	return string(line), nil
}

func PingHandler(b *bot.Bot, e *bot.Event) {
	arg := strings.TrimSpace(e.Args)
	if len(arg) == 0 {
		return
	}
	s, err := Ping(arg)
	if err != nil {
		b.Conn.Privmsg(e.Target, fmt.Sprintf("error: %s", err))
		return
	}
	b.Conn.Privmsg(e.Target, s)
}

// Register registers the plugin with a bot.
func Register(b *bot.Bot) {
	b.AddCommand("ping", bot.Command{
		Help:    "ping a host/IP",
		Handler: PingHandler,
		Pub:     true,
		Priv:    true,
		Hidden:  false})
}
<commit_msg>ping: support timeout exit code<commit_after>// Package ping implements a plugin to ping a host or IP using system ping.
// It is made for ping from iputils (options and output parsing).
package ping

import (
	"errors"
	"fmt"
	bot "github.com/StalkR/goircbot"
	"os/exec"
	"regexp"
	"strings"
)

// Ping runs ping against given host and returns its output.
func Ping(host string) (string, error) {
	matched, err := regexp.Match("^[\\w._-]+$", []byte(host))
	if err != nil {
		return "", err
	}
	if !matched {
		return "", errors.New("invalid host/IP")
	}
	// -c: packet count, -w: timeout in seconds
	out, err := exec.Command("ping", "-c", "1", "-w", "3", "--", host).Output()
	if err != nil {
		errs := fmt.Sprintf("%s", err)
		if errs == "exit status 1" {
			return "", errors.New("timeout")
		}
		if errs == "exit status 2" {
			return "", errors.New("unknown host")
		}
		return "", err
	}
	r, err := regexp.Compile("\\d+ bytes from .*")
	if err != nil {
		return "", err
	}
	line := r.Find(out)
	if line == nil {
		return "", errors.New("cannot parse ping output")
	}
	return string(line), nil
}

func PingHandler(b *bot.Bot, e *bot.Event) {
	arg := strings.TrimSpace(e.Args)
	if len(arg) == 0 {
		return
	}
	s, err := Ping(arg)
	if err != nil {
		b.Conn.Privmsg(e.Target, fmt.Sprintf("error: %s", err))
		return
	}
	b.Conn.Privmsg(e.Target, s)
}

// Register registers the plugin with a bot.
func Register(b *bot.Bot) {
	b.AddCommand("ping", bot.Command{
		Help:    "ping a host/IP",
		Handler: PingHandler,
		Pub:     true,
		Priv:    true,
		Hidden:  false})
}
<|endoftext|>


<commit_before>package main

import (
	"log"
	"strconv"

	"gopkg.in/jcelliott/turnpike.v2"
)

const (
	POLONIEX_WEBSOCKET_ADDRESS  = "wss://api.poloniex.com"
	POLONIEX_WEBSOCKET_REALM    = "realm1"
	POLONIEX_WEBSOCKET_TICKER   = "ticker"
	POLONIEX_WEBSOCKET_TROLLBOX = "trollbox"
)

type PoloniexWebsocketTicker struct {
	CurrencyPair  string
	Last          float64
	LowestAsk     float64
	HighestBid    float64
	PercentChange float64
	BaseVolume    float64
	QuoteVolume   float64
	IsFrozen      bool
	High          float64
	Low           float64
}

func PoloniexOnTicker(args []interface{}, kwargs map[string]interface{}) {
	ticker := PoloniexWebsocketTicker{}
	ticker.CurrencyPair = args[0].(string)
	ticker.Last, _ = strconv.ParseFloat(args[1].(string), 64)
	ticker.LowestAsk, _ = strconv.ParseFloat(args[2].(string), 64)
	ticker.HighestBid, _ = strconv.ParseFloat(args[3].(string), 64)
	ticker.PercentChange, _ = strconv.ParseFloat(args[4].(string), 64)
	ticker.BaseVolume, _ = strconv.ParseFloat(args[5].(string), 64)
	ticker.QuoteVolume, _ = strconv.ParseFloat(args[6].(string), 64)

	if args[7].(float64) != 0 {
		ticker.IsFrozen = true
	} else {
		ticker.IsFrozen = false
	}

	ticker.High, _ = strconv.ParseFloat(args[8].(string), 64)
	ticker.Low, _ = strconv.ParseFloat(args[9].(string), 64)
}

type PoloniexWebsocketTrollboxMessage struct {
	MessageNumber float64
	Username      string
	Message       string
	Reputation    float64
}

func PoloniexOnTrollbox(args []interface{}, kwargs map[string]interface{}) {
	message := PoloniexWebsocketTrollboxMessage{}
	message.MessageNumber, _ = args[1].(float64)
	message.Username = args[2].(string)
	message.Message = args[3].(string)
	message.Reputation = args[4].(float64)
}

func PoloniexOnDepthOrTrade(args []interface{}, kwargs map[string]interface{}) {
	for x := range args {
		data := args[x].(map[string]interface{})
		msgData := data["data"].(map[string]interface{})
		msgType := data["type"].(string)

		switch msgType {
		case "orderBookModify":
			{
				type PoloniexWebsocketOrderbookModify struct {
					Type   string
					Rate   float64
					Amount float64
				}

				orderModify := PoloniexWebsocketOrderbookModify{}
				orderModify.Type = msgData["type"].(string)

				rateStr := msgData["rate"].(string)
				orderModify.Rate, _ = strconv.ParseFloat(rateStr, 64)

				amountStr := msgData["amount"].(string)
				orderModify.Amount, _ = strconv.ParseFloat(amountStr, 64)
			}
		case "orderBookRemove":
			{
				type PoloniexWebsocketOrderbookRemove struct {
					Type string
					Rate float64
				}

				orderRemoval := PoloniexWebsocketOrderbookRemove{}
				orderRemoval.Type = msgData["type"].(string)

				rateStr := msgData["rate"].(string)
				orderRemoval.Rate, _ = strconv.ParseFloat(rateStr, 64)
			}
		case "newTrade":
			{
				type PoloniexWebsocketNewTrade struct {
					Type    string
					TradeID int64
					Rate    float64
					Amount  float64
					Date    string
					Total   float64
				}

				trade := PoloniexWebsocketNewTrade{}
				trade.Type = msgData["type"].(string)

				tradeIDstr := msgData["tradeID"].(string)
				trade.TradeID, _ = strconv.ParseInt(tradeIDstr, 10, 64)

				rateStr := msgData["rate"].(string)
				trade.Rate, _ = strconv.ParseFloat(rateStr, 64)

				amountStr := msgData["amount"].(string)
				trade.Amount, _ = strconv.ParseFloat(amountStr, 64)

				totalStr := msgData["total"].(string)
				trade.Rate, _ = strconv.ParseFloat(totalStr, 64)

				trade.Date = msgData["date"].(string)
			}
		}
	}
}

func (p *Poloniex) WebsocketClient() {
	for p.Enabled && p.Websocket {
		c, err := turnpike.NewWebsocketClient(turnpike.JSON, POLONIEX_WEBSOCKET_ADDRESS)
		if err != nil {
			log.Printf("%s Unable to connect to Websocket. Error: %s\n", p.GetName(), err)
			continue
		}

		if p.Verbose {
			log.Printf("%s Connected to Websocket.\n", p.GetName())
		}

		_, err = c.JoinRealm(POLONIEX_WEBSOCKET_REALM, nil)
		if err != nil {
			log.Printf("%s Unable to join realm. Error: %s\n", p.GetName(), err)
			continue
		}

		if p.Verbose {
			log.Printf("%s Joined Websocket realm.\n", p.GetName())
		}

		c.ReceiveDone = make(chan bool)

		if err := c.Subscribe(POLONIEX_WEBSOCKET_TICKER, PoloniexOnTicker); err != nil {
			log.Printf("%s Error subscribing to ticker channel: %s\n", p.GetName(), err)
		}

		if err := c.Subscribe(POLONIEX_WEBSOCKET_TROLLBOX, PoloniexOnTrollbox); err != nil {
			log.Printf("%s Error subscribing to trollbox channel: %s\n", p.GetName(), err)
		}

		for x := range p.EnabledPairs {
			currency := p.EnabledPairs[x]
			if err := c.Subscribe(currency, PoloniexOnDepthOrTrade); err != nil {
				log.Printf("%s Error subscribing to %s channel: %s\n", p.GetName(), currency, err)
			}
		}

		if p.Verbose {
			log.Printf("%s Subscribed to websocket channels.\n", p.GetName())
		}

		<-c.ReceiveDone
		log.Printf("%s Websocket client disconnected.\n", p.GetName())
	}
}
<commit_msg>Revert "Removes extra argument on poloniex method"<commit_after>package main

import (
	"log"
	"strconv"

	"gopkg.in/jcelliott/turnpike.v2"
)

const (
	POLONIEX_WEBSOCKET_ADDRESS  = "wss://api.poloniex.com"
	POLONIEX_WEBSOCKET_REALM    = "realm1"
	POLONIEX_WEBSOCKET_TICKER   = "ticker"
	POLONIEX_WEBSOCKET_TROLLBOX = "trollbox"
)

type PoloniexWebsocketTicker struct {
	CurrencyPair  string
	Last          float64
	LowestAsk     float64
	HighestBid    float64
	PercentChange float64
	BaseVolume    float64
	QuoteVolume   float64
	IsFrozen      bool
	High          float64
	Low           float64
}

func PoloniexOnTicker(args []interface{}, kwargs map[string]interface{}) {
	ticker := PoloniexWebsocketTicker{}
	ticker.CurrencyPair = args[0].(string)
	ticker.Last, _ = strconv.ParseFloat(args[1].(string), 64)
	ticker.LowestAsk, _ = strconv.ParseFloat(args[2].(string), 64)
	ticker.HighestBid, _ = strconv.ParseFloat(args[3].(string), 64)
	ticker.PercentChange, _ = strconv.ParseFloat(args[4].(string), 64)
	ticker.BaseVolume, _ = strconv.ParseFloat(args[5].(string), 64)
	ticker.QuoteVolume, _ = strconv.ParseFloat(args[6].(string), 64)

	if args[7].(float64) != 0 {
		ticker.IsFrozen = true
	} else {
		ticker.IsFrozen = false
	}

	ticker.High, _ = strconv.ParseFloat(args[8].(string), 64)
	ticker.Low, _ = strconv.ParseFloat(args[9].(string), 64)
}

type PoloniexWebsocketTrollboxMessage struct {
	MessageNumber float64
	Username      string
	Message       string
	Reputation    float64
}

func PoloniexOnTrollbox(args []interface{}, kwargs map[string]interface{}) {
	message := PoloniexWebsocketTrollboxMessage{}
	message.MessageNumber, _ = args[1].(float64)
	message.Username = args[2].(string)
	message.Message = args[3].(string)
	message.Reputation = args[4].(float64)
}

func PoloniexOnDepthOrTrade(args []interface{}, kwargs map[string]interface{}) {
	for x := range args {
		data := args[x].(map[string]interface{})
		msgData := data["data"].(map[string]interface{})
		msgType := data["type"].(string)

		switch msgType {
		case "orderBookModify":
			{
				type PoloniexWebsocketOrderbookModify struct {
					Type   string
					Rate   float64
					Amount float64
				}

				orderModify := PoloniexWebsocketOrderbookModify{}
				orderModify.Type = msgData["type"].(string)

				rateStr := msgData["rate"].(string)
				orderModify.Rate, _ = strconv.ParseFloat(rateStr, 64)

				amountStr := msgData["amount"].(string)
				orderModify.Amount, _ = strconv.ParseFloat(amountStr, 64)
			}
		case "orderBookRemove":
			{
				type PoloniexWebsocketOrderbookRemove struct {
					Type string
					Rate float64
				}

				orderRemoval := PoloniexWebsocketOrderbookRemove{}
				orderRemoval.Type = msgData["type"].(string)

				rateStr := msgData["rate"].(string)
				orderRemoval.Rate, _ = strconv.ParseFloat(rateStr, 64)
			}
		case "newTrade":
			{
				type PoloniexWebsocketNewTrade struct {
					Type    string
					TradeID int64
					Rate    float64
					Amount  float64
					Date    string
					Total   float64
				}

				trade := PoloniexWebsocketNewTrade{}
				trade.Type = msgData["type"].(string)

				tradeIDstr := msgData["tradeID"].(string)
				trade.TradeID, _ = strconv.ParseInt(tradeIDstr, 10, 64)

				rateStr := msgData["rate"].(string)
				trade.Rate, _ = strconv.ParseFloat(rateStr, 64)

				amountStr := msgData["amount"].(string)
				trade.Amount, _ = strconv.ParseFloat(amountStr, 64)

				totalStr := msgData["total"].(string)
				trade.Rate, _ = strconv.ParseFloat(totalStr, 64)

				trade.Date = msgData["date"].(string)
			}
		}
	}
}

func (p *Poloniex) WebsocketClient() {
	for p.Enabled && p.Websocket {
		c, err := turnpike.NewWebsocketClient(turnpike.JSON, POLONIEX_WEBSOCKET_ADDRESS, nil)
		if err != nil {
			log.Printf("%s Unable to connect to Websocket. Error: %s\n", p.GetName(), err)
			continue
		}

		if p.Verbose {
			log.Printf("%s Connected to Websocket.\n", p.GetName())
		}

		_, err = c.JoinRealm(POLONIEX_WEBSOCKET_REALM, nil)
		if err != nil {
			log.Printf("%s Unable to join realm. Error: %s\n", p.GetName(), err)
			continue
		}

		if p.Verbose {
			log.Printf("%s Joined Websocket realm.\n", p.GetName())
		}

		c.ReceiveDone = make(chan bool)

		if err := c.Subscribe(POLONIEX_WEBSOCKET_TICKER, PoloniexOnTicker); err != nil {
			log.Printf("%s Error subscribing to ticker channel: %s\n", p.GetName(), err)
		}

		if err := c.Subscribe(POLONIEX_WEBSOCKET_TROLLBOX, PoloniexOnTrollbox); err != nil {
			log.Printf("%s Error subscribing to trollbox channel: %s\n", p.GetName(), err)
		}

		for x := range p.EnabledPairs {
			currency := p.EnabledPairs[x]
			if err := c.Subscribe(currency, PoloniexOnDepthOrTrade); err != nil {
				log.Printf("%s Error subscribing to %s channel: %s\n", p.GetName(), currency, err)
			}
		}

		if p.Verbose {
			log.Printf("%s Subscribed to websocket channels.\n", p.GetName())
		}

		<-c.ReceiveDone
		log.Printf("%s Websocket client disconnected.\n", p.GetName())
	}
}
<|endoftext|>


<commit_before>package polyline

import (
	"math"
)

func round(x float64) float64 {
	if x < 0 {
		return -math.Floor(-x + 0.5)
	} else {
		return math.Floor(x + 0.5)
	}
}

func EncodeUint(u uint, result []byte) []byte {
	for u > 32 {
		result = append(result, byte((u&31)+95))
		u = u >> 5
	}
	result = append(result, byte(u+63))
	return result
}

func EncodeInt(i int, result []byte) []byte {
	var u uint
	if i < 0 {
		u = uint(^(i << 1))
	} else {
		u = uint(i << 1)
	}
	return EncodeUint(u, result)
}

func EncodeFloat64(f float64, result []byte) []byte {
	return EncodeInt(int(round(1e5*f)), result)
}

func EncodeCoords(coords [][]float64, result []byte) []byte {
	lastLat, lastLong := 0, 0
	for _, coord := range coords {
		lat, long := int(1e5*coord[0]), int(1e5*coord[1])
		result = EncodeInt(lat-lastLat, result)
		result = EncodeInt(long-lastLong, result)
		lastLat, lastLong = lat, long
	}
	return result
}
<commit_msg>Don't encode zeros<commit_after>package polyline

import (
	"math"
)

func round(x float64) float64 {
	if x < 0 {
		return -math.Floor(-x + 0.5)
	} else {
		return math.Floor(x + 0.5)
	}
}

func EncodeUint(u uint, result []byte) []byte {
	for u > 32 {
		result = append(result, byte((u&31)+95))
		u = u >> 5
	}
	result = append(result, byte(u+63))
	return result
}

func EncodeInt(i int, result []byte) []byte {
	var u uint
	if i < 0 {
		u = uint(^(i << 1))
	} else {
		u = uint(i << 1)
	}
	return EncodeUint(u, result)
}

func EncodeFloat64(f float64, result []byte) []byte {
	return EncodeInt(int(round(1e5*f)), result)
}

func EncodeCoords(coords [][]float64, result []byte) []byte {
	lastLat, lastLong := 0, 0
	for _, coord := range coords {
		lat, long := int(1e5*coord[0]), int(1e5*coord[1])
		if lat != lastLat && long != lastLong {
			result = EncodeInt(lat-lastLat, result)
			result = EncodeInt(long-lastLong, result)
			lastLat, lastLong = lat, long
		}
	}
	return result
}
<|endoftext|>