<commit_before>package aws

import (
	"fmt"
	"log"
	"regexp"
	"testing"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/transfer"

	"github.com/hashicorp/terraform/helper/acctest"
	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/terraform"
)

func TestAccAWSTransferServer_basic(t *testing.T) {
	var conf transfer.DescribedServer
	rName := acctest.RandString(5)

	resource.ParallelTest(t, resource.TestCase{
		PreCheck:      func() { testAccPreCheck(t) },
		IDRefreshName: "aws_transfer_server.foo",
		Providers:     testAccProviders,
		CheckDestroy:  testAccCheckAWSTransferServerDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccAWSTransferServerConfig_basic,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAWSTransferServerExists("aws_transfer_server.foo", &conf),
					testAccMatchResourceAttrRegionalARN("aws_transfer_server.foo", "arn", "transfer", regexp.MustCompile(`server/.+`)),
					resource.TestCheckResourceAttrSet(
						"aws_transfer_server.foo", "endpoint"),
					resource.TestCheckResourceAttr(
						"aws_transfer_server.foo", "identity_provider_type", "SERVICE_MANAGED"),
					resource.TestCheckResourceAttr(
						"aws_transfer_server.foo", "tags.%", "1"),
					resource.TestCheckResourceAttr(
						"aws_transfer_server.foo", "tags.NAME", "tf-acc-test-transfer-server"),
				),
			},
			{
				ResourceName:      "aws_transfer_server.foo",
				ImportState:       true,
				ImportStateVerify: true,
			},
			{
				Config: testAccAWSTransferServerConfig_basicUpdate(rName),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAWSTransferServerExists("aws_transfer_server.foo", &conf),
					resource.TestCheckResourceAttr(
						"aws_transfer_server.foo", "tags.%", "2"),
					resource.TestCheckResourceAttr(
						"aws_transfer_server.foo", "tags.NAME", "tf-acc-test-transfer-server"),
					resource.TestCheckResourceAttr(
						"aws_transfer_server.foo", "tags.ENV", "test"),
					resource.TestCheckResourceAttrSet(
						"aws_transfer_server.foo", "logging_role"),
				),
			},
		},
	})
}

func testAccCheckAWSTransferServerExists(n string, res *transfer.DescribedServer) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		rs, ok := s.RootModule().Resources[n]
		if !ok {
			return fmt.Errorf("Not found: %s", n)
		}

		if rs.Primary.ID == "" {
			return fmt.Errorf("No Transfer Server ID is set")
		}

		conn := testAccProvider.Meta().(*AWSClient).transferconn

		describe, err := conn.DescribeServer(&transfer.DescribeServerInput{
			ServerId: aws.String(rs.Primary.ID),
		})

		if err != nil {
			return err
		}

		*res = *describe.Server

		return nil
	}
}

		}

		return nil
	}
}

func testAccCheckAWSTransferServerDestroy(s *terraform.State) error {
	conn := testAccProvider.Meta().(*AWSClient).transferconn

	for _, rs := range s.RootModule().Resources {
		if rs.Type != "aws_transfer_server" {
			continue
		}

		_, err := conn.DescribeServer(&transfer.DescribeServerInput{
			ServerId: aws.String(rs.Primary.ID),
		})

		if isAWSErr(err, transfer.ErrCodeResourceNotFoundException, "") {
			continue
		}

		if err != nil {
			return err
		}
	}

	return nil
}

const testAccAWSTransferServerConfig_basic = `
resource "aws_transfer_server" "foo" {
  identity_provider_type = "SERVICE_MANAGED"

  tags {
	NAME     = "tf-acc-test-transfer-server"
  }
}
`

func testAccAWSTransferServerConfig_basicUpdate(rName string) string {

	return fmt.Sprintf(`

resource "aws_iam_role" "foo" {
	name = "tf-test-transfer-server-iam-role-%s"

	assume_role_policy = <<EOF
{
	"Version": "2012-10-17",
	"Statement": [
		{
		"Effect": "Allow",
		"Principal": {
			"Service": "transfer.amazonaws.com"
		},
		"Action": "sts:AssumeRole"
		}
	]
}
EOF
}

resource "aws_iam_role_policy" "foo" {
	name = "tf-test-transfer-server-iam-policy-%s"
	role = "${aws_iam_role.foo.id}"
	policy = <<POLICY
{
	"Version": "2012-10-17",
	"Statement": [
		{
		"Sid": "AllowFullAccesstoCloudWatchLogs",
		"Effect": "Allow",
		"Action": [
			"logs:*"
		],
		"Resource": "*"
		}
	]
}
POLICY
}

resource "aws_transfer_server" "foo" {
  identity_provider_type = "SERVICE_MANAGED"
  logging_role = "${aws_iam_role.foo.arn}"

  tags {
	NAME   = "tf-acc-test-transfer-server"
	ENV    = "test"
  }
}
`, rName, rName)
}
<commit_msg>Add transfer server test with apigateway<commit_after>package aws

import (
	"fmt"
	"log"
	"regexp"
	"testing"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/transfer"

	"github.com/hashicorp/terraform/helper/acctest"
	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/terraform"
)

func TestAccAWSTransferServer_basic(t *testing.T) {
	var conf transfer.DescribedServer
	rName := acctest.RandString(5)

	resource.ParallelTest(t, resource.TestCase{
		PreCheck:      func() { testAccPreCheck(t) },
		IDRefreshName: "aws_transfer_server.foo",
		Providers:     testAccProviders,
		CheckDestroy:  testAccCheckAWSTransferServerDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccAWSTransferServerConfig_basic,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAWSTransferServerExists("aws_transfer_server.foo", &conf),
					testAccMatchResourceAttrRegionalARN("aws_transfer_server.foo", "arn", "transfer", regexp.MustCompile(`server/.+`)),
					resource.TestCheckResourceAttrSet(
						"aws_transfer_server.foo", "endpoint"),
					resource.TestCheckResourceAttr(
						"aws_transfer_server.foo", "identity_provider_type", "SERVICE_MANAGED"),
					resource.TestCheckResourceAttr(
						"aws_transfer_server.foo", "tags.%", "1"),
					resource.TestCheckResourceAttr(
						"aws_transfer_server.foo", "tags.NAME", "tf-acc-test-transfer-server"),
				),
			},
			{
				ResourceName:      "aws_transfer_server.foo",
				ImportState:       true,
				ImportStateVerify: true,
			},
			{
				Config: testAccAWSTransferServerConfig_basicUpdate(rName),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAWSTransferServerExists("aws_transfer_server.foo", &conf),
					resource.TestCheckResourceAttr(
						"aws_transfer_server.foo", "tags.%", "2"),
					resource.TestCheckResourceAttr(
						"aws_transfer_server.foo", "tags.NAME", "tf-acc-test-transfer-server"),
					resource.TestCheckResourceAttr(
						"aws_transfer_server.foo", "tags.ENV", "test"),
					resource.TestCheckResourceAttrSet(
						"aws_transfer_server.foo", "logging_role"),
				),
			},
		},
	})
}

func TestAccAWSTransferServer_apigateway(t *testing.T) {
	var conf transfer.DescribedServer
	rName := acctest.RandString(5)

	resource.ParallelTest(t, resource.TestCase{
		PreCheck:      func() { testAccPreCheck(t) },
		IDRefreshName: "aws_transfer_server.foo",
		Providers:     testAccProviders,
		CheckDestroy:  testAccCheckAWSTransferServerDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccAWSTransferServerConfig_apigateway(rName),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAWSTransferServerExists("aws_transfer_server.foo", &conf),
					resource.TestCheckResourceAttr(
						"aws_transfer_server.foo", "identity_provider_type", "API_GATEWAY"),
					resource.TestCheckResourceAttrSet(
						"aws_transfer_server.foo", "invocation_role"),
					resource.TestCheckResourceAttr(
						"aws_transfer_server.foo", "tags.%", "2"),
					resource.TestCheckResourceAttr(
						"aws_transfer_server.foo", "tags.NAME", "tf-acc-test-transfer-server"),
					resource.TestCheckResourceAttr(
						"aws_transfer_server.foo", "tags.TYPE", "apigateway"),
				),
			},
		},
	})
}

func testAccCheckAWSTransferServerExists(n string, res *transfer.DescribedServer) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		rs, ok := s.RootModule().Resources[n]
		if !ok {
			return fmt.Errorf("Not found: %s", n)
		}

		if rs.Primary.ID == "" {
			return fmt.Errorf("No Transfer Server ID is set")
		}

		conn := testAccProvider.Meta().(*AWSClient).transferconn

		describe, err := conn.DescribeServer(&transfer.DescribeServerInput{
			ServerId: aws.String(rs.Primary.ID),
		})

		if err != nil {
			return err
		}

		*res = *describe.Server

		return nil
	}
}

		}

		return nil
	}
}

func testAccCheckAWSTransferServerDestroy(s *terraform.State) error {
	conn := testAccProvider.Meta().(*AWSClient).transferconn

	for _, rs := range s.RootModule().Resources {
		if rs.Type != "aws_transfer_server" {
			continue
		}

		_, err := conn.DescribeServer(&transfer.DescribeServerInput{
			ServerId: aws.String(rs.Primary.ID),
		})

		if isAWSErr(err, transfer.ErrCodeResourceNotFoundException, "") {
			continue
		}

		if err != nil {
			return err
		}
	}

	return nil
}

const testAccAWSTransferServerConfig_basic = `
resource "aws_transfer_server" "foo" {
  identity_provider_type = "SERVICE_MANAGED"

  tags {
	NAME     = "tf-acc-test-transfer-server"
  }
}
`

func testAccAWSTransferServerConfig_basicUpdate(rName string) string {

	return fmt.Sprintf(`

resource "aws_iam_role" "foo" {
	name = "tf-test-transfer-server-iam-role-%s"

	assume_role_policy = <<EOF
{
	"Version": "2012-10-17",
	"Statement": [
		{
		"Effect": "Allow",
		"Principal": {
			"Service": "transfer.amazonaws.com"
		},
		"Action": "sts:AssumeRole"
		}
	]
}
EOF
}

resource "aws_iam_role_policy" "foo" {
	name = "tf-test-transfer-server-iam-policy-%s"
	role = "${aws_iam_role.foo.id}"
	policy = <<POLICY
{
	"Version": "2012-10-17",
	"Statement": [
		{
		"Sid": "AllowFullAccesstoCloudWatchLogs",
		"Effect": "Allow",
		"Action": [
			"logs:*"
		],
		"Resource": "*"
		}
	]
}
POLICY
}

resource "aws_transfer_server" "foo" {
  identity_provider_type = "SERVICE_MANAGED"
  logging_role = "${aws_iam_role.foo.arn}"

  tags {
	NAME   = "tf-acc-test-transfer-server"
	ENV    = "test"
  }
}
`, rName, rName)
}

func testAccAWSTransferServerConfig_apigateway(rName string) string {

	return fmt.Sprintf(`
resource "aws_api_gateway_rest_api" "test" {
	name = "test"
}

resource "aws_api_gateway_resource" "test" {
	rest_api_id = "${aws_api_gateway_rest_api.test.id}"
	parent_id = "${aws_api_gateway_rest_api.test.root_resource_id}"
	path_part = "test"
}

resource "aws_api_gateway_method" "test" {
	rest_api_id = "${aws_api_gateway_rest_api.test.id}"
	resource_id = "${aws_api_gateway_resource.test.id}"
	http_method = "GET"
	authorization = "NONE"
}

resource "aws_api_gateway_method_response" "error" {
	rest_api_id = "${aws_api_gateway_rest_api.test.id}"
	resource_id = "${aws_api_gateway_resource.test.id}"
	http_method = "${aws_api_gateway_method.test.http_method}"
	status_code = "400"
}

resource "aws_api_gateway_integration" "test" {
	rest_api_id = "${aws_api_gateway_rest_api.test.id}"
	resource_id = "${aws_api_gateway_resource.test.id}"
	http_method = "${aws_api_gateway_method.test.http_method}"

	type = "HTTP"
	uri = "https://www.google.de"
	integration_http_method = "GET"
}

resource "aws_api_gateway_integration_response" "test" {
	rest_api_id = "${aws_api_gateway_rest_api.test.id}"
	resource_id = "${aws_api_gateway_resource.test.id}"
	http_method = "${aws_api_gateway_integration.test.http_method}"
	status_code = "${aws_api_gateway_method_response.error.status_code}"
}

resource "aws_api_gateway_deployment" "test" {
	depends_on = ["aws_api_gateway_integration.test"]

	rest_api_id = "${aws_api_gateway_rest_api.test.id}"
	stage_name = "test"
	description = "%s"
	stage_description = "%s"

  variables = {
    "a" = "2"
  }
}

resource "aws_iam_role" "foo" {
	name = "tf-test-transfer-server-iam-role-for-apigateway-%s"

	assume_role_policy = <<EOF
{
	"Version": "2012-10-17",
	"Statement": [
		{
		"Effect": "Allow",
		"Principal": {
			"Service": "transfer.amazonaws.com"
		},
		"Action": "sts:AssumeRole"
		}
	]
}
EOF
}

resource "aws_iam_role_policy" "foo" {
	name = "tf-test-transfer-server-iam-policy-%s"
	role = "${aws_iam_role.foo.id}"
	policy = <<POLICY
{
	"Version": "2012-10-17",
	"Statement": [
		{
		"Sid": "AllowFullAccesstoCloudWatchLogs",
		"Effect": "Allow",
		"Action": [
			"logs:*"
		],
		"Resource": "*"
		}
	]
}
POLICY
}

resource "aws_transfer_server" "foo" {
	identity_provider_type	= "API_GATEWAY"
	url 				   	= "https://${aws_api_gateway_rest_api.test.id}.execute-api.us-west-2.amazonaws.com${aws_api_gateway_resource.test.path}"
	invocation_role 	   	= "${aws_iam_role.foo.arn}"
	logging_role 		   	= "${aws_iam_role.foo.arn}"

	tags {
	  NAME     = "tf-acc-test-transfer-server"
	  TYPE	   = "apigateway"
	}
}
`, rName, rName, rName, rName)

}
<|endoftext|>


<commit_before>package attrrange

import (
	"testing"

	"github.com/kylelemons/godebug/pretty"
)

func TestForPosition(t *testing.T) {
	tests := []struct {
		desc string
		// if not nil, called before calling ForPosition.
		// Can add ranges.
		update        func(*Tracker) error
		pos           int
		want          *AttrRange
		wantErr       error
		wantUpdateErr bool
	}{
		{
			desc:    "fails when no ranges given",
			pos:     0,
			wantErr: ErrNotFound,
		},
		{
			desc: "fails to add a duplicate",
			update: func(tr *Tracker) error {
				if err := tr.Add(2, 5, 40); err != nil {
					return err
				}
				return tr.Add(2, 3, 41)
			},
			wantUpdateErr: true,
		},
		{
			desc: "fails when multiple given ranges, position falls before them",
			update: func(tr *Tracker) error {
				if err := tr.Add(2, 5, 40); err != nil {
					return err
				}
				return tr.Add(5, 10, 41)
			},
			pos:     1,
			wantErr: ErrNotFound,
		},
		{
			desc: "multiple given options, position falls on the lower",
			update: func(tr *Tracker) error {
				if err := tr.Add(2, 5, 40); err != nil {
					return err
				}
				return tr.Add(5, 10, 41)
			},
			pos:  2,
			want: newAttrRange(2, 5, 40),
		},
		{
			desc: "multiple given options, position falls between them",
			update: func(tr *Tracker) error {
				if err := tr.Add(2, 5, 40); err != nil {
					return err
				}
				return tr.Add(5, 10, 41)
			},
			pos:  4,
			want: newAttrRange(2, 5, 40),
		},
		{
			desc: "multiple given options, position falls on the higher",
			update: func(tr *Tracker) error {
				if err := tr.Add(2, 5, 40); err != nil {
					return err
				}
				return tr.Add(5, 10, 41)
			},
			pos:  5,
			want: newAttrRange(5, 10, 41),
		},
		{
			desc: "multiple given options, position falls after them",
			update: func(tr *Tracker) error {
				if err := tr.Add(2, 5, 40); err != nil {
					return err
				}
				return tr.Add(5, 10, 41)
			},
			pos:     10,
			wantErr: ErrNotFound,
		},
	}

	for _, tc := range tests {
		t.Run(tc.desc, func(t *testing.T) {
			tr := NewTracker()
			if tc.update != nil {
				err := tc.update(tr)
				if (err != nil) != tc.wantUpdateErr {
					t.Errorf("tc.update => unexpected error:%v, wantUpdateErr:%v", err, tc.wantUpdateErr)
				}
				if err != nil {
					return
				}
			}

			got, err := tr.ForPosition(tc.pos)
			if err != tc.wantErr {
				t.Errorf("ForPosition => unexpected error:%v, wantErr:%v", err, tc.wantErr)
			}
			if err != nil {
				return
			}

			if diff := pretty.Compare(tc.want, got); diff != "" {
				t.Errorf("ForPosition => unexpected diff (-want, +got):\n%s", diff)
			}
		})
	}
}
<commit_msg>Adding an usage example for the attrrange package.<commit_after>package attrrange

import (
	"log"
	"testing"

	"github.com/kylelemons/godebug/pretty"
	"github.com/mum4k/termdash/cell"
)

func Example() {
	// Caller has a slice of some attributes, like a cell color that applies
	// to a portion of text.
	attrs := []cell.Color{cell.ColorRed, cell.ColorBlue}
	redIdx := 0
	blueIdx := 1

	// This is the text the colors apply to.
	const text = "HelloWorld"

	// Assuming that we want the word "Hello" in red and the word "World" in
	// green, we can set our ranges as follows:
	tr := NewTracker()
	if err := tr.Add(0, len("Hello"), redIdx); err != nil {
		panic(err)
	}
	if err := tr.Add(len("Hello")+1, len(text), blueIdx); err != nil {
		panic(err)
	}

	// Now to get the index into attrs (i.e. the color) for a particular
	// character, we can do:
	for i, c := range text {
		ar, err := tr.ForPosition(i)
		if err != nil {
			panic(err)
		}
		log.Printf("character at text[%d] = %q, color index %d = %v, range low:%d, high:%d", i, c, ar.AttrIdx, attrs[ar.AttrIdx], ar.Low, ar.High)
	}
}

func TestForPosition(t *testing.T) {
	tests := []struct {
		desc string
		// if not nil, called before calling ForPosition.
		// Can add ranges.
		update        func(*Tracker) error
		pos           int
		want          *AttrRange
		wantErr       error
		wantUpdateErr bool
	}{
		{
			desc:    "fails when no ranges given",
			pos:     0,
			wantErr: ErrNotFound,
		},
		{
			desc: "fails to add a duplicate",
			update: func(tr *Tracker) error {
				if err := tr.Add(2, 5, 40); err != nil {
					return err
				}
				return tr.Add(2, 3, 41)
			},
			wantUpdateErr: true,
		},
		{
			desc: "fails when multiple given ranges, position falls before them",
			update: func(tr *Tracker) error {
				if err := tr.Add(2, 5, 40); err != nil {
					return err
				}
				return tr.Add(5, 10, 41)
			},
			pos:     1,
			wantErr: ErrNotFound,
		},
		{
			desc: "multiple given options, position falls on the lower",
			update: func(tr *Tracker) error {
				if err := tr.Add(2, 5, 40); err != nil {
					return err
				}
				return tr.Add(5, 10, 41)
			},
			pos:  2,
			want: newAttrRange(2, 5, 40),
		},
		{
			desc: "multiple given options, position falls between them",
			update: func(tr *Tracker) error {
				if err := tr.Add(2, 5, 40); err != nil {
					return err
				}
				return tr.Add(5, 10, 41)
			},
			pos:  4,
			want: newAttrRange(2, 5, 40),
		},
		{
			desc: "multiple given options, position falls on the higher",
			update: func(tr *Tracker) error {
				if err := tr.Add(2, 5, 40); err != nil {
					return err
				}
				return tr.Add(5, 10, 41)
			},
			pos:  5,
			want: newAttrRange(5, 10, 41),
		},
		{
			desc: "multiple given options, position falls after them",
			update: func(tr *Tracker) error {
				if err := tr.Add(2, 5, 40); err != nil {
					return err
				}
				return tr.Add(5, 10, 41)
			},
			pos:     10,
			wantErr: ErrNotFound,
		},
	}

	for _, tc := range tests {
		t.Run(tc.desc, func(t *testing.T) {
			tr := NewTracker()
			if tc.update != nil {
				err := tc.update(tr)
				if (err != nil) != tc.wantUpdateErr {
					t.Errorf("tc.update => unexpected error:%v, wantUpdateErr:%v", err, tc.wantUpdateErr)
				}
				if err != nil {
					return
				}
			}

			got, err := tr.ForPosition(tc.pos)
			if err != tc.wantErr {
				t.Errorf("ForPosition => unexpected error:%v, wantErr:%v", err, tc.wantErr)
			}
			if err != nil {
				return
			}

			if diff := pretty.Compare(tc.want, got); diff != "" {
				t.Errorf("ForPosition => unexpected diff (-want, +got):\n%s", diff)
			}
		})
	}
}
<|endoftext|>


<commit_before>package aws_identity_cert

import (
	"crypto/rand"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/pem"
	"fmt"
	"io/ioutil"
	"math/big"
	"net/http"
	"net/url"
	"strings"
	"time"

	presignc "github.com/Cloud-Foundations/golib/pkg/awsutil/presignauth/caller"
	"github.com/Cloud-Foundations/golib/pkg/log/nulllogger"

	"github.com/aws/aws-sdk-go-v2/aws/arn"
)

func defaultFailureWriter(w http.ResponseWriter, r *http.Request,
	errorString string, code int) {
	http.Error(w, errorString, code)
}

func getCallerIdentity(header http.Header,
	presignCallerClient presignc.Caller) (arn.ARN, error) {
	claimedArn := header.Get("claimed-arn")
	presignedMethod := header.Get("presigned-method")
	presignedUrl := header.Get("presigned-url")
	if claimedArn == "" || presignedUrl == "" || presignedMethod == "" {
		return arn.ARN{}, fmt.Errorf("missing presigned request data")
	}
	parsedArn, err := presignCallerClient.GetCallerIdentity(nil,
		presignedMethod, presignedUrl)
	if err != nil {
		return arn.ARN{}, err
	}
	if parsedArn.String() != claimedArn {
		return arn.ARN{}, fmt.Errorf("validated ARN: %s != claimed ARN: %s",
			parsedArn.String(), claimedArn)
	}
	return parsedArn, nil
}

func makeCertificateTemplate(callerArn arn.ARN) (*x509.Certificate, error) {
	if !strings.HasPrefix(callerArn.Resource, "role/") {
		return nil, fmt.Errorf("invalid resource: %s", callerArn.Resource)
	}
	commonName := roleCommonName(callerArn)
	subject := pkix.Name{
		CommonName:   commonName,
		Organization: []string{"keymaster"},
	}
	arnUrl, err := url.Parse(callerArn.String())
	if err != nil {
		return nil, err
	}
	serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
	serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
	if err != nil {
		return nil, err
	}
	now := time.Now()
	return &x509.Certificate{
		SerialNumber:          serialNumber,
		Subject:               subject,
		NotBefore:             now,
		NotAfter:              now.Add(time.Hour * 24),
		KeyUsage:              x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment | x509.KeyUsageKeyAgreement,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
		BasicConstraintsValid: true,
		IsCA:                  false,
		URIs:                  []*url.URL{arnUrl},
	}, nil
}

func newIssuer(params Params) (*Issuer, error) {
	if params.AccountIdValidator == nil {
		params.AccountIdValidator = nullAccountIdValidator
	}
	if params.FailureWriter == nil {
		params.FailureWriter = defaultFailureWriter
	}
	if params.Logger == nil {
		params.Logger = nulllogger.New()
	}
	presignCallerClient, err := presignc.New(presignc.Params{
		HttpClient: params.HttpClient,
		Logger:     params.Logger,
	})
	if err != nil {
		return nil, err
	}
	return &Issuer{
		presignCallerClient: presignCallerClient,
		params:              params,
	}, nil
}

func nullAccountIdValidator(accountId string) bool {
	return true
}

func nullCertificateModifier(cert *x509.Certificate) error {
	return nil
}

func roleCommonName(roleArn arn.ARN) string {
	return fmt.Sprintf("aws:iam:%s:%s", roleArn.AccountID, roleArn.Resource[5:])
}

func (i *Issuer) requestHandler(w http.ResponseWriter,
	r *http.Request) *x509.Certificate {
	if r.Method != "POST" {
		i.params.FailureWriter(w, r, "", http.StatusMethodNotAllowed)
		return nil
	}
	// First extract and validate AWS credentials claim.
	callerArn, err := getCallerIdentity(r.Header, i.presignCallerClient)
	if err != nil {
		i.params.Logger.Println(err)
		i.params.FailureWriter(w, r, "verification request failed",
			http.StatusUnauthorized)
		return nil
	}
	if !i.params.AccountIdValidator(callerArn.AccountID) {
		i.params.Logger.Printf("AWS account: %s not allowed\n",
			callerArn.AccountID)
		i.params.FailureWriter(w, r, "AWS account not allowed",
			http.StatusUnauthorized)
		return nil
	}
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		i.params.Logger.Println(err)
		i.params.FailureWriter(w, r, "error reading body",
			http.StatusInternalServerError)
		return nil
	}
	// Now extract the public key PEM data.
	block, _ := pem.Decode(body)
	if block == nil {
		i.params.Logger.Println("unable to decode PEM block")
		i.params.FailureWriter(w, r, "invalid PEM block", http.StatusBadRequest)
		return nil
	}
	if block.Type != "PUBLIC KEY" {
		i.params.Logger.Printf("unsupported PEM type: %s\n", block.Type)
		i.params.FailureWriter(w, r, "unsupported PEM type",
			http.StatusBadRequest)
		return nil
	}
	pub, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		i.params.Logger.Println(err)
		i.params.FailureWriter(w, r, "invalid DER", http.StatusBadRequest)
		return nil
	}
	template, certDER, err := i.generateRoleCert(pub, callerArn)
	if err != nil {
		i.params.Logger.Println(err)
		i.params.FailureWriter(w, r, err.Error(),
			http.StatusInternalServerError)
		return nil
	}
	pem.Encode(w, &pem.Block{Bytes: certDER, Type: "CERTIFICATE"})
	return template
}

// Returns template and signed certificate DER.
func (i *Issuer) generateRoleCert(publicKey interface{},
	callerArn arn.ARN) (*x509.Certificate, []byte, error) {
	template, err := makeCertificateTemplate(callerArn)
	if err != nil {
		return nil, nil, err
	}
	certDER, err := i.params.CertificateGenerator(template, publicKey)
	if err != nil {
		return nil, nil, err
	}
	i.params.Logger.Printf(
		"Generated x509 Certificate for ARN=`%s`, expires=%s",
		callerArn.String(), template.NotAfter)
	return template, certDER, nil
}
<commit_msg>Satiate code scanner.<commit_after>package aws_identity_cert

import (
	"crypto/rand"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/pem"
	"fmt"
	"html"
	"io/ioutil"
	"math/big"
	"net/http"
	"net/url"
	"strings"
	"time"

	presignc "github.com/Cloud-Foundations/golib/pkg/awsutil/presignauth/caller"
	"github.com/Cloud-Foundations/golib/pkg/log/nulllogger"

	"github.com/aws/aws-sdk-go-v2/aws/arn"
)

func defaultFailureWriter(w http.ResponseWriter, r *http.Request,
	errorString string, code int) {
	http.Error(w, errorString, code)
}

func getCallerIdentity(header http.Header,
	presignCallerClient presignc.Caller) (arn.ARN, error) {
	claimedArn := html.EscapeString(header.Get("claimed-arn"))
	presignedMethod := header.Get("presigned-method")
	presignedUrl := header.Get("presigned-url")
	if claimedArn == "" || presignedUrl == "" || presignedMethod == "" {
		return arn.ARN{}, fmt.Errorf("missing presigned request data")
	}
	parsedArn, err := presignCallerClient.GetCallerIdentity(nil,
		presignedMethod, presignedUrl)
	if err != nil {
		return arn.ARN{}, err
	}
	if parsedArn.String() != claimedArn {
		return arn.ARN{}, fmt.Errorf("validated ARN: %s != claimed ARN: %s",
			parsedArn.String(), claimedArn)
	}
	return parsedArn, nil
}

func makeCertificateTemplate(callerArn arn.ARN) (*x509.Certificate, error) {
	if !strings.HasPrefix(callerArn.Resource, "role/") {
		return nil, fmt.Errorf("invalid resource: %s", callerArn.Resource)
	}
	commonName := roleCommonName(callerArn)
	subject := pkix.Name{
		CommonName:   commonName,
		Organization: []string{"keymaster"},
	}
	arnUrl, err := url.Parse(callerArn.String())
	if err != nil {
		return nil, err
	}
	serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
	serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
	if err != nil {
		return nil, err
	}
	now := time.Now()
	return &x509.Certificate{
		SerialNumber:          serialNumber,
		Subject:               subject,
		NotBefore:             now,
		NotAfter:              now.Add(time.Hour * 24),
		KeyUsage:              x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment | x509.KeyUsageKeyAgreement,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
		BasicConstraintsValid: true,
		IsCA:                  false,
		URIs:                  []*url.URL{arnUrl},
	}, nil
}

func newIssuer(params Params) (*Issuer, error) {
	if params.AccountIdValidator == nil {
		params.AccountIdValidator = nullAccountIdValidator
	}
	if params.FailureWriter == nil {
		params.FailureWriter = defaultFailureWriter
	}
	if params.Logger == nil {
		params.Logger = nulllogger.New()
	}
	presignCallerClient, err := presignc.New(presignc.Params{
		HttpClient: params.HttpClient,
		Logger:     params.Logger,
	})
	if err != nil {
		return nil, err
	}
	return &Issuer{
		presignCallerClient: presignCallerClient,
		params:              params,
	}, nil
}

func nullAccountIdValidator(accountId string) bool {
	return true
}

func nullCertificateModifier(cert *x509.Certificate) error {
	return nil
}

func roleCommonName(roleArn arn.ARN) string {
	return fmt.Sprintf("aws:iam:%s:%s", roleArn.AccountID, roleArn.Resource[5:])
}

func (i *Issuer) requestHandler(w http.ResponseWriter,
	r *http.Request) *x509.Certificate {
	if r.Method != "POST" {
		i.params.FailureWriter(w, r, "", http.StatusMethodNotAllowed)
		return nil
	}
	// First extract and validate AWS credentials claim.
	callerArn, err := getCallerIdentity(r.Header, i.presignCallerClient)
	if err != nil {
		i.params.Logger.Println(err)
		i.params.FailureWriter(w, r, "verification request failed",
			http.StatusUnauthorized)
		return nil
	}
	if !i.params.AccountIdValidator(callerArn.AccountID) {
		i.params.Logger.Printf("AWS account: %s not allowed\n",
			callerArn.AccountID)
		i.params.FailureWriter(w, r, "AWS account not allowed",
			http.StatusUnauthorized)
		return nil
	}
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		i.params.Logger.Println(err)
		i.params.FailureWriter(w, r, "error reading body",
			http.StatusInternalServerError)
		return nil
	}
	// Now extract the public key PEM data.
	block, _ := pem.Decode(body)
	if block == nil {
		i.params.Logger.Println("unable to decode PEM block")
		i.params.FailureWriter(w, r, "invalid PEM block", http.StatusBadRequest)
		return nil
	}
	if block.Type != "PUBLIC KEY" {
		i.params.Logger.Printf("unsupported PEM type: %s\n",
			html.EscapeString(block.Type))
		i.params.FailureWriter(w, r, "unsupported PEM type",
			http.StatusBadRequest)
		return nil
	}
	pub, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		i.params.Logger.Println(err)
		i.params.FailureWriter(w, r, "invalid DER", http.StatusBadRequest)
		return nil
	}
	template, certDER, err := i.generateRoleCert(pub, callerArn)
	if err != nil {
		i.params.Logger.Println(err)
		i.params.FailureWriter(w, r, err.Error(),
			http.StatusInternalServerError)
		return nil
	}
	pem.Encode(w, &pem.Block{Bytes: certDER, Type: "CERTIFICATE"})
	return template
}

// Returns template and signed certificate DER.
func (i *Issuer) generateRoleCert(publicKey interface{},
	callerArn arn.ARN) (*x509.Certificate, []byte, error) {
	template, err := makeCertificateTemplate(callerArn)
	if err != nil {
		return nil, nil, err
	}
	certDER, err := i.params.CertificateGenerator(template, publicKey)
	if err != nil {
		return nil, nil, err
	}
	i.params.Logger.Printf(
		"Generated x509 Certificate for ARN=`%s`, expires=%s",
		callerArn.String(), template.NotAfter)
	return template, certDER, nil
}
<|endoftext|>


<commit_before>package nats

import (
	"fmt"
	"testing"

	"github.com/micro/go-micro/broker"
	nats "github.com/nats-io/nats.go"
)

var addrTestCases = []struct {
	name        string
	description string
	addrs       map[string]string // expected address : set address
}{
	{
		"brokerOpts",
		"set broker addresses through a broker.Option in constructor",
		map[string]string{
			"nats://192.168.10.1:5222": "192.168.10.1:5222",
			"nats://10.20.10.0:4222":   "10.20.10.0:4222"},
	},
	{
		"brokerInit",
		"set broker addresses through a broker.Option in broker.Init()",
		map[string]string{
			"nats://192.168.10.1:5222": "192.168.10.1:5222",
			"nats://10.20.10.0:4222":   "10.20.10.0:4222"},
	},
	{
		"natsOpts",
		"set broker addresses through the nats.Option in constructor",
		map[string]string{
			"nats://192.168.10.1:5222": "192.168.10.1:5222",
			"nats://10.20.10.0:4222":   "10.20.10.0:4222"},
	},
	{
		"default",
		"check if default Address is set correctly",
		map[string]string{
			"nats://localhost:4222": "",
		},
	},
}

// TestInitAddrs tests issue #100. Ensures that if the addrs is set by an option in init it will be used.
func TestInitAddrs(t *testing.T) {

	for _, tc := range addrTestCases {
		t.Run(fmt.Sprintf("%s: %s", tc.name, tc.description), func(t *testing.T) {

			var br broker.Broker
			var addrs []string

			for _, addr := range tc.addrs {
				addrs = append(addrs, addr)
			}

			switch tc.name {
			case "brokerOpts":
				// we know that there are just two addrs in the dict
				br = NewBroker(broker.Addrs(addrs[0], addrs[1]))
				br.Init()
			case "brokerInit":
				br = NewBroker()
				// we know that there are just two addrs in the dict
				br.Init(broker.Addrs(addrs[0], addrs[1]))
			case "natsOpts":
				nopts := nats.GetDefaultOptions()
				nopts.Servers = addrs
				br = NewBroker(Options(nopts))
				br.Init()
			case "default":
				br = NewBroker()
				br.Init()
			}

			natsBroker, ok := br.(*natsBroker)
			if !ok {
				t.Fatal("Expected broker to be of types *natsBroker")
			}
			// check if the same amount of addrs we set has actually been set, default
			// have only 1 address nats://127.0.0.1:4222 (current nats code) or
			// nats://localhost:4222 (older code version)
			if len(natsBroker.addrs) != len(tc.addrs) && tc.name != "default" {
				t.Errorf("Expected Addr count = %d, Actual Addr count = %d",
					len(natsBroker.addrs), len(tc.addrs))
			}

			for _, addr := range natsBroker.addrs {
				_, ok := tc.addrs[addr]
				if !ok {
					t.Errorf("Expected '%s' has not been set", addr)
				}
			}
		})

	}
}
<commit_msg>Changed default NATS address to nats://127.0.0.1:4222 in nats test<commit_after>package nats

import (
	"fmt"
	"testing"

	"github.com/micro/go-micro/broker"
	nats "github.com/nats-io/nats.go"
)

var addrTestCases = []struct {
	name        string
	description string
	addrs       map[string]string // expected address : set address
}{
	{
		"brokerOpts",
		"set broker addresses through a broker.Option in constructor",
		map[string]string{
			"nats://192.168.10.1:5222": "192.168.10.1:5222",
			"nats://10.20.10.0:4222":   "10.20.10.0:4222"},
	},
	{
		"brokerInit",
		"set broker addresses through a broker.Option in broker.Init()",
		map[string]string{
			"nats://192.168.10.1:5222": "192.168.10.1:5222",
			"nats://10.20.10.0:4222":   "10.20.10.0:4222"},
	},
	{
		"natsOpts",
		"set broker addresses through the nats.Option in constructor",
		map[string]string{
			"nats://192.168.10.1:5222": "192.168.10.1:5222",
			"nats://10.20.10.0:4222":   "10.20.10.0:4222"},
	},
	{
		"default",
		"check if default Address is set correctly",
		map[string]string{
			"nats://127.0.0.1:4222": "",
		},
	},
}

// TestInitAddrs tests issue #100. Ensures that if the addrs is set by an option in init it will be used.
func TestInitAddrs(t *testing.T) {

	for _, tc := range addrTestCases {
		t.Run(fmt.Sprintf("%s: %s", tc.name, tc.description), func(t *testing.T) {

			var br broker.Broker
			var addrs []string

			for _, addr := range tc.addrs {
				addrs = append(addrs, addr)
			}

			switch tc.name {
			case "brokerOpts":
				// we know that there are just two addrs in the dict
				br = NewBroker(broker.Addrs(addrs[0], addrs[1]))
				br.Init()
			case "brokerInit":
				br = NewBroker()
				// we know that there are just two addrs in the dict
				br.Init(broker.Addrs(addrs[0], addrs[1]))
			case "natsOpts":
				nopts := nats.GetDefaultOptions()
				nopts.Servers = addrs
				br = NewBroker(Options(nopts))
				br.Init()
			case "default":
				br = NewBroker()
				br.Init()
			}

			natsBroker, ok := br.(*natsBroker)
			if !ok {
				t.Fatal("Expected broker to be of types *natsBroker")
			}
			// check if the same amount of addrs we set has actually been set, default
			// have only 1 address nats://127.0.0.1:4222 (current nats code) or
			// nats://localhost:4222 (older code version)
			if len(natsBroker.addrs) != len(tc.addrs) && tc.name != "default" {
				t.Errorf("Expected Addr count = %d, Actual Addr count = %d",
					len(natsBroker.addrs), len(tc.addrs))
			}

			for _, addr := range natsBroker.addrs {
				_, ok := tc.addrs[addr]
				if !ok {
					t.Errorf("Expected '%s' has not been set", addr)
				}
			}
		})

	}
}
<|endoftext|>


<commit_before><commit_msg>v5: add logger<commit_after><|endoftext|>


<commit_before>package sso

import (
	"fmt"
	"net/url"
	"strings"
)

type authURLParams struct {
	prividerName   string
	clientID       string
	urlPrefix      string
	scope          Scope
	options        Options
	stateJWTSecret string
	state          State
	baseURL        string
}

func authURL(params authURLParams) (string, error) {
	encodedState, err := EncodeState(params.stateJWTSecret, params.state)
	if err != nil {
		return "", err
	}
	v := url.Values{}
	v.Set("response_type", "code")
	v.Add("client_id", params.clientID)
	v.Add("redirect_uri", RedirectURI(params.urlPrefix, params.prividerName))
	v.Add("state", encodedState)
	v.Add("scope", strings.Join(params.scope, " "))
	v.Add("access_type", "offline")
	v.Add("prompt", "select_account")
	for k, o := range params.options {
		v.Add(k, fmt.Sprintf("%v", o))
	}
	return params.baseURL + "?" + v.Encode(), nil
}
<commit_msg>Remove unnecessary options from authurl<commit_after>package sso

import (
	"fmt"
	"net/url"
	"strings"
)

type authURLParams struct {
	prividerName   string
	clientID       string
	urlPrefix      string
	scope          Scope
	options        Options
	stateJWTSecret string
	state          State
	baseURL        string
}

func authURL(params authURLParams) (string, error) {
	encodedState, err := EncodeState(params.stateJWTSecret, params.state)
	if err != nil {
		return "", err
	}
	v := url.Values{}
	v.Set("response_type", "code")
	v.Add("client_id", params.clientID)
	v.Add("redirect_uri", RedirectURI(params.urlPrefix, params.prividerName))
	v.Add("state", encodedState)
	v.Add("scope", strings.Join(params.scope, " "))
	for k, o := range params.options {
		v.Add(k, fmt.Sprintf("%v", o))
	}
	return params.baseURL + "?" + v.Encode(), nil
}
<|endoftext|>


<commit_before>package handler

import (
	"encoding/json"
	"net/http"

	"github.com/skygeario/skygear-server/pkg/auth/dependency/sso"
	"github.com/skygeario/skygear-server/pkg/server/skyerr"

	"github.com/gorilla/mux"
	"github.com/skygeario/skygear-server/pkg/auth"
	coreAuth "github.com/skygeario/skygear-server/pkg/core/auth"
	"github.com/skygeario/skygear-server/pkg/core/auth/authz"
	"github.com/skygeario/skygear-server/pkg/core/auth/authz/policy"
	"github.com/skygeario/skygear-server/pkg/core/db"
	"github.com/skygeario/skygear-server/pkg/core/handler"
	"github.com/skygeario/skygear-server/pkg/core/inject"
	"github.com/skygeario/skygear-server/pkg/core/server"
)

func AttachLoginAuthURLHandler(
	server *server.Server,
	authDependency auth.DependencyMap,
) *server.Server {
	server.Handle("/sso/{provider}/login_auth_url", &LoginAuthURLHandlerFactory{
		authDependency,
	}).Methods("OPTIONS", "POST")
	return server
}

type LoginAuthURLHandlerFactory struct {
	Dependency auth.DependencyMap
}

func (f LoginAuthURLHandlerFactory) NewHandler(request *http.Request) http.Handler {
	h := &LoginAuthURLHandler{}
	inject.DefaultInject(h, f.Dependency, request)

	vars := mux.Vars(request)
	h.ProviderName = vars["provider"]
	providers := map[string]sso.Provider{
		"google":    h.GoogleProvider,
		"facebook":  h.FacebookProvider,
		"instagram": h.InstagramProvider,
		"linkedin":  h.LinkedInProvider,
	}
	if provider, ok := providers[h.ProviderName]; ok {
		h.Provider = provider
	}

	return handler.APIHandlerToHandler(h, h.TxContext)
}

func (f LoginAuthURLHandlerFactory) ProvideAuthzPolicy() authz.Policy {
	return authz.PolicyFunc(policy.DenyNoAccessKey)
}

// LoginAuthURLRequestPayload login handler request payload
type LoginAuthURLRequestPayload struct {
	Scope       []string               `json:"scope"`
	Options     map[string]interface{} `json:"options"`
	CallbackURL string                 `json:"callback_url"`
	RawUXMode   string                 `json:"ux_mode"`
	UXMode      sso.UXMode
}

// Validate request payload
func (p LoginAuthURLRequestPayload) Validate() error {
	if p.CallbackURL == "" {
		return skyerr.NewInvalidArgument("Callback url is required", []string{"callback_url"})
	}

	if p.UXMode == sso.Undefined {
		return skyerr.NewInvalidArgument("UX mode is required", []string{"ux_mode"})
	}

	return nil
}

// LoginAuthURLHandler returns the SSO auth url by provider.
//
// curl \
//   -X POST \
//   -H "Content-Type: application/json" \
//   -H "X-Skygear-Api-Key: API_KEY" \
//   -d @- \
//   http://localhost:3000/sso/<provider>/login_auth_url \
// <<EOF
// {
//     "scope": ["openid", "profile"],
//     "options": {
//       "prompt": "select_account"
//     },
//     callback_url: <url>,
//     ux_mode: <ux_mode>
// }
// EOF
//
// {
//     "result": "<auth_url>"
// }
type LoginAuthURLHandler struct {
	TxContext         db.TxContext           `dependency:"TxContext"`
	GoogleProvider    sso.Provider           `dependency:"GoogleSSOProvider,optional"`
	FacebookProvider  sso.Provider           `dependency:"FacebookSSOProvider,optional"`
	InstagramProvider sso.Provider           `dependency:"InstagramSSOProvider,optional"`
	LinkedInProvider  sso.Provider           `dependency:"LinkedInSSOProvider,optional"`
	AuthContext       coreAuth.ContextGetter `dependency:"AuthContextGetter"`
	ProviderName      string
	Provider          sso.Provider
}

func (h LoginAuthURLHandler) WithTx() bool {
	return true
}

func (h LoginAuthURLHandler) DecodeRequest(request *http.Request) (handler.RequestPayload, error) {
	payload := LoginAuthURLRequestPayload{
		// avoid nil pointer
		Scope:   make([]string, 0),
		Options: make(sso.Options),
	}
	err := json.NewDecoder(request.Body).Decode(&payload)
	payload.UXMode = sso.UXModeFromString(payload.RawUXMode)

	return payload, err
}

func (h LoginAuthURLHandler) Handle(req interface{}) (resp interface{}, err error) {
	if h.Provider == nil {
		err = skyerr.NewInvalidArgument("Provider is not supported", []string{h.ProviderName})
		return
	}
	payload := req.(LoginAuthURLRequestPayload)
	params := sso.GetURLParams{
		Scope:       payload.Scope,
		Options:     payload.Options,
		CallbackURL: payload.CallbackURL,
		UXMode:      payload.UXMode,
		Action:      "login",
	}
	if h.AuthContext.AuthInfo() != nil {
		params.UserID = h.AuthContext.AuthInfo().ID
	}
	url, err := h.Provider.GetAuthURL(params)
	if err != nil {
		return
	}
	resp = url
	return
}
<commit_msg>Inject SSO provider by route path<commit_after>package handler

import (
	"encoding/json"
	"net/http"
	"strings"

	"github.com/skygeario/skygear-server/pkg/auth/dependency/sso"
	"github.com/skygeario/skygear-server/pkg/server/skyerr"

	"github.com/gorilla/mux"
	"github.com/skygeario/skygear-server/pkg/auth"
	coreAuth "github.com/skygeario/skygear-server/pkg/core/auth"
	"github.com/skygeario/skygear-server/pkg/core/auth/authz"
	"github.com/skygeario/skygear-server/pkg/core/auth/authz/policy"
	"github.com/skygeario/skygear-server/pkg/core/db"
	"github.com/skygeario/skygear-server/pkg/core/handler"
	"github.com/skygeario/skygear-server/pkg/core/inject"
	"github.com/skygeario/skygear-server/pkg/core/server"
)

func AttachLoginAuthURLHandler(
	server *server.Server,
	authDependency auth.DependencyMap,
) *server.Server {
	server.Handle("/sso/{provider}/login_auth_url", &LoginAuthURLHandlerFactory{
		authDependency,
	}).Methods("OPTIONS", "POST")
	return server
}

type LoginAuthURLHandlerFactory struct {
	Dependency auth.DependencyMap
}

func (f LoginAuthURLHandlerFactory) NewHandler(request *http.Request) http.Handler {
	h := &LoginAuthURLHandler{}
	inject.DefaultInject(h, f.Dependency, request)

	vars := mux.Vars(request)
	h.ProviderName = vars["provider"]
	providerDependencyName := strings.Title(h.ProviderName) + "SSOProvider"
	if provider, ok := f.Dependency.Provide(providerDependencyName, request).(sso.Provider); ok {
		h.Provider = provider
	}

	return handler.APIHandlerToHandler(h, h.TxContext)
}

func (f LoginAuthURLHandlerFactory) ProvideAuthzPolicy() authz.Policy {
	return authz.PolicyFunc(policy.DenyNoAccessKey)
}

// LoginAuthURLRequestPayload login handler request payload
type LoginAuthURLRequestPayload struct {
	Scope       []string               `json:"scope"`
	Options     map[string]interface{} `json:"options"`
	CallbackURL string                 `json:"callback_url"`
	RawUXMode   string                 `json:"ux_mode"`
	UXMode      sso.UXMode
}

// Validate request payload
func (p LoginAuthURLRequestPayload) Validate() error {
	if p.CallbackURL == "" {
		return skyerr.NewInvalidArgument("Callback url is required", []string{"callback_url"})
	}

	if p.UXMode == sso.Undefined {
		return skyerr.NewInvalidArgument("UX mode is required", []string{"ux_mode"})
	}

	return nil
}

// LoginAuthURLHandler returns the SSO auth url by provider.
//
// curl \
//   -X POST \
//   -H "Content-Type: application/json" \
//   -H "X-Skygear-Api-Key: API_KEY" \
//   -d @- \
//   http://localhost:3000/sso/<provider>/login_auth_url \
// <<EOF
// {
//     "scope": ["openid", "profile"],
//     "options": {
//       "prompt": "select_account"
//     },
//     callback_url: <url>,
//     ux_mode: <ux_mode>
// }
// EOF
//
// {
//     "result": "<auth_url>"
// }
type LoginAuthURLHandler struct {
	TxContext    db.TxContext           `dependency:"TxContext"`
	AuthContext  coreAuth.ContextGetter `dependency:"AuthContextGetter"`
	ProviderName string
	Provider     sso.Provider
}

func (h LoginAuthURLHandler) WithTx() bool {
	return true
}

func (h LoginAuthURLHandler) DecodeRequest(request *http.Request) (handler.RequestPayload, error) {
	payload := LoginAuthURLRequestPayload{
		// avoid nil pointer
		Scope:   make([]string, 0),
		Options: make(sso.Options),
	}
	err := json.NewDecoder(request.Body).Decode(&payload)
	payload.UXMode = sso.UXModeFromString(payload.RawUXMode)

	return payload, err
}

func (h LoginAuthURLHandler) Handle(req interface{}) (resp interface{}, err error) {
	if h.Provider == nil {
		err = skyerr.NewInvalidArgument("Provider is not supported", []string{h.ProviderName})
		return
	}
	payload := req.(LoginAuthURLRequestPayload)
	params := sso.GetURLParams{
		Scope:       payload.Scope,
		Options:     payload.Options,
		CallbackURL: payload.CallbackURL,
		UXMode:      payload.UXMode,
		Action:      "login",
	}
	if h.AuthContext.AuthInfo() != nil {
		params.UserID = h.AuthContext.AuthInfo().ID
	}
	url, err := h.Provider.GetAuthURL(params)
	if err != nil {
		return
	}
	resp = url
	return
}
<|endoftext|>


<commit_before>package sarama

import (
	"math"
	"sort"
)

// BalanceStrategyPlan is the results of any BalanceStrategy.Plan attempt.
// It contains an allocation of topic/partitions by memberID in the form of
// a `memberID -> topic -> partitions` map.
type BalanceStrategyPlan map[string]map[string][]int32

// Add assigns a topic with a number partitions to a member.
func (p BalanceStrategyPlan) Add(memberID, topic string, partitions ...int32) {
	if len(partitions) == 0 {
		return
	}
	if _, ok := p[memberID]; !ok {
		p[memberID] = make(map[string][]int32, 1)
	}
	p[memberID][topic] = append(p[memberID][topic], partitions...)
}

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

// BalanceStrategy is used to balance topics and partitions
// across memebers of a consumer group
type BalanceStrategy interface {
	// Name uniquely identifies the strategy.
	Name() string

	// Plan accepts a map of `memberID -> metadata` and a map of `topic -> partitions`
	// and returns a distribution plan.
	Plan(members map[string]ConsumerGroupMemberMetadata, topics map[string][]int32) (BalanceStrategyPlan, error)
}

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

// BalanceStrategyRange is the default and assigns partitions as ranges to consumer group members.
// Example with one topic T with six partitions (0..5) and two members (M1, M2):
//   M1: {T: [0, 1, 2]}
//   M2: {T: [3, 4, 5]}
var BalanceStrategyRange = &balanceStrategy{
	name: "range",
	coreFn: func(plan BalanceStrategyPlan, memberIDs []string, topic string, partitions []int32) {
		step := float64(len(partitions)) / float64(len(memberIDs))

		for i, memberID := range memberIDs {
			pos := float64(i)
			min := int(math.Floor(pos*step + 0.5))
			max := int(math.Floor((pos+1)*step + 0.5))
			plan.Add(memberID, topic, partitions[min:max]...)
		}
	},
}

// BalanceStrategyRoundRobin assigns partitions to members in alternating order.
// Example with topic T with six partitions (0..5) and two members (M1, M2):
//   M1: {T: [0, 2, 4]}
//   M2: {T: [1, 3, 5]}
var BalanceStrategyRoundRobin = &balanceStrategy{
	name: "roundrobin",
	coreFn: func(plan BalanceStrategyPlan, memberIDs []string, topic string, partitions []int32) {
		for i, part := range partitions {
			memberID := memberIDs[i%len(memberIDs)]
			plan.Add(memberID, topic, part)
		}
	},
}

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

type balanceStrategy struct {
	name   string
	coreFn func(plan BalanceStrategyPlan, memberIDs []string, topic string, partitions []int32)
}

// Name implements BalanceStrategy.
func (s *balanceStrategy) Name() string { return s.name }

// Balance implements BalanceStrategy.
func (s *balanceStrategy) Plan(members map[string]ConsumerGroupMemberMetadata, topics map[string][]int32) (BalanceStrategyPlan, error) {
	// Build members by topic map
	mbt := make(map[string][]string)
	for memberID, meta := range members {
		for _, topic := range meta.Topics {
			mbt[topic] = append(mbt[topic], memberID)
		}
	}

	// Sort members for each topic
	for topic, memberIDs := range mbt {
		sort.Sort(&balanceStrategySortable{
			topic:     topic,
			memberIDs: memberIDs,
		})
	}

	// Assemble plan
	plan := make(BalanceStrategyPlan, len(members))
	for topic, memberIDs := range mbt {
		s.coreFn(plan, memberIDs, topic, topics[topic])
	}
	return plan, nil
}

type balanceStrategySortable struct {
	topic     string
	memberIDs []string
}

func (p balanceStrategySortable) Len() int { return len(p.memberIDs) }
func (p balanceStrategySortable) Swap(i, j int) {
	p.memberIDs[i], p.memberIDs[j] = p.memberIDs[j], p.memberIDs[i]
}
func (p balanceStrategySortable) Less(i, j int) bool {
	return balanceStrategyHashValue(p.topic, p.memberIDs[i]) < balanceStrategyHashValue(p.topic, p.memberIDs[j])
}

func balanceStrategyHashValue(vv ...string) uint32 {
	h := uint32(2166136261)
	for _, s := range vv {
		for _, c := range s {
			h ^= uint32(c)
			h *= 16777619
		}
	}
	return h
}
<commit_msg>Fix typo and comment in balance_strategy.go<commit_after>package sarama

import (
	"math"
	"sort"
)

// BalanceStrategyPlan is the results of any BalanceStrategy.Plan attempt.
// It contains an allocation of topic/partitions by memberID in the form of
// a `memberID -> topic -> partitions` map.
type BalanceStrategyPlan map[string]map[string][]int32

// Add assigns a topic with a number partitions to a member.
func (p BalanceStrategyPlan) Add(memberID, topic string, partitions ...int32) {
	if len(partitions) == 0 {
		return
	}
	if _, ok := p[memberID]; !ok {
		p[memberID] = make(map[string][]int32, 1)
	}
	p[memberID][topic] = append(p[memberID][topic], partitions...)
}

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

// BalanceStrategy is used to balance topics and partitions
// across members of a consumer group
type BalanceStrategy interface {
	// Name uniquely identifies the strategy.
	Name() string

	// Plan accepts a map of `memberID -> metadata` and a map of `topic -> partitions`
	// and returns a distribution plan.
	Plan(members map[string]ConsumerGroupMemberMetadata, topics map[string][]int32) (BalanceStrategyPlan, error)
}

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

// BalanceStrategyRange is the default and assigns partitions as ranges to consumer group members.
// Example with one topic T with six partitions (0..5) and two members (M1, M2):
//   M1: {T: [0, 1, 2]}
//   M2: {T: [3, 4, 5]}
var BalanceStrategyRange = &balanceStrategy{
	name: "range",
	coreFn: func(plan BalanceStrategyPlan, memberIDs []string, topic string, partitions []int32) {
		step := float64(len(partitions)) / float64(len(memberIDs))

		for i, memberID := range memberIDs {
			pos := float64(i)
			min := int(math.Floor(pos*step + 0.5))
			max := int(math.Floor((pos+1)*step + 0.5))
			plan.Add(memberID, topic, partitions[min:max]...)
		}
	},
}

// BalanceStrategyRoundRobin assigns partitions to members in alternating order.
// Example with topic T with six partitions (0..5) and two members (M1, M2):
//   M1: {T: [0, 2, 4]}
//   M2: {T: [1, 3, 5]}
var BalanceStrategyRoundRobin = &balanceStrategy{
	name: "roundrobin",
	coreFn: func(plan BalanceStrategyPlan, memberIDs []string, topic string, partitions []int32) {
		for i, part := range partitions {
			memberID := memberIDs[i%len(memberIDs)]
			plan.Add(memberID, topic, part)
		}
	},
}

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

type balanceStrategy struct {
	name   string
	coreFn func(plan BalanceStrategyPlan, memberIDs []string, topic string, partitions []int32)
}

// Name implements BalanceStrategy.
func (s *balanceStrategy) Name() string { return s.name }

// Plan implements BalanceStrategy.
func (s *balanceStrategy) Plan(members map[string]ConsumerGroupMemberMetadata, topics map[string][]int32) (BalanceStrategyPlan, error) {
	// Build members by topic map
	mbt := make(map[string][]string)
	for memberID, meta := range members {
		for _, topic := range meta.Topics {
			mbt[topic] = append(mbt[topic], memberID)
		}
	}

	// Sort members for each topic
	for topic, memberIDs := range mbt {
		sort.Sort(&balanceStrategySortable{
			topic:     topic,
			memberIDs: memberIDs,
		})
	}

	// Assemble plan
	plan := make(BalanceStrategyPlan, len(members))
	for topic, memberIDs := range mbt {
		s.coreFn(plan, memberIDs, topic, topics[topic])
	}
	return plan, nil
}

type balanceStrategySortable struct {
	topic     string
	memberIDs []string
}

func (p balanceStrategySortable) Len() int { return len(p.memberIDs) }
func (p balanceStrategySortable) Swap(i, j int) {
	p.memberIDs[i], p.memberIDs[j] = p.memberIDs[j], p.memberIDs[i]
}
func (p balanceStrategySortable) Less(i, j int) bool {
	return balanceStrategyHashValue(p.topic, p.memberIDs[i]) < balanceStrategyHashValue(p.topic, p.memberIDs[j])
}

func balanceStrategyHashValue(vv ...string) uint32 {
	h := uint32(2166136261)
	for _, s := range vv {
		for _, c := range s {
			h ^= uint32(c)
			h *= 16777619
		}
	}
	return h
}
<|endoftext|>


<commit_before>package main

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

	"github.com/Sirupsen/logrus"
)

type UserName string

type Instance struct {
	time *InstanceTime
	name map[ClientID]UserName
	uid  map[ClientID]UnitID

	g *Game
	r InstanceInput
	w InstanceOutputWriter
}

// NewInstance returns a Instance
func NewInstance(r InstanceInput, w InstanceOutputWriter) *Instance {
	time := new(InstanceTime)
	return &Instance{
		time: time,
		name: make(map[ClientID]UserName),
		uid:  make(map[ClientID]UnitID),

		g: NewGame(time, w),
		r: r,
		w: w,
	}
}

// Run starts the instance routine
func (i *Instance) Run() {
	t := time.Tick(RealGameTick)
	for {
		select {
		case <-t:
			*i.time = i.time.Add(GameTick)
			if i.time.IsRegenerationTick() {
				i.sync(i.w)
				i.g.PerformRegenerationTick()
			}
			if i.time.IsPeriodicalTick() {
				i.g.PerformPeriodicalTick()
			}
			i.g.PerformGameTick()
		case input, ok := <-i.r:
			if !ok {
				log.Fatal("Cannot read from the input channel")
			}
			cid := input.ClientID
			switch input := input.Input.(type) {
			case InputConnect:
				i.connect(cid, input)
			case InputDisconnect:
				i.disconnect(cid, input)
			case InputProfile:
				i.profile(cid, input)
			case InputChat:
				i.chat(cid, input)
			case InputStage:
				i.stage(cid, input)
			case InputJoin:
				i.join(cid, input)
			case InputLeave:
				i.leave(cid, input)
			case InputAbility:
				i.ability(cid, input)
			case InputInterrupt:
				// TODO WIP
			default:
				log.Fatal("Unknown input type")
			}
		}
	}
}

// generateName returns a random user name
func (i *Instance) generateName() UserName {
	return UserName(fmt.Sprintf("user%03d", rand.Intn(1000)))
}

// sync sends a OutputSync message
func (i *Instance) sync(w InstanceOutputWriter) {
	w.Write(OutputSync{
		InstanceTime: *i.time,
	})
}

// connect
func (i *Instance) connect(cid ClientID, input InputConnect) {
	name := i.generateName()
	i.name[cid] = name

	i.sync(i.w.BindClientID(cid))
	i.w.BindClientID(cid).Write(OutputMessage{
		Message: "Welcome to Crescent!",
	})
	i.w.Write(OutputMessage{
		Message: fmt.Sprintf("%s has joined.", name),
	})
	i.g.SyncGame(i.w.BindClientID(cid))
}

// disconnect
func (i *Instance) disconnect(cid ClientID, input InputDisconnect) {
	i.leave(cid, InputLeave{})

	name := i.name[cid]
	delete(i.name, cid)

	i.w.Write(OutputMessage{
		Message: fmt.Sprintf("%s has left.", name),
	})
}

// profile
func (i *Instance) profile(cid ClientID, input InputProfile) {
	// TODO validation
	before := i.name[cid]
	after := input.UserName

	i.name[cid] = after

	i.w.Write(OutputMessage{
		Message: fmt.Sprintf("%s has changed the name to %s.", before, after),
	})
}

// chat
func (i *Instance) chat(cid ClientID, input InputChat) {
	name := i.name[cid]
	message := input.Message

	i.w.Write(OutputChat{
		UserName: i.name[cid],
		Message:  input.Message,
	})
	log.WithFields(logrus.Fields{
		"type":    "chat",
		"name":    name,
		"message": message,
	}).Infof("%s: %s", name, message)
}

// stage
func (i *Instance) stage(cid ClientID, input InputStage) {
	// WIP
	i.g.Clear()
	i.g.Join(UnitGroupAI, "MOB", NewClassTank())
	i.w.Write(OutputStage{})
}

// join
func (i *Instance) join(cid ClientID, input InputJoin) {
	// TODO disable join when a game is in progress
	if _, ok := i.uid[cid]; ok {
		return
	}
	// TODO refactor: make ClassFactory
	var class *Class
	switch input.ClassName {
	case "Assassin":
		class = NewClassAssassin()
	case "Disabler":
		class = NewClassDisabler()
	case "Healer":
		class = NewClassHealer()
	case "Mage":
		class = NewClassMage()
	case "Tank":
		class = NewClassTank()
	default:
		return
	}
	uid, err := i.g.Join(UnitGroupPlayer, UnitName(i.name[cid]), class)
	if err != nil {
		log.WithFields(logrus.Fields{
			"cid":  cid,
			"type": "join",
		}).Warn(err)
		return
	}
	i.uid[cid] = uid
}

// leave
func (i *Instance) leave(cid ClientID, input InputLeave) {
	if _, ok := i.uid[cid]; !ok {
		return
	}
	if err := i.g.Leave(i.uid[cid]); err != nil {
		log.WithFields(logrus.Fields{
			"cid":  cid,
			"type": "leave",
		}).Warn(err)
		return
	}
	delete(i.uid, cid)
}

// ability
func (i *Instance) ability(cid ClientID, input InputAbility) {
	if _, ok := i.uid[cid]; !ok {
		return
	}
	i.g.Ability(i.uid[cid], input.ObjectUnitID, input.AbilityName)
}
<commit_msg>Fix stage API<commit_after>package main

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

	"github.com/Sirupsen/logrus"
)

type UserName string

type Instance struct {
	time *InstanceTime
	name map[ClientID]UserName
	uid  map[ClientID]UnitID

	g *Game
	r InstanceInput
	w InstanceOutputWriter
}

// NewInstance returns a Instance
func NewInstance(r InstanceInput, w InstanceOutputWriter) *Instance {
	time := new(InstanceTime)
	return &Instance{
		time: time,
		name: make(map[ClientID]UserName),
		uid:  make(map[ClientID]UnitID),

		g: NewGame(time, w),
		r: r,
		w: w,
	}
}

// Run starts the instance routine
func (i *Instance) Run() {
	t := time.Tick(RealGameTick)
	for {
		select {
		case <-t:
			*i.time = i.time.Add(GameTick)
			if i.time.IsRegenerationTick() {
				i.sync(i.w)
				i.g.PerformRegenerationTick()
			}
			if i.time.IsPeriodicalTick() {
				i.g.PerformPeriodicalTick()
			}
			i.g.PerformGameTick()
		case input, ok := <-i.r:
			if !ok {
				log.Fatal("Cannot read from the input channel")
			}
			cid := input.ClientID
			switch input := input.Input.(type) {
			case InputConnect:
				i.connect(cid, input)
			case InputDisconnect:
				i.disconnect(cid, input)
			case InputProfile:
				i.profile(cid, input)
			case InputChat:
				i.chat(cid, input)
			case InputStage:
				i.stage(cid, input)
			case InputJoin:
				i.join(cid, input)
			case InputLeave:
				i.leave(cid, input)
			case InputAbility:
				i.ability(cid, input)
			case InputInterrupt:
				// TODO WIP
			default:
				log.Fatal("Unknown input type")
			}
		}
	}
}

// generateName returns a random user name
func (i *Instance) generateName() UserName {
	return UserName(fmt.Sprintf("user%03d", rand.Intn(1000)))
}

// sync sends a OutputSync message
func (i *Instance) sync(w InstanceOutputWriter) {
	w.Write(OutputSync{
		InstanceTime: *i.time,
	})
}

// connect
func (i *Instance) connect(cid ClientID, input InputConnect) {
	name := i.generateName()
	i.name[cid] = name

	i.sync(i.w.BindClientID(cid))
	i.w.BindClientID(cid).Write(OutputMessage{
		Message: "Welcome to Crescent!",
	})
	i.w.Write(OutputMessage{
		Message: fmt.Sprintf("%s has joined.", name),
	})
	i.g.SyncGame(i.w.BindClientID(cid))
}

// disconnect
func (i *Instance) disconnect(cid ClientID, input InputDisconnect) {
	i.leave(cid, InputLeave{})

	name := i.name[cid]
	delete(i.name, cid)

	i.w.Write(OutputMessage{
		Message: fmt.Sprintf("%s has left.", name),
	})
}

// profile
func (i *Instance) profile(cid ClientID, input InputProfile) {
	// TODO validation
	before := i.name[cid]
	after := input.UserName

	i.name[cid] = after

	i.w.Write(OutputMessage{
		Message: fmt.Sprintf("%s has changed the name to %s.", before, after),
	})
}

// chat
func (i *Instance) chat(cid ClientID, input InputChat) {
	name := i.name[cid]
	message := input.Message

	i.w.Write(OutputChat{
		UserName: i.name[cid],
		Message:  input.Message,
	})
	log.WithFields(logrus.Fields{
		"type":    "chat",
		"name":    name,
		"message": message,
	}).Infof("%s: %s", name, message)
}

// stage
func (i *Instance) stage(cid ClientID, input InputStage) {
	// WIP
	i.w.Write(OutputStage{})
	i.g.Clear()
	i.g.Join(UnitGroupAI, "MOB", NewClassTank())
}

// join
func (i *Instance) join(cid ClientID, input InputJoin) {
	// TODO disable join when a game is in progress
	if _, ok := i.uid[cid]; ok {
		return
	}
	// TODO refactor: make ClassFactory
	var class *Class
	switch input.ClassName {
	case "Assassin":
		class = NewClassAssassin()
	case "Disabler":
		class = NewClassDisabler()
	case "Healer":
		class = NewClassHealer()
	case "Mage":
		class = NewClassMage()
	case "Tank":
		class = NewClassTank()
	default:
		return
	}
	uid, err := i.g.Join(UnitGroupPlayer, UnitName(i.name[cid]), class)
	if err != nil {
		log.WithFields(logrus.Fields{
			"cid":  cid,
			"type": "join",
		}).Warn(err)
		return
	}
	i.uid[cid] = uid
}

// leave
func (i *Instance) leave(cid ClientID, input InputLeave) {
	if _, ok := i.uid[cid]; !ok {
		return
	}
	if err := i.g.Leave(i.uid[cid]); err != nil {
		log.WithFields(logrus.Fields{
			"cid":  cid,
			"type": "leave",
		}).Warn(err)
		return
	}
	delete(i.uid, cid)
}

// ability
func (i *Instance) ability(cid ClientID, input InputAbility) {
	if _, ok := i.uid[cid]; !ok {
		return
	}
	i.g.Ability(i.uid[cid], input.ObjectUnitID, input.AbilityName)
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"fmt"
	"os"
	"time"
)

func printDuration(d time.Duration) {
	fmt.Printf("\r%02d:%02d:%02d ",
		int(d.Hours())%60,
		int(d.Minutes())%60,
		int(d.Seconds())%60,
	)
}

// The Countdown function prints time remaining relative to a given total (as HH:MM:SS).
func Countdown(ticker *time.Ticker, d time.Duration) {
	start := time.Now()
	printDuration(d)
	for range ticker.C {
		remaining := d - time.Since(start) + time.Second
		if remaining >= 0.0 {
			printDuration(remaining)
		} else {
			fmt.Println()
			os.Exit(0)
		}
	}
}

// The Elapsed function prints elapsed time as HH:MM:SS.
func Elapsed(ticker *time.Ticker) {
	start := time.Now()
	fmt.Printf("\r00:00:00 ")
	for range ticker.C {
		printDuration(time.Since(start))
	}
}

func main() {
	// TODO
	//alarm := flag.String("a", "", "alarm filename")
	countdown := flag.Duration("c", time.Second*0, "countdown (duration)")
	flag.Parse()

	ticker := time.NewTicker(time.Second)

	if *countdown >= time.Second {
		go Countdown(ticker, *countdown)
	} else {
		go Elapsed(ticker)
	}

	var input string
	fmt.Scanln(&input)
}
<commit_msg>Remove unnecessary print statements<commit_after>package main

import (
	"flag"
	"fmt"
	"os"
	"time"
)

func printDuration(d time.Duration) {
	fmt.Printf("\r%02d:%02d:%02d ",
		int(d.Hours())%60,
		int(d.Minutes())%60,
		int(d.Seconds())%60,
	)
}

// The Countdown function prints time remaining relative to a given total (as HH:MM:SS).
func Countdown(ticker *time.Ticker, d time.Duration) {
	start := time.Now()
	for range ticker.C {
		remaining := d - time.Since(start) + time.Second
		if remaining >= 0.0 {
			printDuration(remaining)
		} else {
			fmt.Println()
			os.Exit(0)
		}
	}
}

// The Elapsed function prints elapsed time as HH:MM:SS.
func Elapsed(ticker *time.Ticker) {
	start := time.Now()
	for range ticker.C {
		printDuration(time.Since(start))
	}
}

func main() {
	// TODO
	//alarm := flag.String("a", "", "alarm filename")
	countdown := flag.Duration("c", time.Second*0, "countdown (duration)")
	flag.Parse()

	ticker := time.NewTicker(time.Second)

	if *countdown >= time.Second {
		go Countdown(ticker, *countdown)
	} else {
		go Elapsed(ticker)
	}

	var input string
	fmt.Scanln(&input)
}
<|endoftext|>


<commit_before>package times

import "time"

type Times struct {
    time time.Time
    timezone string
    location Location
}

// This will return an instance of Times the current time localized to UTC
func Now() times.Times{

	return Times{}
}

// This will localixe
func (t Time) Localize( )<commit_msg>making coressponding changes<commit_after>package times

import "time"

type Times struct {
	time     time.Time
	timezone string
	location time.Location
}

// This will return an instance of Times the current time localized to UTC
func Now() Times {

	return Times{}
}

// This will localixe
func (t Times) Localize() {

}
<|endoftext|>


<commit_before>package io

import (
	"fmt"
	"strconv"

	artio "github.com/phil-mansfield/go-artio"
)

type ARTIOBuffer struct {
	open bool
	buf [][3]float32
	sBufs [][][3]float32
	fileset string
}

func NewARTIOBuffer(fileset string) (VectorBuffer, error) {
	h, err := artio.FilesetOpen(fileset, artio.OpenHeader, artio.NullContext)
	if err != nil { return nil, err  }
	defer h.Close()

	numSpecies := h.GetInt(h.Key("num_particle_species"))[0]

	return &ARTIOBuffer{ sBufs: make([][][3]float32, numSpecies) }, nil
}

func (buf *ARTIOBuffer) Read(fileNumStr string) ([][3]float32, error) {
	// Open the file.
	if buf.open { panic("Buffer already open.") }
	buf.open = true

	h, err := artio.FilesetOpen(
		buf.fileset, artio.OpenHeader, artio.NullContext,
	)
	if err != nil { return nil, err  }
	defer h.Close()

	// I'm not sure if this can just be replaced with putting an
	// artio.OpenParticles flag in artio.FilesetOpen(). Someone with more
	// knowledge about ARTIO than me should figure this out.
	err = h.OpenParticles()
	if err != nil { return nil, err}

	// Flag N_BODY particles.
	flags, err := nBodyFlags(h, buf.fileset)
	if err != nil { return nil, err }

	// Get SFC range.
	fIdx, err := strconv.Atoi(fileNumStr)
	fileIdxs := h.GetLong(h.Key("particle_file_sfc_index"))
	sfcStart, sfcEnd := fileIdxs[fIdx], fileIdxs[fIdx + 1] - 1

	// Counts and buffer manipulation. Do the reading.
	sCounts, err := h.CountInRange(sfcStart, sfcEnd)
	totCount := int64(0)
	for i := range sCounts {
		if flags[i] {
			totCount += sCounts[i]
			expandVectors(buf.sBufs[i], int(sCounts[i]))
			err = h.GetPositionsAt(i, sfcStart, sfcEnd, buf.sBufs[i])
			if err != nil { return nil, err }
		}
	}

	// Copy to output buffer.
	expandVectors(buf.buf, int(totCount))
	k := 0
	for j := range buf.sBufs {
		for i := range buf.sBufs[j] {
			buf.buf[i] = buf.sBufs[j][k]
			k++
		}
	}

	return buf.buf, nil
}

func nBodyFlags(h artio.Fileset, fname string) ([]bool, error) {
	speciesLabels := h.GetString(h.Key("particle_species_labels"))
	isNBody, nBodyCount := make([]bool, len(speciesLabels)), 0
	for i := range isNBody {
		isNBody[i] = speciesLabels[i] == "N-BODY"
		nBodyCount++
	}
	if nBodyCount == 0 {
		return nil, fmt.Errorf("ARTIO fileset '%s' does not contain any " +
		"particle species of type 'N-BODY'.", fname)
	}
	return isNBody, nil

}

func (buf *ARTIOBuffer) Close() {
	if !buf.open { panic("Buffer not open.") }
	buf.open = false
}

func (buf *ARTIOBuffer) IsOpen() bool {
	return buf.open
}

func (buf *ARTIOBuffer) ReadHeader(fileNumStr string, out *Header) error {
	xs, err := buf.Read(fileNumStr)

	h, err := artio.FilesetOpen(
		buf.fileset, artio.OpenHeader, artio.NullContext,
	)
	if err != nil { return err }
	defer h.Close()

	out.TotalWidth = h.GetDouble(h.Key("box_size"))[0]
	out.Origin, out.Width = boundingBox(xs, out.TotalWidth)
	out.N = int64(len(xs))
	out.Count = -1

	// I get the cosmology afterwards to aid in debugging.
	switch {
	case !h.HasKey("auni"):
		return fmt.Errorf("ARTIO header does not contain 'auni' field.")
	case !h.HasKey("OmegaM"):
		return fmt.Errorf("ARTIO header does not contain 'OmegaM' field.")
	case !h.HasKey("OmegaL"):
		return fmt.Errorf("ARTIO header does not contain 'OmegaL' field.")
	case !h.HasKey("hubble"):
		return fmt.Errorf("ARTIO header does not contain 'hubble' field.")
	}

	out.Cosmo.Z = 1/h.GetDouble(h.Key("auni"))[0] - 1
	out.Cosmo.OmegaM = h.GetDouble(h.Key("OmegaM"))[0]
	out.Cosmo.OmegaL = h.GetDouble(h.Key("OmegaL"))[0]
	out.Cosmo.H100 = h.GetDouble(h.Key("hubble"))[0]

	return nil
}<commit_msg>Fixed bug in units handling of ARTIO input.<commit_after>package io

import (
	"fmt"
	"strconv"

	"github.com/phil-mansfield/shellfish/cosmo"
	artio "github.com/phil-mansfield/go-artio"
)

type ARTIOBuffer struct {
	open bool
	buf [][3]float32
	sBufs [][][3]float32
	fileset string
}

func NewARTIOBuffer(fileset string) (VectorBuffer, error) {
	h, err := artio.FilesetOpen(fileset, artio.OpenHeader, artio.NullContext)
	if err != nil { return nil, err  }
	defer h.Close()

	numSpecies := h.GetInt(h.Key("num_particle_species"))[0]

	return &ARTIOBuffer{ sBufs: make([][][3]float32, numSpecies) }, nil
}

func (buf *ARTIOBuffer) Read(fileNumStr string) ([][3]float32, error) {
	// Open the file.
	if buf.open { panic("Buffer already open.") }
	buf.open = true

	h, err := artio.FilesetOpen(
		buf.fileset, artio.OpenHeader, artio.NullContext,
	)
	if err != nil { return nil, err  }
	defer h.Close()

	// I'm not sure if this can just be replaced with putting an
	// artio.OpenParticles flag in artio.FilesetOpen(). Someone with more
	// knowledge about ARTIO than me should figure this out.
	err = h.OpenParticles()
	if err != nil { return nil, err}

	// Flag N_BODY particles.
	flags, err := nBodyFlags(h, buf.fileset)
	if err != nil { return nil, err }

	// Get SFC range.
	fIdx, err := strconv.Atoi(fileNumStr)
	fileIdxs := h.GetLong(h.Key("particle_file_sfc_index"))
	sfcStart, sfcEnd := fileIdxs[fIdx], fileIdxs[fIdx + 1] - 1

	// Counts and buffer manipulation. Do the reading.
	sCounts, err := h.CountInRange(sfcStart, sfcEnd)
	totCount := int64(0)
	for i := range sCounts {
		if flags[i] {
			totCount += sCounts[i]
			expandVectors(buf.sBufs[i], int(sCounts[i]))
			err = h.GetPositionsAt(i, sfcStart, sfcEnd, buf.sBufs[i])
			if err != nil { return nil, err }
		}
	}

	// Copy to output buffer.
	expandVectors(buf.buf, int(totCount))
	k := 0
	for j := range buf.sBufs {
		for i := range buf.sBufs[j] {
			buf.buf[i] = buf.sBufs[j][k]
			k++
		}
	}

	if !h.HasKey("hubble") {
		return nil, fmt.Errorf("ARTIO header does not contain 'hubble field.'")
	}
	h100 := h.GetDouble(h.Key("hubble"))[0]
	units := float32(h100) / (cosmo.MpcMks * 100)
	for i := range buf.buf {
		buf.buf[i][0] *= units
		buf.buf[i][1] *= units
		buf.buf[i][2] *= units
	}

	return buf.buf, nil
}

func nBodyFlags(h artio.Fileset, fname string) ([]bool, error) {
	speciesLabels := h.GetString(h.Key("particle_species_labels"))
	isNBody, nBodyCount := make([]bool, len(speciesLabels)), 0
	for i := range isNBody {
		isNBody[i] = speciesLabels[i] == "N-BODY"
		nBodyCount++
	}
	if nBodyCount == 0 {
		return nil, fmt.Errorf("ARTIO fileset '%s' does not contain any " +
		"particle species of type 'N-BODY'.", fname)
	}
	return isNBody, nil

}

func (buf *ARTIOBuffer) Close() {
	if !buf.open { panic("Buffer not open.") }
	buf.open = false
}

func (buf *ARTIOBuffer) IsOpen() bool {
	return buf.open
}

func (buf *ARTIOBuffer) ReadHeader(fileNumStr string, out *Header) error {
	xs, err := buf.Read(fileNumStr)

	h, err := artio.FilesetOpen(
		buf.fileset, artio.OpenHeader, artio.NullContext,
	)
	if err != nil { return err }
	defer h.Close()

	if !h.HasKey("hubble") {
		return fmt.Errorf("ARTIO header does not contain 'hubble' field.")
	}

	out.TotalWidth = h.GetDouble(h.Key("box_size"))[0] *
		(h.GetDouble(h.Key("hubble"))[0] / (cosmo.MpcMks * 100))
	out.Origin, out.Width = boundingBox(xs, out.TotalWidth)
	out.N = int64(len(xs))
	out.Count = -1

	// I get the cosmology afterwards to aid in debugging.
	switch {
	case !h.HasKey("auni"):
		return fmt.Errorf("ARTIO header does not contain 'auni' field.")
	case !h.HasKey("OmegaM"):
		return fmt.Errorf("ARTIO header does not contain 'OmegaM' field.")
	case !h.HasKey("OmegaL"):
		return fmt.Errorf("ARTIO header does not contain 'OmegaL' field.")

	}

	out.Cosmo.Z = 1/h.GetDouble(h.Key("auni"))[0] - 1
	out.Cosmo.OmegaM = h.GetDouble(h.Key("OmegaM"))[0]
	out.Cosmo.OmegaL = h.GetDouble(h.Key("OmegaL"))[0]
	out.Cosmo.H100 = h.GetDouble(h.Key("hubble"))[0]

	if out.Cosmo.H100 > 10 {
		panic("Oops, Phil misunderstood the meaning of an ARTIO field. " +
		"Please submit an issue.")
	}

	panic("Debugging")

	return nil
}<|endoftext|>


<commit_before>package iptrie

import (
	"bytes"
	"strings"
	"testing"
)

type testCaseElement struct {
	key    []byte
	ln     byte
	repl   bool
	result string
}

func (s *testCaseElement) getKey() []uint32 {
	key := make([]uint32, 0, (len(s.key)+3)/4)
	for i := 0; i < len(s.key); i += 4 {
		switch len(s.key) - i {
		case 1:
			key = append(key, uint32(s.key[i])<<24)
		case 2:
			key = append(key, uint32(s.key[i])<<24|uint32(s.key[i+1])<<16)
		case 3:
			key = append(key, uint32(s.key[i])<<24|uint32(s.key[i+1])<<16|uint32(s.key[i+2])<<8)
		default:
			key = append(key, uint32(s.key[i])<<24|uint32(s.key[i+1])<<16|uint32(s.key[i+2])<<8|uint32(s.key[i+3]))
		}
	}
	return key
}

var testCases = [][]testCaseElement{
	{
		{[]byte{1, 2, 3, 0}, 24, true, "root=1.2.3.0/24 (no subtree)\\n"},
		{[]byte{1, 2, 3, 0}, 29, true, "found 1.2.3.0/24 for 1.2.3.0/29\\nb-child 1.2.3.0/29 for 1.2.3.0/24\\n"},
		{[]byte{1, 2, 0, 0}, 16, true, "root=1.2.0.0/16 (uses 1.2.3.0/24 as b-child)\\n"},
		{[]byte{1, 2, 3, 0}, 26, true, "found 1.2.0.0/16 for 1.2.3.0/26\\nfound 1.2.3.0/24 for 1.2.3.0/26\\ninsert b-child 1.2.3.0/26 to 1.2.3.0/24 before 1.2.3.0/29\\n"},
		{[]byte{1, 2, 4, 0}, 26, true, "found 1.2.0.0/16 for 1.2.4.0/26\\ncreated b-dummy 1.2.4.0/21 with 1.2.4.0/26 and 1.2.3.0/24\\ninsert b-child 1.2.4.0/21 to 1.2.0.0/16 before 1.2.3.0/24\\n"},
		{[]byte{1, 3, 0, 0}, 16, true, "created b-dummy 1.3.0.0/15 with 1.3.0.0/16 and 1.2.0.0/16\\nroot=1.3.0.0/15 (uses 1.3.0.0/16 as b-child)\\n"},
	},
}

func TestTreeAppend(t *testing.T) {
	T := new(tree160)
	for _, testcase := range testCases {
		buf := bytes.NewBuffer(nil)
		DEBUG = buf
		for _, s := range testcase {
			T.addRoute(s.getKey(), s.ln, nil, s.repl)
			got := strings.Replace(buf.String(), "\n", "\\n", -1)
			if got != s.result {
				t.Error(got, "!=", s.result)
			}
			buf.Reset()
		}
		DEBUG = nil
	}
	// should find exact and not-exact matches
	for _, testcase := range testCases {
		for _, s := range testcase {
			exact, match, _ := T.findBestMatch(s.getKey(), s.ln)
			if !exact {
				t.Errorf("Incorrect match found for exact search, got %v key while looking for %v", match, s.getKey())
			}
			exact, match, _ = T.findBestMatch(s.getKey(), s.ln+1)
			if exact || match.prefixlen != s.ln {
				t.Errorf("Incorrect match found for not-exact search, got %v key while looking for %v", match, s.getKey())
			}
		}
	}
}
<commit_msg>Made things simpler in basic test<commit_after>package iptrie

import (
	"bytes"
	"strings"
	"testing"
)

type testCaseElement struct {
	key    []byte
	ln     byte
	repl   bool
	result string
}

var testCases = [][]testCaseElement{
	{
		{[]byte{1, 2, 3, 0}, 24, true, "root=1.2.3.0/24 (no subtree)\\n"},
		{[]byte{1, 2, 3, 0}, 29, true, "found 1.2.3.0/24 for 1.2.3.0/29\\nb-child 1.2.3.0/29 for 1.2.3.0/24\\n"},
		{[]byte{1, 2, 0, 0}, 16, true, "root=1.2.0.0/16 (uses 1.2.3.0/24 as b-child)\\n"},
		{[]byte{1, 2, 3, 0}, 26, true, "found 1.2.0.0/16 for 1.2.3.0/26\\nfound 1.2.3.0/24 for 1.2.3.0/26\\ninsert b-child 1.2.3.0/26 to 1.2.3.0/24 before 1.2.3.0/29\\n"},
		{[]byte{1, 2, 4, 0}, 26, true, "found 1.2.0.0/16 for 1.2.4.0/26\\ncreated b-dummy 1.2.4.0/21 with 1.2.4.0/26 and 1.2.3.0/24\\ninsert b-child 1.2.4.0/21 to 1.2.0.0/16 before 1.2.3.0/24\\n"},
		{[]byte{1, 3, 0, 0}, 16, true, "created b-dummy 1.3.0.0/15 with 1.3.0.0/16 and 1.2.0.0/16\\nroot=1.3.0.0/15 (uses 1.3.0.0/16 as b-child)\\n"},
	},
}

func TestTreeAppend(t *testing.T) {
	T := new(tree160)
	for _, testcase := range testCases {
		buf := bytes.NewBuffer(nil)
		DEBUG = buf
		for _, s := range testcase {
			T.addRoute(iptou(s.key, s.ln), s.ln, nil, s.repl)
			got := strings.Replace(buf.String(), "\n", "\\n", -1)
			if got != s.result {
				t.Error(got, "!=", s.result)
			}
			buf.Reset()
		}
		DEBUG = nil
	}
	// should find exact and not-exact matches
	for _, testcase := range testCases {
		for _, s := range testcase {
			exact, match, _ := T.findBestMatch(iptou(s.key, s.ln), s.ln)
			if !exact {
				t.Errorf("Incorrect match found for exact search, got %v key while looking for %v", match, s)
			}
			exact, match, _ = T.findBestMatch(iptou(s.key, s.ln), s.ln+1)
			if exact || match.prefixlen != s.ln {
				t.Errorf("Incorrect match found for not-exact search, got %v key while looking for %v", match, s)
			}
		}
	}
}
<|endoftext|>


<commit_before>package main

import (
	"net"
	"os"
	"fmt"
	"strings"
	"container/list"
	"github.com/thoj/go-mysqlpure"
	"bytes"
	//"time"
)

var waiting *list.List;
var games map[string] Game

type Person struct {
	name string
	con net.Conn
}

type Game struct {
	people map[string] Person
}

func main() {
	waiting = list.New()
	games = make(map[string]Game)
	LogIt("SETUP", "Starting...")

	addr, err := net.ResolveTCPAddr("ip4", ":4849")
	ErrorCheck(err, "Problem resolving TCP address")

	listen, err := net.ListenTCP("tcp", addr)
	ErrorCheck(err, "TCP listening error")

	LogIt("SETUP", "Ready.")

	for{
		connection, err := listen.Accept()
		if(err != nil){
			continue
		}
		LogIt("CONNECTION", "Got new connection")

		go newClient(connection)

	}

	os.Exit(0)
}

func newClient(connect net.Conn){
	LogIt("CONNECTION", "Handling new client")
	var buffer [512]byte

	_, err := connect.Read(buffer[0:])
	if err != nil {
		LogError("ERROR", "Error reading from client", err)
		connect.Close()
		return
	}

	parseCommand(string(bytes.TrimRight(buffer[0:], string(byte(0)))), connect)
	for {
		_, err := connect.Read(buffer[0:])
		if err != nil {
			LogError("ERROR", "Error reading from client", err)
			connect.Close()
			return
		}
		parseCommand(string(bytes.TrimRight(buffer[0:], string(byte(0)))), connect)
	}
}

func parseCommand(com string, connection net.Conn){

	//var response string;
	parts := strings.Split(com, ":")
	dataCon, err := mysql.Connect("tcp", "127.0.0.1:3306", "hhss", "highscores", "hhss")
	ErrorCheck(err, "Could not connect to MySQL database.")

	switch parts[0] {
		case "new":
			checker := new(mysql.MySQLResponse)

			checker, err = dataCon.Query("SELECT username FROM users WHERE username='" + parts[1] + "';")
			if len(checker.FetchRowMap()) > 0{
				var newPerson Person
				newPerson.name = parts[1]
				newPerson.con = connection

				waiting.PushFront(newPerson)

				if waiting.Len() > 1 {
					var p1,p2 Person
					e1 := waiting.Back()
					p1 = e1.Value.(Person)
					waiting.Remove(e1)
					e2 := waiting.Back()
					p2 = e2.Value.(Person)
					waiting.Remove(e2)
					go newGame(p1,p2)
				}
			} else {
				connection.Write([]byte("fail:you don't exist"))
				connection.Close();
			}
		case "move":
			fmt.Println(parts)
			fmt.Println("move:" + parts[1] + ":" + parts[3] + ":" + parts[4])
			 _, err := games[parts[2]].people[parts[1]].con.Write([]byte("move:" + parts[1] + ":" + parts[3] + ":" + parts[4]))
			if ErrorCheck(err, "Could not send new move to client in game " + parts[2]){
				connection.Write([]byte("fail:Could not message opponent."))
			}
			//fmt.Println("%s: MOVED in game %s: %s, %s", parts[1], parts[2], parts[3], parts[4])
		case "finished":
			_, err := games[parts[2]].people[parts[1]].con.Write([]byte("finished:" + parts[2] + ":" + parts[3] + ":" + parts[4]))
			if ErrorCheck(err, "Could not send finished message to client in game " + parts[2]) {
				connection.Write([]byte("fail:Could not message opponent."))
			}
			for _, p := range(games[parts[2]].people){
				p.con.Close();
			}
	}
	dataCon.Quit();
}

func newGame(p1 Person, p2 Person) {
	gameName := p1.name + "AND" + p2.name
	fmt.Println(gameName)

	games[gameName] = Game{make(map[string]Person)}
	games[gameName].people[p1.name] = p2
	games[gameName].people[p2.name] = p1

	p1.con.Write([]byte("partner:" + p2.name + ":" + gameName))
	p2.con.Write([]byte("partner:" + p1.name + ":" + gameName))
}

//LogIt("CONNECTION", "Closing connection to clients " + p1.name + " and " + p2.name)<commit_msg>Added some comments<commit_after>package main

import (
	"net"
	"os"
	"fmt"
	"strings"
	"container/list"
	"github.com/thoj/go-mysqlpure"
	"bytes"
	//"time"
)

var waiting *list.List;
var games map[string] Game

//Holds information pertaining to a single player
type Person struct {
	name string
	con net.Conn
}

//Holds information pertaining to a single game between two players
type Game struct {
	people map[string] Person
}

func main() {
	waiting = list.New()
	games = make(map[string]Game)
	LogIt("SETUP", "Starting...")

	//Setup server socket
	addr, err := net.ResolveTCPAddr("ip4", ":4849")
	ErrorCheck(err, "Problem resolving TCP address")

	//Listen on socket
	listen, err := net.ListenTCP("tcp", addr)
	ErrorCheck(err, "TCP listening error")

	LogIt("SETUP", "Ready.")

	for{
		//Wait for connection
		connection, err := listen.Accept()
		if(err != nil){
			continue
		}
		LogIt("CONNECTION", "Got new connection")

		//Setup connection to new client in it's own thread
		go newClient(connection)

	}

	os.Exit(0)
}

//Called when a new client connects to the server.
//Reads command from the client and sends it to be parsed.
//It then sits awaiting more commands from the client
func newClient(connect net.Conn){
	LogIt("CONNECTION", "Handling new client")
	var buffer [512]byte

	_, err := connect.Read(buffer[0:])
	if err != nil {
		LogError("ERROR", "Error reading from client", err)
		connect.Close()
		return
	}

	parseCommand(string(bytes.TrimRight(buffer[0:], string(byte(0)))), connect)
	for {
		_, err := connect.Read(buffer[0:])
		if err != nil {
			LogError("ERROR", "Error reading from client", err)
			connect.Close()
			return
		}
		parseCommand(string(bytes.TrimRight(buffer[0:], string(byte(0)))), connect)
	}
}

//Parses out client commands
func parseCommand(com string, connection net.Conn){

	//var response string;
	parts := strings.Split(com, ":")
	dataCon, err := mysql.Connect("tcp", "127.0.0.1:3306", "hhss", "highscores", "hhss")
	ErrorCheck(err, "Could not connect to MySQL database.")

	switch parts[0] {
		//Creates a new game or adds user to a game waiting for a partner
		case "new":
			checker := new(mysql.MySQLResponse)

			checker, err = dataCon.Query("SELECT username FROM users WHERE username='" + parts[1] + "';")
			if len(checker.FetchRowMap()) > 0{
				var newPerson Person
				newPerson.name = parts[1]
				newPerson.con = connection

				waiting.PushFront(newPerson)

				if waiting.Len() > 1 {
					var p1,p2 Person
					e1 := waiting.Back()
					p1 = e1.Value.(Person)
					waiting.Remove(e1)
					e2 := waiting.Back()
					p2 = e2.Value.(Person)
					waiting.Remove(e2)
					go newGame(p1,p2)
				}
			} else {
				connection.Write([]byte("fail:you don't exist"))
				connection.Close();
			}
		//Passes along a player's move to another player
		case "move":
			fmt.Println(parts)
			fmt.Println("move:" + parts[1] + ":" + parts[3] + ":" + parts[4])
			 _, err := games[parts[2]].people[parts[1]].con.Write([]byte("move:" + parts[1] + ":" + parts[3] + ":" + parts[4]))
			if ErrorCheck(err, "Could not send new move to client in game " + parts[2]){
				connection.Write([]byte("fail:Could not message opponent."))
			}
			//fmt.Println("%s: MOVED in game %s: %s, %s", parts[1], parts[2], parts[3], parts[4])
		//Passess along a player winning to another player
		case "finished":
			_, err := games[parts[2]].people[parts[1]].con.Write([]byte("finished:" + parts[2] + ":" + parts[3] + ":" + parts[4]))
			if ErrorCheck(err, "Could not send finished message to client in game " + parts[2]) {
				connection.Write([]byte("fail:Could not message opponent."))
			}
			for _, p := range(games[parts[2]].people){
				p.con.Close();
			}
	}
	dataCon.Quit();
}

//Creates new game
func newGame(p1 Person, p2 Person) {
	gameName := p1.name + "AND" + p2.name
	fmt.Println(gameName)

	games[gameName] = Game{make(map[string]Person)}
	games[gameName].people[p1.name] = p2
	games[gameName].people[p2.name] = p1

	p1.con.Write([]byte("partner:" + p2.name + ":" + gameName))
	p2.con.Write([]byte("partner:" + p1.name + ":" + gameName))
}

//LogIt("CONNECTION", "Closing connection to clients " + p1.name + " and " + p2.name)<|endoftext|>


<commit_before>package iter

type Iterator interface {
	Close() error
	Decode(interface{}) error
	Err() error
	Next() bool
}
<commit_msg>updated docs<commit_after>package iter

// Iterator represents a "normal" iterator.
//
// Many of the sub-packages that are part of this export types that fit
// this interface.
//
// Some of those exported type have more methods than just these.
//
// But these can be relied on to exist.
//
// Example Usage
//
//	iterator := //...
//
//	defer iterator.Close()
//
//	for iterator.Next() {
//
//		datum := struct{
//			GivenName  string `iter:"given_name"`
//			FamilyName string `iter:"family_name"`
//			Age        int64  `iter:"age"`
//		}{}
//
//		if err := iterator.Decode(&datum); nil != err {
//			return err
//		}
//
//		//@TODO: do something with `datum`.
//	}
//	if err := iterator.Err(); nil != err {
//		return err
//	}
type Iterator interface {
	Close() error
	Decode(interface{}) error
	Err() error
	Next() bool
}
<|endoftext|>


<commit_before><commit_msg>Add tests for keys.InternalKey<commit_after><|endoftext|>


<commit_before><commit_msg>readcommitted is right protection level, since it's a simple for update (#1271)<commit_after><|endoftext|>


<commit_before>package metric

import (
	"database/sql"
	"database/sql/driver"
)

//go:generate counterfeiter . Conn

type Conn interface {
	Prepare(query string) (driver.Stmt, error)
	Close() error
	Begin() (driver.Tx, error)
}

//go:generate counterfeiter . Driver

type Driver interface {
	Open(name string) (driver.Conn, error)
}

type connectionCountingDriver struct {
	Driver
}

func SetupConnectionCountingDriver(delegateDriverName, sqlDataSource, newDriverName string) {
	// ignoring any connection errors since we only need this to access the driver struct
	delegateDBConn, _ := sql.Open(delegateDriverName, sqlDataSource)
	delegateDBConn.Close()

	connectionCountingDriver := &connectionCountingDriver{delegateDBConn.Driver()}
	sql.Register(newDriverName, connectionCountingDriver)
}

func (d *connectionCountingDriver) Open(name string) (driver.Conn, error) {
	delegateConn, err := d.Driver.Open(name)
	if err != nil {
		return nil, err
	}

	DatabaseConnections.Inc()
	return &connectionCountingConn{delegateConn}, nil
}

type connectionCountingConn struct {
	driver.Conn
}

func (c *connectionCountingConn) Close() error {
	err := c.Conn.Close()
	if err != nil {
		return err
	}

	DatabaseConnections.Dec()
	return nil
}
<commit_msg>prevent nil panic when opening db fails<commit_after>package metric

import (
	"database/sql"
	"database/sql/driver"
)

//go:generate counterfeiter . Conn

type Conn interface {
	Prepare(query string) (driver.Stmt, error)
	Close() error
	Begin() (driver.Tx, error)
}

//go:generate counterfeiter . Driver

type Driver interface {
	Open(name string) (driver.Conn, error)
}

type connectionCountingDriver struct {
	Driver
}

func SetupConnectionCountingDriver(delegateDriverName, sqlDataSource, newDriverName string) {
	delegateDBConn, err := sql.Open(delegateDriverName, sqlDataSource)
	if err == nil {
		// ignoring any connection errors since we only need this to access the driver struct
		delegateDBConn.Close()
	}

	connectionCountingDriver := &connectionCountingDriver{delegateDBConn.Driver()}
	sql.Register(newDriverName, connectionCountingDriver)
}

func (d *connectionCountingDriver) Open(name string) (driver.Conn, error) {
	delegateConn, err := d.Driver.Open(name)
	if err != nil {
		return nil, err
	}

	DatabaseConnections.Inc()
	return &connectionCountingConn{delegateConn}, nil
}

type connectionCountingConn struct {
	driver.Conn
}

func (c *connectionCountingConn) Close() error {
	err := c.Conn.Close()
	if err != nil {
		return err
	}

	DatabaseConnections.Dec()
	return nil
}
<|endoftext|>


<commit_before>// Copyright 2014 tsuru-client authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"errors"
	"fmt"
	"github.com/tsuru/tsuru/cmd"
	"io/ioutil"
	"net/http"
	"os"
)

type pluginInstall struct{}

func (pluginInstall) Info() *cmd.Info {
	return &cmd.Info{
		Name:    "plugin-install",
		Usage:   "plugin-install <plugin-name> <plugin-url>",
		Desc:    "Install tsuru plugins.",
		MinArgs: 2,
	}
}

func (c *pluginInstall) Run(context *cmd.Context, client *cmd.Client) error {
	pluginsDir := cmd.JoinWithUserDir(".tsuru", "plugins")
	err := filesystem().MkdirAll(pluginsDir, 0755)
	if err != nil {
		return err
	}
	pluginName := context.Args[0]
	pluginUrl := context.Args[1]
	pluginPath := cmd.JoinWithUserDir(".tsuru", "plugins", pluginName)
	file, err := filesystem().OpenFile(pluginPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0755)
	if err != nil {
		return err
	}
	resp, err := http.Get(pluginUrl)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	n, err := file.Write(data)
	if err != nil {
		return err
	}
	if n != len(data) {
		return errors.New("Failed to install plugin.")
	}
	fmt.Fprintf(context.Stdout, `Plugin "%s" successfully installed!`+"\n", pluginName)
	return nil
}

type plugin struct{}

func (plugin) Info() *cmd.Info {
	return &cmd.Info{
		Name:    "plugin",
		Usage:   "plugin <plugin-name> [<args>]",
		Desc:    "Execute tsuru plugins.",
		MinArgs: 1,
	}
}

func (c *plugin) Run(context *cmd.Context, client *cmd.Client) error {
	pluginName := context.Args[0]
	pluginPath := cmd.JoinWithUserDir(".tsuru", "plugins", pluginName)
	err := executor().Execute(pluginPath, context.Args[1:], nil, context.Stdout, context.Stderr)
	if err != nil {
		return err
	}
	return nil
}

type pluginRemove struct{}

func (pluginRemove) Info() *cmd.Info {
	return &cmd.Info{
		Name:    "plugin-remove",
		Usage:   "plugin-remove <plugin-name>",
		Desc:    "Remove tsuru plugins.",
		MinArgs: 1,
	}
}

func (c *pluginRemove) Run(context *cmd.Context, client *cmd.Client) error {
	pluginName := context.Args[0]
	pluginPath := cmd.JoinWithUserDir(".tsuru", "plugins", pluginName)
	err := filesystem().Remove(pluginPath)
	if err != nil {
		return err
	}
	fmt.Fprintf(context.Stdout, `Plugin "%s" successfully removed!`+"\n", pluginName)
	return nil
}

type pluginList struct{}

func (pluginList) Info() *cmd.Info {
	return &cmd.Info{
		Name:    "plugin-list",
		Usage:   "plugin-list",
		Desc:    "List installed tsuru plugins.",
		MinArgs: 0,
	}
}

func (c *pluginList) Run(context *cmd.Context, client *cmd.Client) error {
	pluginsPath := cmd.JoinWithUserDir(".tsuru", "plugins")
	plugins, _ := ioutil.ReadDir(pluginsPath)
	for _, p := range plugins {
		fmt.Println(p.Name())
	}
	return nil
}
<commit_msg>plugin: using new opts for executor.<commit_after>// Copyright 2014 tsuru-client authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"errors"
	"fmt"
	"github.com/tsuru/tsuru/cmd"
	"github.com/tsuru/tsuru/exec"
	"io/ioutil"
	"net/http"
	"os"
)

type pluginInstall struct{}

func (pluginInstall) Info() *cmd.Info {
	return &cmd.Info{
		Name:    "plugin-install",
		Usage:   "plugin-install <plugin-name> <plugin-url>",
		Desc:    "Install tsuru plugins.",
		MinArgs: 2,
	}
}

func (c *pluginInstall) Run(context *cmd.Context, client *cmd.Client) error {
	pluginsDir := cmd.JoinWithUserDir(".tsuru", "plugins")
	err := filesystem().MkdirAll(pluginsDir, 0755)
	if err != nil {
		return err
	}
	pluginName := context.Args[0]
	pluginUrl := context.Args[1]
	pluginPath := cmd.JoinWithUserDir(".tsuru", "plugins", pluginName)
	file, err := filesystem().OpenFile(pluginPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0755)
	if err != nil {
		return err
	}
	resp, err := http.Get(pluginUrl)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	n, err := file.Write(data)
	if err != nil {
		return err
	}
	if n != len(data) {
		return errors.New("Failed to install plugin.")
	}
	fmt.Fprintf(context.Stdout, `Plugin "%s" successfully installed!`+"\n", pluginName)
	return nil
}

type plugin struct{}

func (plugin) Info() *cmd.Info {
	return &cmd.Info{
		Name:    "plugin",
		Usage:   "plugin <plugin-name> [<args>]",
		Desc:    "Execute tsuru plugins.",
		MinArgs: 1,
	}
}

func (c *plugin) Run(context *cmd.Context, client *cmd.Client) error {
	pluginName := context.Args[0]
	pluginPath := cmd.JoinWithUserDir(".tsuru", "plugins", pluginName)
	opts := exec.ExecuteOptions{
		Cmd:    pluginPath,
		Args:   context.Args[1:],
		Stdout: context.Stdout,
		Stderr: context.Stderr,
	}
	err := executor().Execute(opts)
	if err != nil {
		return err
	}
	return nil
}

type pluginRemove struct{}

func (pluginRemove) Info() *cmd.Info {
	return &cmd.Info{
		Name:    "plugin-remove",
		Usage:   "plugin-remove <plugin-name>",
		Desc:    "Remove tsuru plugins.",
		MinArgs: 1,
	}
}

func (c *pluginRemove) Run(context *cmd.Context, client *cmd.Client) error {
	pluginName := context.Args[0]
	pluginPath := cmd.JoinWithUserDir(".tsuru", "plugins", pluginName)
	err := filesystem().Remove(pluginPath)
	if err != nil {
		return err
	}
	fmt.Fprintf(context.Stdout, `Plugin "%s" successfully removed!`+"\n", pluginName)
	return nil
}

type pluginList struct{}

func (pluginList) Info() *cmd.Info {
	return &cmd.Info{
		Name:    "plugin-list",
		Usage:   "plugin-list",
		Desc:    "List installed tsuru plugins.",
		MinArgs: 0,
	}
}

func (c *pluginList) Run(context *cmd.Context, client *cmd.Client) error {
	pluginsPath := cmd.JoinWithUserDir(".tsuru", "plugins")
	plugins, _ := ioutil.ReadDir(pluginsPath)
	for _, p := range plugins {
		fmt.Println(p.Name())
	}
	return nil
}
<|endoftext|>


<commit_before>// Copyright © 2015-2017 Go Opus Authors (see AUTHORS file)
//
// License for use of this code is detailed in the LICENSE file

package opus

import (
	"testing"
)

func TestDecoderNew(t *testing.T) {
	dec, err := NewDecoder(48000, 1)
	if err != nil || dec == nil {
		t.Errorf("Error creating new decoder: %v", err)
	}
	dec, err = NewDecoder(12345, 1)
	if err == nil || dec != nil {
		t.Errorf("Expected error for illegal samplerate 12345")
	}
}

func TestDecoderUnitialized(t *testing.T) {
	var dec Decoder
	_, err := dec.Decode(nil, nil)
	if err != errDecUninitialized {
		t.Errorf("Expected \"unitialized decoder\" error: %v", err)
	}
	_, err = dec.DecodeFloat32(nil, nil)
	if err != errDecUninitialized {
		t.Errorf("Expected \"unitialized decoder\" error: %v", err)
	}
}

func TestDecoder_GetLastPacketDuration(t *testing.T) {
	const G4 = 391.995
	const SAMPLE_RATE = 48000
	const FRAME_SIZE_MS = 60
	const FRAME_SIZE = SAMPLE_RATE * FRAME_SIZE_MS / 1000
	pcm := make([]int16, FRAME_SIZE)
	enc, err := NewEncoder(SAMPLE_RATE, 1, AppVoIP)
	if err != nil || enc == nil {
		t.Fatalf("Error creating new encoder: %v", err)
	}
	addSine(pcm, SAMPLE_RATE, G4)

	data := make([]byte, 1000)
	n, err := enc.Encode(pcm, data)
	if err != nil {
		t.Fatalf("Couldn't encode data: %v", err)
	}
	data = data[:n]

	dec, err := NewDecoder(SAMPLE_RATE, 1)
	if err != nil || dec == nil {
		t.Fatalf("Error creating new decoder: %v", err)
	}
	n, err = dec.Decode(data, pcm)
	if err != nil {
		t.Fatalf("Couldn't decode data: %v", err)
	}
	samples, err := dec.LastPacketDuration()
	if err!=nil{
		t.Fatalf("Couldn't get last packet duration: %v",err)
	}
	if samples!=n{
		t.Fatalf("Wrong duration length. Expected %d. Got %d", n, samples)
	}
}
<commit_msg>ran gofmt<commit_after>// Copyright © 2015-2017 Go Opus Authors (see AUTHORS file)
//
// License for use of this code is detailed in the LICENSE file

package opus

import (
	"testing"
)

func TestDecoderNew(t *testing.T) {
	dec, err := NewDecoder(48000, 1)
	if err != nil || dec == nil {
		t.Errorf("Error creating new decoder: %v", err)
	}
	dec, err = NewDecoder(12345, 1)
	if err == nil || dec != nil {
		t.Errorf("Expected error for illegal samplerate 12345")
	}
}

func TestDecoderUnitialized(t *testing.T) {
	var dec Decoder
	_, err := dec.Decode(nil, nil)
	if err != errDecUninitialized {
		t.Errorf("Expected \"unitialized decoder\" error: %v", err)
	}
	_, err = dec.DecodeFloat32(nil, nil)
	if err != errDecUninitialized {
		t.Errorf("Expected \"unitialized decoder\" error: %v", err)
	}
}

func TestDecoder_GetLastPacketDuration(t *testing.T) {
	const G4 = 391.995
	const SAMPLE_RATE = 48000
	const FRAME_SIZE_MS = 60
	const FRAME_SIZE = SAMPLE_RATE * FRAME_SIZE_MS / 1000
	pcm := make([]int16, FRAME_SIZE)
	enc, err := NewEncoder(SAMPLE_RATE, 1, AppVoIP)
	if err != nil || enc == nil {
		t.Fatalf("Error creating new encoder: %v", err)
	}
	addSine(pcm, SAMPLE_RATE, G4)

	data := make([]byte, 1000)
	n, err := enc.Encode(pcm, data)
	if err != nil {
		t.Fatalf("Couldn't encode data: %v", err)
	}
	data = data[:n]

	dec, err := NewDecoder(SAMPLE_RATE, 1)
	if err != nil || dec == nil {
		t.Fatalf("Error creating new decoder: %v", err)
	}
	n, err = dec.Decode(data, pcm)
	if err != nil {
		t.Fatalf("Couldn't decode data: %v", err)
	}
	samples, err := dec.LastPacketDuration()
	if err != nil {
		t.Fatalf("Couldn't get last packet duration: %v", err)
	}
	if samples != n {
		t.Fatalf("Wrong duration length. Expected %d. Got %d", n, samples)
	}
}
<|endoftext|>