<commit_before>package client

// Common object elements

type (
	UID             string
	FinalizerName   string
	ConditionStatus string

	TypeMeta struct {
		Kind       string `json:"kind,omitempty"`
		APIVersion string `json:"apiVersion,omitempty"`
	}

	ObjectMeta struct {
		Name            string            `json:"name,omitempty"`
		Namespace       string            `json:"namespace,omitempty"`
		SelfLink        string            `json:"selfLink,omitempty"`
		UID             UID               `json:"uid,omitempty"`
		ResourceVersion string            `json:"resourceVersion,omitempty"`
		Generation      int64             `json:"generation,omitempty"`
		Labels          map[string]string `json:"labels,omitempty"`
		Annotations     map[string]string `json:"annotations,omitempty"`
	}

	ListMeta struct {
		SelfLink        string `json:"selfLink,omitempty"`
		ResourceVersion string `json:"resourceVersion,omitempty"`
	}

	ObjectReference struct {
		Kind            string `json:"kind,omitempty"`
		Namespace       string `json:"namespace,omitempty"`
		Name            string `json:"name,omitempty"`
		UID             UID    `json:"uid,omitempty"`
		APIVersion      string `json:"apiVersion,omitempty"`
		ResourceVersion string `json:"resourceVersion,omitempty"`
		FieldPath       string `json:"fieldPath,omitempty"`
	}

	LocalObjectReference struct {
		Name string
	}

	ObjectFieldSelector struct {
		APIVersion string `json:"apiVersion"`
		FieldPath  string `json:"fieldPath"`
	}

	ConfigMapKeySelector struct {
		LocalObjectReference `json:",inline"`
		Key                  string `json:"key"`
	}

	SecretKeySelector struct {
		LocalObjectReference `json:",inline"`
		Key                  string `json:"key"`
	}

	LabelSelector struct {
		// matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels
		// map is equivalent to an element of matchExpressions, whose key field is "key", the
		// operator is "In", and the values array contains only "value". The requirements are ANDed.
		MatchLabels map[string]string `json:"matchLabels,omitempty" protobuf:"bytes,1,rep,name=matchLabels"`
	}

	FieldSelector map[string]string

	Object interface {
		GetKind() string
	}
	NamespacedObject interface {
		Object
		GetNamespace() string
		GetAnnotations() map[string]string
	}
	ListObject interface {
		Object
		GetItems()
	}
)

func (t *TypeMeta) GetKind() string {
	return t.Kind
}

func (o *ObjectMeta) GetNamespace() string {
	return o.Namespace
}

func (o *ObjectMeta) GetAnnotations() map[string]string {
	return o.Annotations
}
<commit_msg>Add metadata helpers (#7)<commit_after>package client

// Common object elements

type (
	UID             string
	FinalizerName   string
	ConditionStatus string

	TypeMeta struct {
		Kind       string `json:"kind,omitempty"`
		APIVersion string `json:"apiVersion,omitempty"`
	}

	ObjectMeta struct {
		Name            string            `json:"name,omitempty"`
		Namespace       string            `json:"namespace,omitempty"`
		SelfLink        string            `json:"selfLink,omitempty"`
		UID             UID               `json:"uid,omitempty"`
		ResourceVersion string            `json:"resourceVersion,omitempty"`
		Generation      int64             `json:"generation,omitempty"`
		Labels          map[string]string `json:"labels,omitempty"`
		Annotations     map[string]string `json:"annotations,omitempty"`
	}

	ListMeta struct {
		SelfLink        string `json:"selfLink,omitempty"`
		ResourceVersion string `json:"resourceVersion,omitempty"`
	}

	ObjectReference struct {
		Kind            string `json:"kind,omitempty"`
		Namespace       string `json:"namespace,omitempty"`
		Name            string `json:"name,omitempty"`
		UID             UID    `json:"uid,omitempty"`
		APIVersion      string `json:"apiVersion,omitempty"`
		ResourceVersion string `json:"resourceVersion,omitempty"`
		FieldPath       string `json:"fieldPath,omitempty"`
	}

	LocalObjectReference struct {
		Name string
	}

	ObjectFieldSelector struct {
		APIVersion string `json:"apiVersion"`
		FieldPath  string `json:"fieldPath"`
	}

	ConfigMapKeySelector struct {
		LocalObjectReference `json:",inline"`
		Key                  string `json:"key"`
	}

	SecretKeySelector struct {
		LocalObjectReference `json:",inline"`
		Key                  string `json:"key"`
	}

	LabelSelector struct {
		// matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels
		// map is equivalent to an element of matchExpressions, whose key field is "key", the
		// operator is "In", and the values array contains only "value". The requirements are ANDed.
		MatchLabels map[string]string `json:"matchLabels,omitempty" protobuf:"bytes,1,rep,name=matchLabels"`
	}

	FieldSelector map[string]string

	Object interface {
		GetKind() string
		GetAnnotations() map[string]string
		GetLabels() map[string]string
		SetLabels(labels map[string]string)
	}

	NamespacedObject interface {
		Object
		GetNamespace() string
	}
	ListObject interface {
		Object
		GetItems()
	}
)

func (t *TypeMeta) GetKind() string {
	return t.Kind
}

func (o *ObjectMeta) GetNamespace() string {
	return o.Namespace
}

func (o *ObjectMeta) GetAnnotations() map[string]string {
	return o.Annotations
}

func (o *ObjectMeta) GetLabels() map[string]string {
	return o.Labels
}

func (o *ObjectMeta) SetLabels(labels map[string]string) {
	o.Labels = labels
}
<|endoftext|>


<commit_before>package common

import (
	"fmt"
	"net/http"
	"net/http/httputil"
	"net/url"
	"regexp"
	"strings"
	"time"
)

func ValidBarcode8(s string) bool {
	re := regexp.MustCompile("^[A-Z0-9]{8,8}$")
	return re.MatchString(s)
}

func ValidBarcode7(s string) bool {
	re := regexp.MustCompile("^[A-Z0-9]{7,7}$")
	return re.MatchString(s)
}

func ValidCarton20(s string) bool {
	re := regexp.MustCompile("^[0-9]{20,20}$")
	return re.MatchString(s)
}

func ReverseProxy(proxyPort string, pathMap map[string]string) {

	for urlPath, targetPort := range pathMap {
		u, _ := url.Parse("http://127.0.0.1:" + targetPort)
		http.Handle(urlPath, httputil.NewSingleHostReverseProxy(u))
	}

	http.ListenAndServe(":"+proxyPort, nil)

}

func TimeNowString() string {
	return fmt.Sprintf("%v", time.Unix(0, time.Now().UnixNano()/(int64(time.Millisecond)/int64(time.Nanosecond))*int64(time.Millisecond)))[:23]
}

func EscapeLatex(s string) string {
	s2 := strings.Replace(s, "\\", "\\textbackslash", -1)
	s2 = strings.Replace(s2, "&", "\\&", -1)
	s2 = strings.Replace(s2, "%", "\\%", -1)
	s2 = strings.Replace(s2, "$", "\\$", -1)
	s2 = strings.Replace(s2, "#", "\\#", -1)
	s2 = strings.Replace(s2, "_", "\\_", -1)
	s2 = strings.Replace(s2, "", "\\$", -1)
	s2 = strings.Replace(s2, "{", "\\{", -1)
	s2 = strings.Replace(s2, "}", "\\}", -1)
	s2 = strings.Replace(s2, "~", "\\textasciitilde", -1)
	return strings.Replace(s2, "^", "\\textasciicircum", -1)

}
<commit_msg>added PadZero<commit_after>package common

import (
	"fmt"
	"net/http"
	"net/http/httputil"
	"net/url"
	"regexp"
	"strings"
	"time"
)

func ValidBarcode8(s string) bool {
	re := regexp.MustCompile("^[A-Z0-9]{8,8}$")
	return re.MatchString(s)
}

func ValidBarcode7(s string) bool {
	re := regexp.MustCompile("^[A-Z0-9]{7,7}$")
	return re.MatchString(s)
}

func ValidCarton20(s string) bool {
	re := regexp.MustCompile("^[0-9]{20,20}$")
	return re.MatchString(s)
}

func ReverseProxy(proxyPort string, pathMap map[string]string) {

	for urlPath, targetPort := range pathMap {
		u, _ := url.Parse("http://127.0.0.1:" + targetPort)
		http.Handle(urlPath, httputil.NewSingleHostReverseProxy(u))
	}

	http.ListenAndServe(":"+proxyPort, nil)

}

func TimeNowString() string {
	return fmt.Sprintf("%v", time.Unix(0, time.Now().UnixNano()/(int64(time.Millisecond)/int64(time.Nanosecond))*int64(time.Millisecond)))[:23]
}

func EscapeLatex(s string) string {
	s2 := strings.Replace(s, "\\", "\\textbackslash", -1)
	s2 = strings.Replace(s2, "&", "\\&", -1)
	s2 = strings.Replace(s2, "%", "\\%", -1)
	s2 = strings.Replace(s2, "$", "\\$", -1)
	s2 = strings.Replace(s2, "#", "\\#", -1)
	s2 = strings.Replace(s2, "_", "\\_", -1)
	s2 = strings.Replace(s2, "{", "\\{", -1)
	s2 = strings.Replace(s2, "}", "\\}", -1)
	s2 = strings.Replace(s2, "~", "\\textasciitilde", -1)
	return strings.Replace(s2, "^", "\\textasciicircum", -1)

}

func PadZero(s string) string {
	if s[0] == '.' {
		return "0" + s
	} else {
		return s
	}
}
<|endoftext|>


<commit_before>package serverscommands

import (
	"github.com/jrperritt/rack/internal/github.com/codegangsta/cli"
	"github.com/jrperritt/rack/commands/serverscommands/flavorcommands"
	"github.com/jrperritt/rack/commands/serverscommands/imagecommands"
	"github.com/jrperritt/rack/commands/serverscommands/instancecommands"
	"github.com/jrperritt/rack/commands/serverscommands/keypaircommands"
)

// Get returns all the commands allowed for a `servers` request.
func Get() []cli.Command {
	return []cli.Command{
		{
			Name:        "instance",
			Usage:       "Used for Server Instance operations",
			Subcommands: instancecommands.Get(),
		},
		{
			Name:        "image",
			Usage:       "Used for Server Image operations",
			Subcommands: imagecommands.Get(),
		},
		{
			Name:        "flavor",
			Usage:       "Used for Server Flavor operations",
			Subcommands: flavorcommands.Get(),
		},
		{
			Name:        "keypair",
			Usage:       "Used for Server Keypair operations",
			Subcommands: keypaircommands.Get(),
		},
	}
}
<commit_msg>Flesh out the servers section.<commit_after>package serverscommands

import (
	"github.com/jrperritt/rack/commands/serverscommands/flavorcommands"
	"github.com/jrperritt/rack/commands/serverscommands/imagecommands"
	"github.com/jrperritt/rack/commands/serverscommands/instancecommands"
	"github.com/jrperritt/rack/commands/serverscommands/keypaircommands"
	"github.com/jrperritt/rack/internal/github.com/codegangsta/cli"
)

// Get returns all the commands allowed for a `servers` request.
func Get() []cli.Command {
	return []cli.Command{
		{
			Name:        "instance",
			Usage:       "Servers.",
			Subcommands: instancecommands.Get(),
		},
		{
			Name:        "image",
			Usage:       "Base operating system layout for a server.",
			Subcommands: imagecommands.Get(),
		},
		{
			Name:        "flavor",
			Usage:       "Resource allocations for servers.",
			Subcommands: flavorcommands.Get(),
		},
		{
			Name:        "keypair",
			Usage:       "SSH keypairs for accessing servers.",
			Subcommands: keypaircommands.Get(),
		},
	}
}
<|endoftext|>


<commit_before>package mithril

import (
	"database/sql"
	"log"

	"github.com/lib/pq"
)

type PostgreSQLHandler struct {
	connUri     string
	db          *sql.DB
	nextHandler Handler
}

func NewPostgreSQLHandler(connUri string, next Handler) *PostgreSQLHandler {
	pgHandler := &PostgreSQLHandler{connUri: connUri}
	pgHandler.SetNextHandler(next)
	return pgHandler
}

func (me *PostgreSQLHandler) SetNextHandler(handler Handler) {
	me.nextHandler = handler
}

func (me *PostgreSQLHandler) Init() error {
	var err error

	if err = me.ensureConnected(); err != nil {
		return err
	}

	if err = me.ensureSchemaPresent(); err != nil {
		return err
	}

	log.Println("PostgreSQL handler initialized")

	if me.nextHandler != nil {
		return me.nextHandler.Init()
	}

	return nil
}

func (me *PostgreSQLHandler) HandleRequest(req Request) error {
	var err error

	if err = me.ensureConnected(); err != nil {
		return err
	}

	log.Println("PostgreSQLHandler not really handling request")
	if err := me.selectNow(); err != nil {
		return err
	}

	if me.nextHandler != nil {
		return me.nextHandler.HandleRequest(req)
	}

	return nil
}

func (me *PostgreSQLHandler) ensureConnected() error {
	if me.isConnected() {
		return nil
	}

	return me.establishConnection()
}

func (me *PostgreSQLHandler) isConnected() bool {
	if me.db == nil {
		return false
	}

	if me.selectNow() != nil {
		return false
	}

	return true
}

func (me *PostgreSQLHandler) selectNow() error {
	_, err := me.db.Query("SELECT now()")

	if err != nil {
		log.Println("PostgreSQL failed to execute 'SELECT now()':", err)
		log.Println("Is PostgreSQL running?")
	}

	return err
}

func (me *PostgreSQLHandler) establishConnection() error {
	var (
		connStr string
		err     error
		db      *sql.DB
	)

	if connStr, err = pq.ParseURL(me.connUri); err != nil {
		return err
	}

	if db, err = sql.Open("postgres", connStr); err != nil {
		return err
	}

	me.db = db
	return me.selectNow()
}

func (me *PostgreSQLHandler) ensureSchemaPresent() error {
	// TODO should this delegate to some kind of schema-checking thingydoo?
	return nil
}
<commit_msg>Cutting down on pg ping noise and making the query more obviously ours<commit_after>package mithril

import (
	"database/sql"
	"log"

	"github.com/lib/pq"
)

type PostgreSQLHandler struct {
	connUri     string
	db          *sql.DB
	nextHandler Handler
}

func NewPostgreSQLHandler(connUri string, next Handler) *PostgreSQLHandler {
	pgHandler := &PostgreSQLHandler{connUri: connUri}
	pgHandler.SetNextHandler(next)
	return pgHandler
}

func (me *PostgreSQLHandler) SetNextHandler(handler Handler) {
	me.nextHandler = handler
}

func (me *PostgreSQLHandler) Init() error {
	var err error

	if err = me.ensureConnected(); err != nil {
		return err
	}

	if err = me.ensureSchemaPresent(); err != nil {
		return err
	}

	log.Println("PostgreSQL handler initialized")

	if me.nextHandler != nil {
		return me.nextHandler.Init()
	}

	return nil
}

func (me *PostgreSQLHandler) HandleRequest(req Request) error {
	log.Println("PostgreSQLHandler not really handling request")

	if me.nextHandler != nil {
		return me.nextHandler.HandleRequest(req)
	}

	return nil
}

func (me *PostgreSQLHandler) ensureConnected() error {
	if me.isConnected() {
		return nil
	}

	return me.establishConnection()
}

func (me *PostgreSQLHandler) isConnected() bool {
	if me.db == nil {
		return false
	}

	if me.selectNow() != nil {
		return false
	}

	return true
}

func (me *PostgreSQLHandler) selectNow() error {
	_, err := me.db.Query(`SELECT now() "mithril ping test";`)

	if err != nil {
		log.Println("PostgreSQL failed to execute 'SELECT now()':", err)
		log.Println("Is PostgreSQL running?")
	}

	return err
}

func (me *PostgreSQLHandler) establishConnection() error {
	var (
		connStr string
		err     error
		db      *sql.DB
	)

	if connStr, err = pq.ParseURL(me.connUri); err != nil {
		return err
	}

	if db, err = sql.Open("postgres", connStr); err != nil {
		return err
	}

	me.db = db
	return me.selectNow()
}

func (me *PostgreSQLHandler) ensureSchemaPresent() error {
	// TODO should this delegate to some kind of schema-checking thingydoo?
	return nil
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"encoding/json"
	"flag"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"net/http/cookiejar"
	"net/http/httptest"
	"net/url"
	"os"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	"github.com/catatsuy/isucon6-final/portal/job"
)

var s *httptest.Server

func TestMain(m *testing.M) {
	*startsAtHour = -1
	*endsAtHour = -1

	flag.Parse()
	err := initWeb()
	if err != nil {
		log.Fatal(err)
	}

	s = httptest.NewServer(buildMux())
	n := m.Run()
	s.Close()
	os.Exit(n)
}

type testHTTPClient struct {
	*http.Client
	*testing.T
}

func (c *testHTTPClient) Must(resp *http.Response, err error) *http.Response {
	require.NoError(c.T, err)
	return resp
}

func newTestClient(t *testing.T) *testHTTPClient {
	jar, _ := cookiejar.New(nil)
	return &testHTTPClient{
		Client: &http.Client{Jar: jar},
		T:      t,
	}
}

func TestLogin(t *testing.T) {
	jar, _ := cookiejar.New(nil)
	cli := &http.Client{Jar: jar}

	resp, err := cli.PostForm(s.URL+"/login", url.Values{"team_id": {"26"}, "password": {"p6aYuUempoticryg"}})
	require.NoError(t, err)
	require.Equal(t, "/", resp.Request.URL.Path)
}

func readAll(r io.Reader) string {
	b, _ := ioutil.ReadAll(r)
	return string(b)
}

func benchGetJob(bench *testHTTPClient) *job.Job {
	resp := bench.Must(bench.Post(s.URL+"/mBGWHqBVEjUSKpBF/job/new", "", nil))
	if !assert.Equal(bench.T, http.StatusOK, resp.StatusCode) {
		return nil
	}

	var j job.Job
	err := json.NewDecoder(resp.Body).Decode(&j)
	require.NoError(bench.T, err)

	return &j
}

func benchPostResult(bench *testHTTPClient, j *job.Job, output *job.Output) {
	time.Sleep(1 * time.Second)

	result := job.Result{
		Job:    j,
		Output: output,
		Stderr: "",
	}
	resultJSON, err := json.Marshal(result)
	require.NoError(bench.T, err)

	resp := bench.Must(bench.Post(s.URL+"/mBGWHqBVEjUSKpBF/job/result", "application/json", bytes.NewBuffer(resultJSON)))
	require.Equal(bench.T, http.StatusOK, resp.StatusCode)
}

func cliLogin(cli *testHTTPClient, teamID int, password string) {
	resp := cli.Must(
		cli.PostForm(
			s.URL+"/login",
			url.Values{
				"team_id":  {fmt.Sprint(teamID)},
				"password": {password},
			},
		),
	)
	require.Equal(cli.T, "/", resp.Request.URL.Path)
}

func TestPostJob(t *testing.T) {
	var (
		cli   = newTestClient(t)
		cli2  = newTestClient(t)
		bench = newTestClient(t)
	)

	var resp *http.Response

	// cli: ログイン
	resp = cli.Must(cli.PostForm(s.URL+"/login", url.Values{"team_id": {"26"}, "password": {"p6aYuUempoticryg"}}))
	require.Equal(t, "/", resp.Request.URL.Path)

	// bench: ジョブ取る
	resp = bench.Must(bench.Post(s.URL+"/mBGWHqBVEjUSKpBF/job/new", "", nil))
	require.Equal(t, http.StatusNoContent, resp.StatusCode)

	// cli: ジョブいれる→まだIP入れてないのでエラー
	resp = cli.Must(cli.PostForm(s.URL+"/queue", nil))
	require.Equal(t, http.StatusBadRequest, resp.StatusCode)

	// cli: IP入れる
	resp = cli.Must(cli.PostForm(s.URL+"/team", url.Values{"ip_address": {"127.0.0.1"}, "instance_name": {""}}))
	assert.Contains(t, readAll(resp.Body), `<input class="form-control" type="text" name="ip_address" value="127.0.0.1" autocomplete="off">`, "IP入った表示")

	// cli: ジョブ入れる
	resp = cli.Must(cli.PostForm(s.URL+"/queue", nil))
	assert.Contains(t, readAll(resp.Body), `<span class="label label-default">26*</span>`, "ジョブ入った表示")

	// cli2: ログイン
	resp = cli2.Must(cli2.PostForm(s.URL+"/login", url.Values{"team_id": {"5"}, "password": {"Y7i06XOllyJI5ogn"}}))
	require.Equal(t, "/", resp.Request.URL.Path)
	assert.Contains(t, readAll(resp.Body), `<span class="label label-default">26</span>`, "他人のジョブ入った表示")

	// bench: ジョブ取る
	j := benchGetJob(bench)

	// cli: ジョブいれる (2) → 入らない
	resp = cli.Must(cli.PostForm(s.URL+"/queue", nil))
	assert.Contains(t, readAll(resp.Body), `Job already queued`)

	// cli2: IP入れる
	resp = cli2.Must(cli2.PostForm(s.URL+"/team", url.Values{"ip_address": {"127.0.0.2"}, "instance_name": {""}}))
	assert.Contains(t, readAll(resp.Body), `<input class="form-control" type="text" name="ip_address" value="127.0.0.2" autocomplete="off">`, "IP入った表示")

	// cli2: ジョブ入れる → 入る
	resp = cli2.Must(cli2.PostForm(s.URL+"/queue", nil))
	assert.Contains(t, readAll(resp.Body), `<span class="label label-default">5*</span>`, "ジョブ入った表示")

	// bench: ジョブ取る → 放置
	j2 := benchGetJob(bench)
	_ = j2

	// cli: トップリロード
	resp = cli.Must(cli.Get(s.URL + "/"))
	assert.Contains(t, readAll(resp.Body), `<span class="label label-success">26*</span>`, "ジョブ実行中の表示")

	// bench: 結果入れる
	benchPostResult(bench, j, &job.Output{Pass: false, Score: 5000})

	// cli: トップリロード
	resp = cli.Must(cli.Get(s.URL + "/"))
	body := readAll(resp.Body)
	require.Contains(t, body, `<th>Status</th><td>FAIL</td>`)
	require.Contains(t, body, `<th>Score</th><td>5000</td>`)
	require.Contains(t, body, `<th>Best</th><td>-</td>`)

	// cli: ジョブいれる (3)
	resp = cli.Must(cli.PostForm(s.URL+"/queue", url.Values{"ip_addr": {"127.0.0.1"}}))
	assert.NotContains(t, readAll(resp.Body), `Job already queued`)

	// bench: ジョブ取る
	j = benchGetJob(bench)

	// bench: 結果入れる
	benchPostResult(bench, j, &job.Output{Pass: true, Score: 3000})

	// cli: トップリロード
	resp = cli.Must(cli.Get(s.URL + "/"))
	body = readAll(resp.Body)
	require.Contains(t, body, `<th>Status</th><td>PASS</td>`)
	require.Contains(t, body, `<th>Score</th><td>3000</td>`)
	require.Contains(t, body, `<th>Best</th><td>3000</td>`)
	require.Regexp(t, `<td>RUDT</td>\s*<td>3000</td>`, body)
	require.NotContains(t, body, "流れ弾")

	// bench: 結果入れる
	benchPostResult(bench, j2, &job.Output{Pass: true, Score: 4500})

	resp = cli2.Must(cli2.Get(s.URL + "/"))
	body = readAll(resp.Body)
	require.Contains(t, body, `<th>Status</th><td>PASS</td>`)
	require.Contains(t, body, `<th>Score</th><td>4500</td>`)
	require.Contains(t, body, `<th>Best</th><td>4500</td>`)
	require.Regexp(t, `<td>流れ弾</td>\s*<td>4500</td>(?s:.*)<td>RUDT</td>\s*<td>3000</td>`, body)
}

func TestPostJobNotWithinContestTime(t *testing.T) {
	cli := newTestClient(t)
	cliLogin(cli, 10, "3svumTo3amDShlFy")

	var resp *http.Response

	*startsAtHour = 24
	resp = cli.Must(cli.PostForm(s.URL+"/queue", nil))
	assert.Equal(t, http.StatusForbidden, resp.StatusCode)
	assert.Equal(t, "Final has not started yet\n", readAll(resp.Body))
	*startsAtHour = -1

	*endsAtHour = 0
	resp = cli.Must(cli.PostForm(s.URL+"/queue", nil))
	assert.Equal(t, http.StatusForbidden, resp.StatusCode)
	assert.Equal(t, "Final has finished\n", readAll(resp.Body))
	*endsAtHour = -1
}

func TestUpdateTeam(t *testing.T) {
	cli := newTestClient(t)
	admin := newTestClient(t)
	cliLogin(cli, 11, "L6KZ7UJyAEtpVr9G")

	resp := cli.Must(cli.PostForm(s.URL+"/team", url.Values{"instance_name": {"xxxxxx"}, "ip_address": {"0.0.0.0"}}))
	assert.Equal(t, http.StatusOK, resp.StatusCode)
	body := readAll(resp.Body)
	assert.Contains(t, body, `value="xxxxxx"`)
	assert.Contains(t, body, `value="0.0.0.0"`)

	resp = cli.Must(cli.Get(s.URL + "/"))
	body = readAll(resp.Body)
	assert.Contains(t, body, `value="xxxxxx"`)
	assert.Contains(t, body, `value="0.0.0.0"`)

	resp = admin.Must(admin.Get(s.URL + "/mBGWHqBVEjUSKpBF/proxy/nginx.conf"))
	require.Equal(t, http.StatusOK, resp.StatusCode)
	body = readAll(resp.Body)
	assert.Contains(t, body, `# team11`)
	assert.Contains(t, body, `listen 10011;`)
	assert.Contains(t, body, `proxy_pass 0.0.0.0:443;`)
}

func TestUpdateProxies(t *testing.T) {
	cli := newTestClient(t)
	bench := newTestClient(t)
	admin := newTestClient(t)
	cliLogin(cli, 12, "YJUaDANoex8Y6MB")

	// proxyのIP一覧を入れる
	nodes := `[{"Name":"portal","Addr":"192.168.0.10","Status":1},{"Name":"isu-proxy-1","Addr":"192.168.0.11","Status":1},{"Name":"isu-proxy-2","Addr":"192.168.0.12","Status":1},{"Name":"isu-proxy-3","Addr":"192.168.0.13","Status":0}]`
	resp := admin.Must(admin.Post(s.URL+"/mBGWHqBVEjUSKpBF/proxy/update", "application/json", bytes.NewBuffer([]byte(nodes))))
	body := readAll(resp.Body)
	assert.NotContains(t, body, `192.168.0.10`, "portalのIP")
	assert.Contains(t, body, `192.168.0.11`, "proxy-1のIP")
	assert.Contains(t, body, `192.168.0.12`, "proxy-2のIP")
	assert.NotContains(t, body, `192.168.0.13`, "proxy-3のIP")

	// cli: IP入れる
	resp = cli.Must(cli.PostForm(s.URL+"/team", url.Values{"ip_address": {"127.0.0.1"}, "instance_name": {""}}))

	// cli: ジョブ入れる
	resp = cli.Must(cli.PostForm(s.URL+"/queue", nil))

	// bench: ジョブ取る
	j := benchGetJob(bench)
	require.Equal(t, 12, j.TeamID)
	assert.Contains(t, j.URLs, `https://192.168.0.11:10012`, "proxy-1のIP")
	assert.Contains(t, j.URLs, `https://192.168.0.12:10012`, "proxy-2のIP")
	assert.NotContains(t, j.URLs, `https://192.168.0.13:10012`, "proxy-3のIP")
}
<commit_msg>Delete web_test.go (it did not pass)<commit_after><|endoftext|>


<commit_before>package pqcrypto

import (
	"testing"
	"errors"
)

var (
	ErrHash = errors.New("hash verification failed")
)

const test_data = "bitnation rocks"

func TestVerify(t *testing.T) {
	hash := Hash([]byte(test_data))
	t.Logf("hash: %x", hash)

	if CheckHash([]byte(test_data), hash) != true {
		t.Error(ErrHash)
	}

	// Alter the Hash
	hash[0] = 1
	if CheckHash([]byte(test_data), hash) == true {
		t.Error(ErrHash)
	}
}
<commit_msg>[pqcrypto] Fmt<commit_after>package pqcrypto

import (
	"errors"
	"testing"
)

var (
	ErrHash = errors.New("hash verification failed")
)

const test_data = "bitnation rocks"

func TestVerify(t *testing.T) {
	hash := Hash([]byte(test_data))
	t.Logf("hash: %x", hash)

	if CheckHash([]byte(test_data), hash) != true {
		t.Error(ErrHash)
	}

	// Alter the Hash
	hash[0] = 1
	if CheckHash([]byte(test_data), hash) == true {
		t.Error(ErrHash)
	}
}
<|endoftext|>


<commit_before>package pqtgo

import (
	"bytes"
	"fmt"
	"go/types"
	"io"
	"sort"
	"strings"

	"github.com/huandu/xstrings"
	"github.com/piotrkowalczuk/pqcnstr"
	"github.com/piotrkowalczuk/pqt"
)

type generator struct {
	acronyms map[string]string
	imports  []string
	pkg      string
}

// Generator ...
func Generator() *generator {
	return &generator{
		pkg: "main",
	}
}

// SetAcronyms ...
func (g *generator) SetAcronyms(acronyms map[string]string) *generator {
	g.acronyms = acronyms

	return g
}

// SetImports ...
func (g *generator) SetImports(imports ...string) *generator {
	g.imports = imports

	return g
}

// AddImport ...
func (g *generator) AddImport(i string) *generator {
	if g.imports == nil {
		g.imports = make([]string, 0, 1)
	}

	g.imports = append(g.imports, i)
	return g
}

// SetPackage ...
func (g *generator) SetPackage(pkg string) *generator {
	g.pkg = pkg

	return g
}

// Generate ...
func (g *generator) Generate(s *pqt.Schema) ([]byte, error) {
	code, err := g.generate(s)
	if err != nil {
		return nil, err
	}

	return code.Bytes(), nil
}

// GenerateTo ...
func (g *generator) GenerateTo(s *pqt.Schema, w io.Writer) error {
	code, err := g.generate(s)
	if err != nil {
		return err
	}

	_, err = code.WriteTo(w)
	return err
}

func (g *generator) generate(s *pqt.Schema) (*bytes.Buffer, error) {
	code := bytes.NewBuffer(nil)

	g.generatePackage(code)
	g.generateImports(code, s)
	for _, table := range s.Tables {
		g.generateConstants(code, table)
		g.generateColumns(code, table)
		g.generateEntity(code, table)
	}

	return code, nil
}

func (g *generator) generatePackage(code *bytes.Buffer) {
	fmt.Fprintf(code, "package %s \n", g.pkg)
}

func (g *generator) generateImports(code *bytes.Buffer, schema *pqt.Schema) {
	imports := []string{}

	for _, t := range schema.Tables {
		for _, c := range t.Columns {
			if ct, ok := c.Type.(CustomType); ok {
				imports = append(imports, ct.pkg)
			}
		}
	}

	code.WriteString("import (\n")
	for _, imp := range imports {
		fmt.Fprintf(code, `"%s"`, imp)
	}
	code.WriteString(")\n")
}

func (g *generator) generateEntity(code *bytes.Buffer, table *pqt.Table) {
	code.WriteString("type " + g.private(table.Name) + "Entity struct {")
	for _, c := range table.Columns {
		code.WriteString(g.public(c.Name))
		code.WriteRune(' ')
		g.generateType(code, c)
		code.WriteRune('\n')
	}
	code.WriteString("}\n")
}

func (g *generator) generateType(code *bytes.Buffer, c *pqt.Column) {
	var t string

	if str, ok := c.Type.(fmt.Stringer); ok {
		t = str.String()
	} else {
		t = "struct{}"
	}

	mandatory := c.NotNull || c.PrimaryKey

	switch tp := c.Type.(type) {
	case pqt.MappableType:
		for _, mapto := range tp.Mapping {
			switch mt := mapto.(type) {
			case BuiltinType:
				t = generateBuiltinType(mt, mandatory)
			case CustomType:
				t = mt.String()
			}
		}
	case BuiltinType:
		t = generateBuiltinType(tp, mandatory)
	case pqt.BaseType:
		t = generateBaseType(tp, mandatory)
	}

	code.WriteString(t)
}

func (g *generator) generateConstants(code *bytes.Buffer, table *pqt.Table) {
	code.WriteString("const (\n")
	g.generateConstantsColumns(code, table)
	g.generateConstantsConstraints(code, table)
	code.WriteString(")\n")
}

func (g *generator) generateConstantsColumns(code *bytes.Buffer, table *pqt.Table) {
	fmt.Fprintf(code, `table%s = "%s"`, g.public(table.Name), table.FullName())
	code.WriteRune('\n')

	for _, name := range sortedColumns(table.Columns) {
		fmt.Fprintf(code, `table%sColumn%s = "%s"`, g.public(table.Name), g.public(name), name)
		code.WriteRune('\n')
	}
}

func (g *generator) generateConstantsConstraints(code *bytes.Buffer, table *pqt.Table) {
	for _, c := range tableConstraints(table) {
		name := fmt.Sprintf("%s_%s", c.Table.Name, pqt.JoinColumns(c.Columns, "_"))
		switch c.Type {
		case pqcnstr.KindCheck:
			fmt.Fprintf(code, `table%sConstraint%sCheck = "%s"`, g.public(table.Name), g.public(name), c.String())
		case pqcnstr.KindPrimaryKey:
			fmt.Fprintf(code, `table%sConstraintPrimaryKey = "%s"`, g.public(table.Name), c.String())
		case pqcnstr.KindForeignKey:
			fmt.Fprintf(code, `table%sConstraint%sForeignKey = "%s"`, g.public(table.Name), g.public(name), c.String())
		case pqcnstr.KindExclusion:
			fmt.Fprintf(code, `table%sConstraint%sExclusion = "%s"`, g.public(table.Name), g.public(name), c.String())
		case pqcnstr.KindUnique:
			fmt.Fprintf(code, `table%sConstraint%sUnique = "%s"`, g.public(table.Name), g.public(name), c.String())
		case pqcnstr.KindIndex:
			fmt.Fprintf(code, `table%sConstraint%sIndex = "%s"`, g.public(table.Name), g.public(name), c.String())
		}

		code.WriteRune('\n')
	}
}

func (g *generator) generateColumns(code *bytes.Buffer, table *pqt.Table) {
	code.WriteString("var (\n")
	code.WriteRune('\n')

	code.WriteString("table")
	code.WriteString(g.public(table.Name))
	code.WriteString("Columns = []string{\n")

	for _, name := range sortedColumns(table.Columns) {
		fmt.Fprintf(code, "table%sColumn%s", g.public(table.Name), g.public(name))
		code.WriteRune(',')
		code.WriteRune('\n')
	}
	code.WriteString("}")
	code.WriteString(")\n")
}

func (g *generator) generateQueries(code *bytes.Buffer, table *pqt.Table) {

}

func sortedColumns(columns []*pqt.Column) []string {
	tmp := make([]string, 0, len(columns))
	for _, c := range columns {
		tmp = append(tmp, c.Name)
	}
	sort.Strings(tmp)

	return tmp
}

func snake(s string, private bool, acronyms map[string]string) string {
	var parts []string
	parts1 := strings.Split(s, "_")
	for _, p1 := range parts1 {
		parts2 := strings.Split(p1, "/")
		for _, p2 := range parts2 {
			parts3 := strings.Split(p2, "-")
			parts = append(parts, parts3...)
		}
	}

	for i, part := range parts {
		if !private || i > 0 {
			if formatted, ok := acronyms[part]; ok {
				parts[i] = formatted

				continue
			}
		}

		parts[i] = xstrings.FirstRuneToUpper(part)
	}

	if private {
		parts[0] = xstrings.FirstRuneToLower(parts[0])
	}

	return strings.Join(parts, "")
}

func (g *generator) private(s string) string {
	return snake(s, true, g.acronyms)
}

func (g *generator) public(s string) string {
	return snake(s, false, g.acronyms)
}

func nullable(typeA, typeB string, mandatory bool) string {
	if mandatory {
		return typeA
	}
	return typeB
}

func tableConstraints(t *pqt.Table) []*pqt.Constraint {
	var constraints []*pqt.Constraint
	for _, c := range t.Columns {
		constraints = append(constraints, c.Constraints()...)
	}

	return append(constraints, t.Constraints...)
}

func generateBaseType(t pqt.Type, mandatory bool) string {
	switch t {
	case pqt.TypeText():
		return nullable("string", "nilt.String", mandatory)
	case pqt.TypeBool():
		return nullable("bool", "nilt.Bool", mandatory)
	case pqt.TypeIntegerSmall():
		return "int16"
	case pqt.TypeInteger():
		return nullable("int", "nilt.Int", mandatory)
	case pqt.TypeIntegerBig():
		return nullable("int64", "nilt.Int64", mandatory)
	case pqt.TypeSerial():
		return "int32"
	case pqt.TypeSerialSmall():
		return "int16"
	case pqt.TypeSerialBig():
		return "int64"
	case pqt.TypeTimestamp(), pqt.TypeTimestampTZ():
		return nullable("time.Time", "*time.Time", mandatory)
	case pqt.TypeReal():
		return nullable("float32", "nilt.Float32", mandatory)
	case pqt.TypeDoublePrecision():
		return nullable("float64", "nilt.Float64", mandatory)
	default:
		gt := t.String()
		switch {
		case strings.HasPrefix(gt, "SMALLINT["):
			return "[]int16"
		case strings.HasPrefix(gt, "INTEGER["):
			return "[]int"
		case strings.HasPrefix(gt, "BIGINT["):
			return "pqt.ArrayInt64"
		case strings.HasPrefix(gt, "TEXT["):
			return "pqt.ArrayString"
		case strings.HasPrefix(gt, "DECIMAL"):
			return nullable("float32", "nilt.Float32", mandatory)
		case strings.HasPrefix(gt, "VARCHAR"):
			return nullable("string", "nilt.String", mandatory)
		default:
			return "struct{}"
		}
	}
}

func generateBuiltinType(t BuiltinType, mandatory bool) (r string) {
	switch types.BasicKind(t) {
	case types.Bool:
		r = nullable("bool", "nilt.Bool", mandatory)
	case types.Int:
		r = nullable("int", "nilt.Int", mandatory)
	case types.Int8:
		r = nullable("int8", "*int8", mandatory)
	case types.Int16:
		r = nullable("int16", "*int16", mandatory)
	case types.Int32:
		r = nullable("int32", "nilt.Int32", mandatory)
	case types.Int64:
		r = nullable("int64", "nilt.Int64", mandatory)
	case types.Uint:
		r = nullable("uint", "*uint", mandatory)
	case types.Uint8:
		r = nullable("uint8", "*uint8", mandatory)
	case types.Uint16:
		r = nullable("uint16", "*uint16", mandatory)
	case types.Uint32:
		r = nullable("uint32", "nilt.Uint32", mandatory)
	case types.Uint64:
		r = nullable("uint64", "*uint64", mandatory)
	case types.Float32:
		r = nullable("float32", "nilt.Float32", mandatory)
	case types.Float64:
		r = nullable("float64", "nilt.Float64", mandatory)
	case types.Complex64:
		r = nullable("complex64", "*complex64", mandatory)
	case types.Complex128:
		r = nullable("complex128", "*complex128", mandatory)
	case types.String:
		r = nullable("string", "nilt.String", mandatory)
	default:
		r = "invalid"
	}

	return
}
<commit_msg>removed legacy import from pqtgo<commit_after>package pqtgo

import (
	"bytes"
	"fmt"
	"go/types"
	"io"
	"sort"
	"strings"

	"github.com/huandu/xstrings"
	"github.com/piotrkowalczuk/pqt"
)

type generator struct {
	acronyms map[string]string
	imports  []string
	pkg      string
}

// Generator ...
func Generator() *generator {
	return &generator{
		pkg: "main",
	}
}

// SetAcronyms ...
func (g *generator) SetAcronyms(acronyms map[string]string) *generator {
	g.acronyms = acronyms

	return g
}

// SetImports ...
func (g *generator) SetImports(imports ...string) *generator {
	g.imports = imports

	return g
}

// AddImport ...
func (g *generator) AddImport(i string) *generator {
	if g.imports == nil {
		g.imports = make([]string, 0, 1)
	}

	g.imports = append(g.imports, i)
	return g
}

// SetPackage ...
func (g *generator) SetPackage(pkg string) *generator {
	g.pkg = pkg

	return g
}

// Generate ...
func (g *generator) Generate(s *pqt.Schema) ([]byte, error) {
	code, err := g.generate(s)
	if err != nil {
		return nil, err
	}

	return code.Bytes(), nil
}

// GenerateTo ...
func (g *generator) GenerateTo(s *pqt.Schema, w io.Writer) error {
	code, err := g.generate(s)
	if err != nil {
		return err
	}

	_, err = code.WriteTo(w)
	return err
}

func (g *generator) generate(s *pqt.Schema) (*bytes.Buffer, error) {
	code := bytes.NewBuffer(nil)

	g.generatePackage(code)
	g.generateImports(code, s)
	for _, table := range s.Tables {
		g.generateConstants(code, table)
		g.generateColumns(code, table)
		g.generateEntity(code, table)
	}

	return code, nil
}

func (g *generator) generatePackage(code *bytes.Buffer) {
	fmt.Fprintf(code, "package %s \n", g.pkg)
}

func (g *generator) generateImports(code *bytes.Buffer, schema *pqt.Schema) {
	imports := []string{}

	for _, t := range schema.Tables {
		for _, c := range t.Columns {
			if ct, ok := c.Type.(CustomType); ok {
				imports = append(imports, ct.pkg)
			}
		}
	}

	code.WriteString("import (\n")
	for _, imp := range imports {
		fmt.Fprintf(code, `"%s"`, imp)
	}
	code.WriteString(")\n")
}

func (g *generator) generateEntity(code *bytes.Buffer, table *pqt.Table) {
	code.WriteString("type " + g.private(table.Name) + "Entity struct {")
	for _, c := range table.Columns {
		code.WriteString(g.public(c.Name))
		code.WriteRune(' ')
		g.generateType(code, c)
		code.WriteRune('\n')
	}
	code.WriteString("}\n")
}

func (g *generator) generateType(code *bytes.Buffer, c *pqt.Column) {
	var t string

	if str, ok := c.Type.(fmt.Stringer); ok {
		t = str.String()
	} else {
		t = "struct{}"
	}

	mandatory := c.NotNull || c.PrimaryKey

	switch tp := c.Type.(type) {
	case pqt.MappableType:
		for _, mapto := range tp.Mapping {
			switch mt := mapto.(type) {
			case BuiltinType:
				t = generateBuiltinType(mt, mandatory)
			case CustomType:
				t = mt.String()
			}
		}
	case BuiltinType:
		t = generateBuiltinType(tp, mandatory)
	case pqt.BaseType:
		t = generateBaseType(tp, mandatory)
	}

	code.WriteString(t)
}

func (g *generator) generateConstants(code *bytes.Buffer, table *pqt.Table) {
	code.WriteString("const (\n")
	g.generateConstantsColumns(code, table)
	g.generateConstantsConstraints(code, table)
	code.WriteString(")\n")
}

func (g *generator) generateConstantsColumns(code *bytes.Buffer, table *pqt.Table) {
	fmt.Fprintf(code, `table%s = "%s"`, g.public(table.Name), table.FullName())
	code.WriteRune('\n')

	for _, name := range sortedColumns(table.Columns) {
		fmt.Fprintf(code, `table%sColumn%s = "%s"`, g.public(table.Name), g.public(name), name)
		code.WriteRune('\n')
	}
}

func (g *generator) generateConstantsConstraints(code *bytes.Buffer, table *pqt.Table) {
	for _, c := range tableConstraints(table) {
		name := fmt.Sprintf("%s_%s", c.Table.Name, pqt.JoinColumns(c.Columns, "_"))
		switch c.Type {
		case pqt.ConstraintTypeCheck:
			fmt.Fprintf(code, `table%sConstraint%sCheck = "%s"`, g.public(table.Name), g.public(name), c.String())
		case pqt.ConstraintTypePrimaryKey:
			fmt.Fprintf(code, `table%sConstraintPrimaryKey = "%s"`, g.public(table.Name), c.String())
		case pqt.ConstraintTypeForeignKey:
			fmt.Fprintf(code, `table%sConstraint%sForeignKey = "%s"`, g.public(table.Name), g.public(name), c.String())
		case pqt.ConstraintTypeExclusion:
			fmt.Fprintf(code, `table%sConstraint%sExclusion = "%s"`, g.public(table.Name), g.public(name), c.String())
		case pqt.ConstraintTypeUnique:
			fmt.Fprintf(code, `table%sConstraint%sUnique = "%s"`, g.public(table.Name), g.public(name), c.String())
		case pqt.ConstraintTypeIndex:
			fmt.Fprintf(code, `table%sConstraint%sIndex = "%s"`, g.public(table.Name), g.public(name), c.String())
		}

		code.WriteRune('\n')
	}
}

func (g *generator) generateColumns(code *bytes.Buffer, table *pqt.Table) {
	code.WriteString("var (\n")
	code.WriteRune('\n')

	code.WriteString("table")
	code.WriteString(g.public(table.Name))
	code.WriteString("Columns = []string{\n")

	for _, name := range sortedColumns(table.Columns) {
		fmt.Fprintf(code, "table%sColumn%s", g.public(table.Name), g.public(name))
		code.WriteRune(',')
		code.WriteRune('\n')
	}
	code.WriteString("}")
	code.WriteString(")\n")
}

func (g *generator) generateQueries(code *bytes.Buffer, table *pqt.Table) {

}

func sortedColumns(columns []*pqt.Column) []string {
	tmp := make([]string, 0, len(columns))
	for _, c := range columns {
		tmp = append(tmp, c.Name)
	}
	sort.Strings(tmp)

	return tmp
}

func snake(s string, private bool, acronyms map[string]string) string {
	var parts []string
	parts1 := strings.Split(s, "_")
	for _, p1 := range parts1 {
		parts2 := strings.Split(p1, "/")
		for _, p2 := range parts2 {
			parts3 := strings.Split(p2, "-")
			parts = append(parts, parts3...)
		}
	}

	for i, part := range parts {
		if !private || i > 0 {
			if formatted, ok := acronyms[part]; ok {
				parts[i] = formatted

				continue
			}
		}

		parts[i] = xstrings.FirstRuneToUpper(part)
	}

	if private {
		parts[0] = xstrings.FirstRuneToLower(parts[0])
	}

	return strings.Join(parts, "")
}

func (g *generator) private(s string) string {
	return snake(s, true, g.acronyms)
}

func (g *generator) public(s string) string {
	return snake(s, false, g.acronyms)
}

func nullable(typeA, typeB string, mandatory bool) string {
	if mandatory {
		return typeA
	}
	return typeB
}

func tableConstraints(t *pqt.Table) []*pqt.Constraint {
	var constraints []*pqt.Constraint
	for _, c := range t.Columns {
		constraints = append(constraints, c.Constraints()...)
	}

	return append(constraints, t.Constraints...)
}

func generateBaseType(t pqt.Type, mandatory bool) string {
	switch t {
	case pqt.TypeText():
		return nullable("string", "nilt.String", mandatory)
	case pqt.TypeBool():
		return nullable("bool", "nilt.Bool", mandatory)
	case pqt.TypeIntegerSmall():
		return "int16"
	case pqt.TypeInteger():
		return nullable("int", "nilt.Int", mandatory)
	case pqt.TypeIntegerBig():
		return nullable("int64", "nilt.Int64", mandatory)
	case pqt.TypeSerial():
		return "int32"
	case pqt.TypeSerialSmall():
		return "int16"
	case pqt.TypeSerialBig():
		return "int64"
	case pqt.TypeTimestamp(), pqt.TypeTimestampTZ():
		return nullable("time.Time", "*time.Time", mandatory)
	case pqt.TypeReal():
		return nullable("float32", "nilt.Float32", mandatory)
	case pqt.TypeDoublePrecision():
		return nullable("float64", "nilt.Float64", mandatory)
	default:
		gt := t.String()
		switch {
		case strings.HasPrefix(gt, "SMALLINT["):
			return "[]int16"
		case strings.HasPrefix(gt, "INTEGER["):
			return "[]int"
		case strings.HasPrefix(gt, "BIGINT["):
			return "pqt.ArrayInt64"
		case strings.HasPrefix(gt, "TEXT["):
			return "pqt.ArrayString"
		case strings.HasPrefix(gt, "DECIMAL"):
			return nullable("float32", "nilt.Float32", mandatory)
		case strings.HasPrefix(gt, "VARCHAR"):
			return nullable("string", "nilt.String", mandatory)
		default:
			return "struct{}"
		}
	}
}

func generateBuiltinType(t BuiltinType, mandatory bool) (r string) {
	switch types.BasicKind(t) {
	case types.Bool:
		r = nullable("bool", "nilt.Bool", mandatory)
	case types.Int:
		r = nullable("int", "nilt.Int", mandatory)
	case types.Int8:
		r = nullable("int8", "*int8", mandatory)
	case types.Int16:
		r = nullable("int16", "*int16", mandatory)
	case types.Int32:
		r = nullable("int32", "nilt.Int32", mandatory)
	case types.Int64:
		r = nullable("int64", "nilt.Int64", mandatory)
	case types.Uint:
		r = nullable("uint", "*uint", mandatory)
	case types.Uint8:
		r = nullable("uint8", "*uint8", mandatory)
	case types.Uint16:
		r = nullable("uint16", "*uint16", mandatory)
	case types.Uint32:
		r = nullable("uint32", "nilt.Uint32", mandatory)
	case types.Uint64:
		r = nullable("uint64", "*uint64", mandatory)
	case types.Float32:
		r = nullable("float32", "nilt.Float32", mandatory)
	case types.Float64:
		r = nullable("float64", "nilt.Float64", mandatory)
	case types.Complex64:
		r = nullable("complex64", "*complex64", mandatory)
	case types.Complex128:
		r = nullable("complex128", "*complex128", mandatory)
	case types.String:
		r = nullable("string", "nilt.String", mandatory)
	default:
		r = "invalid"
	}

	return
}
<|endoftext|>


<commit_before>package websocket

import (
	"net"

	"time"

	"github.com/gorilla/websocket"
	"github.com/spring1843/chat-server/src/shared/errs"
	"github.com/spring1843/chat-server/src/shared/logs"
)

const (
	// Time allowed to write a message to the peer.
	writeWait = 10 * time.Second

	// Time allowed to read the next pong message from the peer.
	pongWait = 60 * time.Second

	// Send pings to peer with this period. Must be less than pongWait.
	pingPeriod = (pongWait * 9) / 10

	// Maximum message size allowed from peer.
	maxMessageSize = 512
)

// ChatConnection is an middleman between the WebSocket connection and Chat Server
type ChatConnection struct {
	Connection *websocket.Conn
	incoming   chan []byte
	outgoing   chan []byte
}

// NewChatConnection returns a new ChatConnection
func NewChatConnection() *ChatConnection {
	return &ChatConnection{
		incoming: make(chan []byte),
		outgoing: make(chan []byte),
	}
}

// Read waits for user to enter a text, or reads the last entered incoming message
func (c *ChatConnection) Read(p []byte) (int, error) {
	i := 0
	message := <-c.incoming
	message = append(message, byte('\n'))

	if len(p) < len(message) {
		p = make([]byte, len(message))
	}

	for _, bit := range message {
		p[i] = bit
		i++
	}
	return i, nil
}

// Write to a ChatConnection
func (c *ChatConnection) Write(p []byte) (int, error) {
	wtr, err := c.Connection.NextWriter(websocket.TextMessage)
	if err != nil {
		return 0, errs.Wrap(err, "Error getting nextwriter from WebSocket connection.")
	}
	defer wtr.Close()
	return wtr.Write(p)
}

// readPump pumps messages from the websocket connection to the hub.
//
// The application runs readPump in a per-connection goroutine. The application
// ensures that there is at most one reader on a connection by executing all
// reads from this goroutine.
func (c *ChatConnection) readPump() {
	defer func() {
		c.Connection.Close()
		close(c.incoming)
		close(c.outgoing)
		logs.Infof("No longer reading Websocket pump for %s", c.Connection.RemoteAddr())
	}()
	c.Connection.SetReadLimit(maxMessageSize)
	c.Connection.SetReadDeadline(time.Now().Add(pongWait))
	c.Connection.SetPongHandler(func(string) error { c.Connection.SetReadDeadline(time.Now().Add(pongWait)); return nil })
	for {
		_, message, err := c.Connection.ReadMessage()
		if err != nil {
			if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {
				logs.ErrIfErrf(err, "Error reading from WebSocket connection")
			}
			break
		}
		c.incoming <- message
	}
}

// writePump pumps messages from the hub to the websocket connection.
//
// A goroutine running writePump is started for each connection. The
// application ensures that there is at most one writer to a connection by
// executing all writes from this goroutine.
func (c *ChatConnection) writePump() {
	ticker := time.NewTicker(pingPeriod)
	defer func() {
		ticker.Stop()
		c.Connection.Close()
	}()
	for {
		select {
		case message, ok := <-c.outgoing:
			c.Connection.SetWriteDeadline(time.Now().Add(writeWait))
			if !ok {
				// The hub closed the channel.
				c.Connection.WriteMessage(websocket.CloseMessage, []byte{})
				return
			}

			w, err := c.Connection.NextWriter(websocket.TextMessage)
			if err != nil {
				return
			}
			w.Write(message)

			// Add queued chat messages to the current websocket message.
			n := len(c.outgoing)
			for i := 0; i < n; i++ {
				w.Write([]byte{'\n'})
				w.Write(<-c.outgoing)
			}

			if err := w.Close(); err != nil {
				return
			}
		case <-ticker.C:
			c.Connection.SetWriteDeadline(time.Now().Add(writeWait))
			if err := c.Connection.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
				return
			}
		}
	}
}

// RemoteAddr returns the remote address of the connected user
func (c *ChatConnection) RemoteAddr() net.Addr {
	return c.Connection.RemoteAddr()
}

// Close a ChatConnection
func (c *ChatConnection) Close() error {
	if err := c.Connection.Close(); err != nil {
		return errs.Wrap(err, "Error closing WebSocket connection")
	}
	return nil
}
<commit_msg>Unrace<commit_after>package websocket

import (
	"net"

	"time"

	"github.com/gorilla/websocket"
	"github.com/spring1843/chat-server/src/shared/errs"
	"github.com/spring1843/chat-server/src/shared/logs"
)

const (
	// Time allowed to write a message to the peer.
	writeWait = 10 * time.Second

	// Time allowed to read the next pong message from the peer.
	pongWait = 60 * time.Second

	// Send pings to peer with this period. Must be less than pongWait.
	pingPeriod = (pongWait * 9) / 10

	// Maximum message size allowed from peer.
	maxMessageSize = 512
)

// ChatConnection is an middleman between the WebSocket connection and Chat Server
type ChatConnection struct {
	Connection *websocket.Conn
	incoming   chan []byte
	outgoing   chan []byte
}

// NewChatConnection returns a new ChatConnection
func NewChatConnection() *ChatConnection {
	return &ChatConnection{
		incoming: make(chan []byte),
		outgoing: make(chan []byte),
	}
}

// Read waits for user to enter a text, or reads the last entered incoming message
func (c *ChatConnection) Read(p []byte) (int, error) {
	i := 0
	message := <-c.incoming
	message = append(message, byte('\n'))

	if len(p) < len(message) {
		p = make([]byte, len(message))
	}

	for _, bit := range message {
		p[i] = bit
		i++
	}
	return i, nil
}

// Write to a ChatConnection
func (c *ChatConnection) Write(p []byte) (int, error) {
	// At max 1 go routine must be writing to this connection so we use a channel here
	c.outgoing <- p
	return len(p), nil

}

// readPump pumps messages from the websocket connection to the hub.
//
// The application runs readPump in a per-connection goroutine. The application
// ensures that there is at most one reader on a connection by executing all
// reads from this goroutine.
func (c *ChatConnection) readPump() {
	defer func() {
		c.Connection.Close()
		logs.Infof("No longer reading Websocket pump for %s", c.Connection.RemoteAddr())
	}()
	c.Connection.SetReadLimit(maxMessageSize)
	c.Connection.SetReadDeadline(time.Now().Add(pongWait))
	c.Connection.SetPongHandler(func(string) error { c.Connection.SetReadDeadline(time.Now().Add(pongWait)); return nil })
	for {
		_, message, err := c.Connection.ReadMessage()
		if err != nil {
			if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {
				logs.ErrIfErrf(err, "Error reading from WebSocket connection")
			}
			break
		}
		c.incoming <- message
	}
}

// writePump pumps messages from the hub to the websocket connection.
//
// A goroutine running writePump is started for each connection. The
// application ensures that there is at most one writer to a connection by
// executing all writes from this goroutine.
func (c *ChatConnection) writePump() {
	ticker := time.NewTicker(pingPeriod)
	defer func() {
		ticker.Stop()
		c.Connection.Close()
	}()
	for {
		select {
		case message, ok := <-c.outgoing:
			c.Connection.SetWriteDeadline(time.Now().Add(writeWait))
			if !ok {
				// The hub closed the channel.
				c.Connection.WriteMessage(websocket.CloseMessage, []byte{})
				return
			}

			w, err := c.Connection.NextWriter(websocket.TextMessage)
			if err != nil {
				return
			}
			w.Write(message)

			// Add queued chat messages to the current websocket message.
			n := len(c.outgoing)
			for i := 0; i < n; i++ {
				w.Write([]byte{'\n'})
				w.Write(<-c.outgoing)
			}

			if err := w.Close(); err != nil {
				return
			}
		case <-ticker.C:
			c.Connection.SetWriteDeadline(time.Now().Add(writeWait))
			if err := c.Connection.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
				return
			}
		}
	}
}

// RemoteAddr returns the remote address of the connected user
func (c *ChatConnection) RemoteAddr() net.Addr {
	return c.Connection.RemoteAddr()
}

// Close a ChatConnection
func (c *ChatConnection) Close() error {
	if err := c.Connection.Close(); err != nil {
		return errs.Wrap(err, "Error closing WebSocket connection")
	}
	return nil
}
<|endoftext|>


<commit_before>/*
Copyright (c) 2015, Emir Pasic
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

// Implementation of Red-black tree.
// Used by TreeSet and TreeMap.
// Structure is not thread safe.
// References: http://en.wikipedia.org/wiki/Red%E2%80%93black_tree

package redblacktree

import (
	"fmt"
	"github.com/emirpasic/gods/stacks/linkedliststack"
	"github.com/emirpasic/gods/trees"
	"github.com/emirpasic/gods/utils"
)

func assertInterfaceImplementation() {
	var _ trees.Interface = (*Tree)(nil)
}

type color bool

const (
	black, red color = true, false
)

type Tree struct {
	root       *node
	size       int
	comparator utils.Comparator
}

type node struct {
	key    interface{}
	value  interface{}
	color  color
	left   *node
	right  *node
	parent *node
}

// Instantiates a red-black tree with the custom comparator.
func NewWith(comparator utils.Comparator) *Tree {
	return &Tree{comparator: comparator}
}

// Instantiates a red-black tree with the IntComparator, i.e. keys are of type int.
func NewWithIntComparator() *Tree {
	return &Tree{comparator: utils.IntComparator}
}

// Instantiates a red-black tree with the StringComparator, i.e. keys are of type string.
func NewWithStringComparator() *Tree {
	return &Tree{comparator: utils.StringComparator}
}

// Inserts node into the tree.
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) Put(key interface{}, value interface{}) {
	insertedNode := &node{key: key, value: value, color: red}
	if tree.root == nil {
		tree.root = insertedNode
	} else {
		node := tree.root
		loop := true
		for loop {
			compare := tree.comparator(key, node.key)
			switch {
			case compare == 0:
				node.value = value
				return
			case compare < 0:
				if node.left == nil {
					node.left = insertedNode
					loop = false
				} else {
					node = node.left
				}
			case compare > 0:
				if node.right == nil {
					node.right = insertedNode
					loop = false
				} else {
					node = node.right
				}
			}
		}
		insertedNode.parent = node
	}
	tree.insertCase1(insertedNode)
	tree.size += 1
}

// Searches the node in the tree by key and returns its value or nil if key is not found in tree.
// Second return parameter is true if key was found, otherwise false.
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) Get(key interface{}) (value interface{}, found bool) {
	node := tree.lookup(key)
	if node != nil {
		return node.value, true
	}
	return nil, false
}

// Remove the node from the tree by key.
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) Remove(key interface{}) {
	var child *node
	node := tree.lookup(key)
	if node == nil {
		return
	}
	if node.left != nil && node.right != nil {
		pred := node.left.maximumNode()
		node.key = pred.key
		node.value = pred.value
		node = pred
	}
	if node.left == nil || node.right == nil {
		if node.right == nil {
			child = node.left
		} else {
			child = node.right
		}
		if node.color == black {
			node.color = nodeColor(child)
			tree.deleteCase1(node)
		}
		tree.replaceNode(node, child)
		if node.parent == nil && child != nil {
			child.color = black
		}
	}
	tree.size -= 1
}

// Returns true if tree does not contain any nodes
func (tree *Tree) Empty() bool {
	return tree.size == 0
}

// Returns number of nodes in the tree.
func (tree *Tree) Size() int {
	return tree.size
}

// Returns all keys in-order
func (tree *Tree) Keys() []interface{} {
	keys := make([]interface{}, tree.size)
	for i, node := range tree.inOrder() {
		keys[i] = node.key
	}
	return keys
}

// Returns all values in-order based on the key.
func (tree *Tree) Values() []interface{} {
	values := make([]interface{}, tree.size)
	for i, node := range tree.inOrder() {
		values[i] = node.value
	}
	return values
}

// Removes all nodes from the tree.
func (tree *Tree) Clear() {
	tree.root = nil
	tree.size = 0
}

func (tree *Tree) String() string {
	str := "RedBlackTree\n"
	if !tree.Empty() {
		output(tree.root, "", true, &str)
	}
	return str
}

func (node *node) String() string {
	return fmt.Sprintf("%v", node.key)
}

// Returns all nodes in order
func (tree *Tree) inOrder() []*node {
	nodes := make([]*node, tree.size)
	if tree.size > 0 {
		current := tree.root
		stack := linkedliststack.New()
		done := false
		count := 0
		for !done {
			if current != nil {
				stack.Push(current)
				current = current.left
			} else {
				if !stack.Empty() {
					currentPop, _ := stack.Pop()
					current = currentPop.(*node)
					nodes[count] = current
					count += 1
					current = current.right
				} else {
					done = true
				}
			}
		}
	}
	return nodes
}

func output(node *node, prefix string, isTail bool, str *string) {
	if node.right != nil {
		newPrefix := prefix
		if isTail {
			newPrefix += "│   "
		} else {
			newPrefix += "    "
		}
		output(node.right, newPrefix, false, str)
	}
	*str += prefix
	if isTail {
		*str += "└── "
	} else {
		*str += "┌── "
	}
	*str += node.String() + "\n"
	if node.left != nil {
		newPrefix := prefix
		if isTail {
			newPrefix += "    "
		} else {
			newPrefix += "│   "
		}
		output(node.left, newPrefix, true, str)
	}
}

func (tree *Tree) lookup(key interface{}) *node {
	node := tree.root
	for node != nil {
		compare := tree.comparator(key, node.key)
		switch {
		case compare == 0:
			return node
		case compare < 0:
			node = node.left
		case compare > 0:
			node = node.right
		}
	}
	return nil
}

func (node *node) grandparent() *node {
	if node != nil && node.parent != nil {
		return node.parent.parent
	}
	return nil
}

func (node *node) uncle() *node {
	if node == nil || node.parent == nil || node.parent.parent == nil {
		return nil
	}
	return node.parent.sibling()
}

func (node *node) sibling() *node {
	if node == nil || node.parent == nil {
		return nil
	}
	if node == node.parent.left {
		return node.parent.right
	} else {
		return node.parent.left
	}
}

func (tree *Tree) rotateLeft(node *node) {
	right := node.right
	tree.replaceNode(node, right)
	node.right = right.left
	if right.left != nil {
		right.left.parent = node
	}
	right.left = node
	node.parent = right
}

func (tree *Tree) rotateRight(node *node) {
	left := node.left
	tree.replaceNode(node, left)
	node.left = left.right
	if left.right != nil {
		left.right.parent = node
	}
	left.right = node
	node.parent = left
}

func (tree *Tree) replaceNode(old *node, new *node) {
	if old.parent == nil {
		tree.root = new
	} else {
		if old == old.parent.left {
			old.parent.left = new
		} else {
			old.parent.right = new
		}
	}
	if new != nil {
		new.parent = old.parent
	}
}

func (tree *Tree) insertCase1(node *node) {
	if node.parent == nil {
		node.color = black
	} else {
		tree.insertCase2(node)
	}
}

func (tree *Tree) insertCase2(node *node) {
	if nodeColor(node.parent) == black {
		return
	}
	tree.insertCase3(node)
}

func (tree *Tree) insertCase3(node *node) {
	uncle := node.uncle()
	if nodeColor(uncle) == red {
		node.parent.color = black
		uncle.color = black
		node.grandparent().color = red
		tree.insertCase1(node.grandparent())
	} else {
		tree.insertCase4(node)
	}
}

func (tree *Tree) insertCase4(node *node) {
	grandparent := node.grandparent()
	if node == node.parent.right && node.parent == grandparent.left {
		tree.rotateLeft(node.parent)
		node = node.left
	} else if node == node.parent.left && node.parent == grandparent.right {
		tree.rotateRight(node.parent)
		node = node.right
	}
	tree.insertCase5(node)
}

func (tree *Tree) insertCase5(node *node) {
	node.parent.color = black
	grandparent := node.grandparent()
	grandparent.color = red
	if node == node.parent.left && node.parent == grandparent.left {
		tree.rotateRight(grandparent)
	} else if node == node.parent.right && node.parent == grandparent.right {
		tree.rotateLeft(grandparent)
	}
}

func (node *node) maximumNode() *node {
	if node == nil {
		return nil
	}
	for node.right != nil {
		node = node.right
	}
	return node
}

func (tree *Tree) deleteCase1(node *node) {
	if node.parent == nil {
		return
	} else {
		tree.deleteCase2(node)
	}
}

func (tree *Tree) deleteCase2(node *node) {
	sibling := node.sibling()
	if nodeColor(sibling) == red {
		node.parent.color = red
		sibling.color = black
		if node == node.parent.left {
			tree.rotateLeft(node.parent)
		} else {
			tree.rotateRight(node.parent)
		}
	}
	tree.deleteCase3(node)
}

func (tree *Tree) deleteCase3(node *node) {
	sibling := node.sibling()
	if nodeColor(node.parent) == black &&
		nodeColor(sibling) == black &&
		nodeColor(sibling.left) == black &&
		nodeColor(sibling.right) == black {
		sibling.color = red
		tree.deleteCase1(node.parent)
	} else {
		tree.deleteCase4(node)
	}
}

func (tree *Tree) deleteCase4(node *node) {
	sibling := node.sibling()
	if nodeColor(node.parent) == red &&
		nodeColor(sibling) == black &&
		nodeColor(sibling.left) == black &&
		nodeColor(sibling.right) == black {
		sibling.color = red
		node.parent.color = black
	} else {
		tree.deleteCase5(node)
	}
}

func (tree *Tree) deleteCase5(node *node) {
	sibling := node.sibling()
	if node == node.parent.left &&
		nodeColor(sibling) == black &&
		nodeColor(sibling.left) == red &&
		nodeColor(sibling.right) == black {
		sibling.color = red
		sibling.left.color = black
		tree.rotateRight(sibling)
	} else if node == node.parent.right &&
		nodeColor(sibling) == black &&
		nodeColor(sibling.right) == red &&
		nodeColor(sibling.left) == black {
		sibling.color = red
		sibling.right.color = black
		tree.rotateLeft(sibling)
	}
	tree.deleteCase6(node)
}

func (tree *Tree) deleteCase6(node *node) {
	sibling := node.sibling()
	sibling.color = nodeColor(node.parent)
	node.parent.color = black
	if node == node.parent.left && nodeColor(sibling.right) == red {
		sibling.right.color = black
		tree.rotateLeft(node.parent)
	} else if nodeColor(sibling.left) == red {
		sibling.left.color = black
		tree.rotateRight(node.parent)
	}
}

func nodeColor(node *node) color {
	if node == nil {
		return black
	}
	return node.color
}
<commit_msg>- expose the root of the red-black tree to allow custom tree traversal<commit_after>/*
Copyright (c) 2015, Emir Pasic
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

// Implementation of Red-black tree.
// Used by TreeSet and TreeMap.
// Structure is not thread safe.
// References: http://en.wikipedia.org/wiki/Red%E2%80%93black_tree

package redblacktree

import (
	"fmt"
	"github.com/emirpasic/gods/stacks/linkedliststack"
	"github.com/emirpasic/gods/trees"
	"github.com/emirpasic/gods/utils"
)

func assertInterfaceImplementation() {
	var _ trees.Interface = (*Tree)(nil)
}

type color bool

const (
	black, red color = true, false
)

type Tree struct {
	Root       *Node
	size       int
	comparator utils.Comparator
}

type Node struct {
	Key    interface{}
	Value  interface{}
	color  color
	Left   *Node
	Right  *Node
	Parent *Node
}

// Instantiates a red-black tree with the custom comparator.
func NewWith(comparator utils.Comparator) *Tree {
	return &Tree{comparator: comparator}
}

// Instantiates a red-black tree with the IntComparator, i.e. keys are of type int.
func NewWithIntComparator() *Tree {
	return &Tree{comparator: utils.IntComparator}
}

// Instantiates a red-black tree with the StringComparator, i.e. keys are of type string.
func NewWithStringComparator() *Tree {
	return &Tree{comparator: utils.StringComparator}
}

// Inserts node into the tree.
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) Put(key interface{}, value interface{}) {
	insertedNode := &Node{Key: key, Value: value, color: red}
	if tree.Root == nil {
		tree.Root = insertedNode
	} else {
		node := tree.Root
		loop := true
		for loop {
			compare := tree.comparator(key, node.Key)
			switch {
			case compare == 0:
				node.Value = value
				return
			case compare < 0:
				if node.Left == nil {
					node.Left = insertedNode
					loop = false
				} else {
					node = node.Left
				}
			case compare > 0:
				if node.Right == nil {
					node.Right = insertedNode
					loop = false
				} else {
					node = node.Right
				}
			}
		}
		insertedNode.Parent = node
	}
	tree.insertCase1(insertedNode)
	tree.size += 1
}

// Searches the node in the tree by key and returns its value or nil if key is not found in tree.
// Second return parameter is true if key was found, otherwise false.
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) Get(key interface{}) (value interface{}, found bool) {
	node := tree.lookup(key)
	if node != nil {
		return node.Value, true
	}
	return nil, false
}

// Remove the node from the tree by key.
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) Remove(key interface{}) {
	var child *Node
	node := tree.lookup(key)
	if node == nil {
		return
	}
	if node.Left != nil && node.Right != nil {
		pred := node.Left.maximumNode()
		node.Key = pred.Key
		node.Value = pred.Value
		node = pred
	}
	if node.Left == nil || node.Right == nil {
		if node.Right == nil {
			child = node.Left
		} else {
			child = node.Right
		}
		if node.color == black {
			node.color = nodeColor(child)
			tree.deleteCase1(node)
		}
		tree.replaceNode(node, child)
		if node.Parent == nil && child != nil {
			child.color = black
		}
	}
	tree.size -= 1
}

// Returns true if tree does not contain any nodes
func (tree *Tree) Empty() bool {
	return tree.size == 0
}

// Returns number of nodes in the tree.
func (tree *Tree) Size() int {
	return tree.size
}

// Returns all keys in-order
func (tree *Tree) Keys() []interface{} {
	keys := make([]interface{}, tree.size)
	for i, node := range tree.inOrder() {
		keys[i] = node.Key
	}
	return keys
}

// Returns all values in-order based on the key.
func (tree *Tree) Values() []interface{} {
	values := make([]interface{}, tree.size)
	for i, node := range tree.inOrder() {
		values[i] = node.Value
	}
	return values
}

// Removes all nodes from the tree.
func (tree *Tree) Clear() {
	tree.Root = nil
	tree.size = 0
}

func (tree *Tree) String() string {
	str := "RedBlackTree\n"
	if !tree.Empty() {
		output(tree.Root, "", true, &str)
	}
	return str
}

func (node *Node) String() string {
	return fmt.Sprintf("%v", node.Key)
}

// Returns all nodes in order
func (tree *Tree) inOrder() []*Node {
	nodes := make([]*Node, tree.size)
	if tree.size > 0 {
		current := tree.Root
		stack := linkedliststack.New()
		done := false
		count := 0
		for !done {
			if current != nil {
				stack.Push(current)
				current = current.Left
			} else {
				if !stack.Empty() {
					currentPop, _ := stack.Pop()
					current = currentPop.(*Node)
					nodes[count] = current
					count += 1
					current = current.Right
				} else {
					done = true
				}
			}
		}
	}
	return nodes
}

func output(node *Node, prefix string, isTail bool, str *string) {
	if node.Right != nil {
		newPrefix := prefix
		if isTail {
			newPrefix += "│   "
		} else {
			newPrefix += "    "
		}
		output(node.Right, newPrefix, false, str)
	}
	*str += prefix
	if isTail {
		*str += "└── "
	} else {
		*str += "┌── "
	}
	*str += node.String() + "\n"
	if node.Left != nil {
		newPrefix := prefix
		if isTail {
			newPrefix += "    "
		} else {
			newPrefix += "│   "
		}
		output(node.Left, newPrefix, true, str)
	}
}

func (tree *Tree) lookup(key interface{}) *Node {
	node := tree.Root
	for node != nil {
		compare := tree.comparator(key, node.Key)
		switch {
		case compare == 0:
			return node
		case compare < 0:
			node = node.Left
		case compare > 0:
			node = node.Right
		}
	}
	return nil
}

func (node *Node) grandparent() *Node {
	if node != nil && node.Parent != nil {
		return node.Parent.Parent
	}
	return nil
}

func (node *Node) uncle() *Node {
	if node == nil || node.Parent == nil || node.Parent.Parent == nil {
		return nil
	}
	return node.Parent.sibling()
}

func (node *Node) sibling() *Node {
	if node == nil || node.Parent == nil {
		return nil
	}
	if node == node.Parent.Left {
		return node.Parent.Right
	} else {
		return node.Parent.Left
	}
}

func (tree *Tree) rotateLeft(node *Node) {
	right := node.Right
	tree.replaceNode(node, right)
	node.Right = right.Left
	if right.Left != nil {
		right.Left.Parent = node
	}
	right.Left = node
	node.Parent = right
}

func (tree *Tree) rotateRight(node *Node) {
	left := node.Left
	tree.replaceNode(node, left)
	node.Left = left.Right
	if left.Right != nil {
		left.Right.Parent = node
	}
	left.Right = node
	node.Parent = left
}

func (tree *Tree) replaceNode(old *Node, new *Node) {
	if old.Parent == nil {
		tree.Root = new
	} else {
		if old == old.Parent.Left {
			old.Parent.Left = new
		} else {
			old.Parent.Right = new
		}
	}
	if new != nil {
		new.Parent = old.Parent
	}
}

func (tree *Tree) insertCase1(node *Node) {
	if node.Parent == nil {
		node.color = black
	} else {
		tree.insertCase2(node)
	}
}

func (tree *Tree) insertCase2(node *Node) {
	if nodeColor(node.Parent) == black {
		return
	}
	tree.insertCase3(node)
}

func (tree *Tree) insertCase3(node *Node) {
	uncle := node.uncle()
	if nodeColor(uncle) == red {
		node.Parent.color = black
		uncle.color = black
		node.grandparent().color = red
		tree.insertCase1(node.grandparent())
	} else {
		tree.insertCase4(node)
	}
}

func (tree *Tree) insertCase4(node *Node) {
	grandparent := node.grandparent()
	if node == node.Parent.Right && node.Parent == grandparent.Left {
		tree.rotateLeft(node.Parent)
		node = node.Left
	} else if node == node.Parent.Left && node.Parent == grandparent.Right {
		tree.rotateRight(node.Parent)
		node = node.Right
	}
	tree.insertCase5(node)
}

func (tree *Tree) insertCase5(node *Node) {
	node.Parent.color = black
	grandparent := node.grandparent()
	grandparent.color = red
	if node == node.Parent.Left && node.Parent == grandparent.Left {
		tree.rotateRight(grandparent)
	} else if node == node.Parent.Right && node.Parent == grandparent.Right {
		tree.rotateLeft(grandparent)
	}
}

func (node *Node) maximumNode() *Node {
	if node == nil {
		return nil
	}
	for node.Right != nil {
		node = node.Right
	}
	return node
}

func (tree *Tree) deleteCase1(node *Node) {
	if node.Parent == nil {
		return
	} else {
		tree.deleteCase2(node)
	}
}

func (tree *Tree) deleteCase2(node *Node) {
	sibling := node.sibling()
	if nodeColor(sibling) == red {
		node.Parent.color = red
		sibling.color = black
		if node == node.Parent.Left {
			tree.rotateLeft(node.Parent)
		} else {
			tree.rotateRight(node.Parent)
		}
	}
	tree.deleteCase3(node)
}

func (tree *Tree) deleteCase3(node *Node) {
	sibling := node.sibling()
	if nodeColor(node.Parent) == black &&
		nodeColor(sibling) == black &&
		nodeColor(sibling.Left) == black &&
		nodeColor(sibling.Right) == black {
		sibling.color = red
		tree.deleteCase1(node.Parent)
	} else {
		tree.deleteCase4(node)
	}
}

func (tree *Tree) deleteCase4(node *Node) {
	sibling := node.sibling()
	if nodeColor(node.Parent) == red &&
		nodeColor(sibling) == black &&
		nodeColor(sibling.Left) == black &&
		nodeColor(sibling.Right) == black {
		sibling.color = red
		node.Parent.color = black
	} else {
		tree.deleteCase5(node)
	}
}

func (tree *Tree) deleteCase5(node *Node) {
	sibling := node.sibling()
	if node == node.Parent.Left &&
		nodeColor(sibling) == black &&
		nodeColor(sibling.Left) == red &&
		nodeColor(sibling.Right) == black {
		sibling.color = red
		sibling.Left.color = black
		tree.rotateRight(sibling)
	} else if node == node.Parent.Right &&
		nodeColor(sibling) == black &&
		nodeColor(sibling.Right) == red &&
		nodeColor(sibling.Left) == black {
		sibling.color = red
		sibling.Right.color = black
		tree.rotateLeft(sibling)
	}
	tree.deleteCase6(node)
}

func (tree *Tree) deleteCase6(node *Node) {
	sibling := node.sibling()
	sibling.color = nodeColor(node.Parent)
	node.Parent.color = black
	if node == node.Parent.Left && nodeColor(sibling.Right) == red {
		sibling.Right.color = black
		tree.rotateLeft(node.Parent)
	} else if nodeColor(sibling.Left) == red {
		sibling.Left.color = black
		tree.rotateRight(node.Parent)
	}
}

func nodeColor(node *Node) color {
	if node == nil {
		return black
	}
	return node.color
}
<|endoftext|>


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

// Generate a self-signed X.509 certificate for a TLS server. Outputs to
// 'cert.pem' and 'key.pem' and will overwrite existing files.

package main

import (
	"crypto/rsa"
	"crypto/rand"
	"crypto/x509"
	"encoding/pem"
	"flag"
	"log"
	"os"
	"time"
)

var hostName *string = flag.String("host", "127.0.0.1", "Hostname to generate a certificate for")

func main() {
	flag.Parse()

	priv, err := rsa.GenerateKey(rand.Reader, 1024)
	if err != nil {
		log.Fatalf("failed to generate private key: %s", err)
		return
	}

	now := time.Seconds()

	template := x509.Certificate{
		SerialNumber: []byte{0},
		Subject: x509.Name{
			CommonName:   *hostName,
			Organization: []string{"Acme Co"},
		},
		NotBefore: time.SecondsToUTC(now - 300),
		NotAfter:  time.SecondsToUTC(now + 60*60*24*365), // valid for 1 year.

		SubjectKeyId: []byte{1, 2, 3, 4},
		KeyUsage:     x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
	}

	derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
	if err != nil {
		log.Fatalf("Failed to create certificate: %s", err)
		return
	}

	certOut, err := os.Create("cert.pem")
	if err != nil {
		log.Fatalf("failed to open cert.pem for writing: %s", err)
		return
	}
	pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
	certOut.Close()
	log.Print("written cert.pem\n")

	keyOut, err := os.OpenFile("key.pem", os.O_WRONLY|os.O_CREAT|os.O_TRUNC, 0600)
	if err != nil {
		log.Print("failed to open key.pem for writing:", err)
		return
	}
	pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
	keyOut.Close()
	log.Print("written key.pem\n")
}
<commit_msg>crypto/tls/generate_cert.go: fix misspelling of O_CREATE. Fixes #1888.<commit_after>// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Generate a self-signed X.509 certificate for a TLS server. Outputs to
// 'cert.pem' and 'key.pem' and will overwrite existing files.

package main

import (
	"crypto/rsa"
	"crypto/rand"
	"crypto/x509"
	"encoding/pem"
	"flag"
	"log"
	"os"
	"time"
)

var hostName *string = flag.String("host", "127.0.0.1", "Hostname to generate a certificate for")

func main() {
	flag.Parse()

	priv, err := rsa.GenerateKey(rand.Reader, 1024)
	if err != nil {
		log.Fatalf("failed to generate private key: %s", err)
		return
	}

	now := time.Seconds()

	template := x509.Certificate{
		SerialNumber: []byte{0},
		Subject: x509.Name{
			CommonName:   *hostName,
			Organization: []string{"Acme Co"},
		},
		NotBefore: time.SecondsToUTC(now - 300),
		NotAfter:  time.SecondsToUTC(now + 60*60*24*365), // valid for 1 year.

		SubjectKeyId: []byte{1, 2, 3, 4},
		KeyUsage:     x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
	}

	derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
	if err != nil {
		log.Fatalf("Failed to create certificate: %s", err)
		return
	}

	certOut, err := os.Create("cert.pem")
	if err != nil {
		log.Fatalf("failed to open cert.pem for writing: %s", err)
		return
	}
	pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
	certOut.Close()
	log.Print("written cert.pem\n")

	keyOut, err := os.OpenFile("key.pem", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
	if err != nil {
		log.Print("failed to open key.pem for writing:", err)
		return
	}
	pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
	keyOut.Close()
	log.Print("written key.pem\n")
}
<|endoftext|>


<commit_before>// Package websocketproxy is a reverse websocket proxy handler
package websocketproxy

import (
	"io"
	"log"
	"net/http"
	"net/url"

	"github.com/gorilla/websocket"
)

// WebsocketProxy is an HTTP Handler that takes an incoming websocket
// connection and proxies it to another server.
type WebsocketProxy struct {
	// Backend returns the backend URL which the proxy uses to reverse proxy
	// the incoming websocket connection.
	Backend func() *url.URL
}

var upgrader = websocket.Upgrader{
	ReadBufferSize:  4096,
	WriteBufferSize: 4096,
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

// ProxyHandler returns a new http.Handler interface that reverse proxies the
// request to the given target.
func ProxyHandler(target *url.URL) http.Handler {
	return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
		NewProxy(target).ServerHTTP(rw, req)
	})
}

// NewProxy returns a new Websocket reverse proxy that rewrites the
// URL's to the scheme, host and base path provider in target.
func NewProxy(target *url.URL) *WebsocketProxy {
	backend := func() *url.URL { return target }
	return &WebsocketProxy{Backend: backend}
}

// ServerHTTP implements the http.Handler that proxies WebSocket connections.
func (w *WebsocketProxy) ServerHTTP(rw http.ResponseWriter, req *http.Request) {
	connPub, err := upgrader.Upgrade(rw, req, nil)
	if err != nil {
		log.Println(err)
		return
	}
	defer connPub.Close()

	backendURL := w.Backend()

	connKite, _, err := websocket.DefaultDialer.Dial(backendURL.String(), nil)
	if err != nil {
		log.Println("websocket.Dialer", err)
		return
	}
	defer connKite.Close()

	errc := make(chan error, 2)
	cp := func(dst io.Writer, src io.Reader) {
		_, err := io.Copy(dst, src)
		errc <- err
	}

	go cp(connKite.UnderlyingConn(), connPub.UnderlyingConn())
	go cp(connPub.UnderlyingConn(), connKite.UnderlyingConn())
	<-errc
}
<commit_msg>websocket: improve logs<commit_after>// Package websocketproxy is a reverse websocket proxy handler
package websocketproxy

import (
	"io"
	"log"
	"net/http"
	"net/url"

	"github.com/gorilla/websocket"
)

// WebsocketProxy is an HTTP Handler that takes an incoming websocket
// connection and proxies it to another server.
type WebsocketProxy struct {
	// Backend returns the backend URL which the proxy uses to reverse proxy
	// the incoming websocket connection.
	Backend func() *url.URL
}

var upgrader = websocket.Upgrader{
	ReadBufferSize:  4096,
	WriteBufferSize: 4096,
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

// ProxyHandler returns a new http.Handler interface that reverse proxies the
// request to the given target.
func ProxyHandler(target *url.URL) http.Handler {
	return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
		NewProxy(target).ServerHTTP(rw, req)
	})
}

// NewProxy returns a new Websocket reverse proxy that rewrites the
// URL's to the scheme, host and base path provider in target.
func NewProxy(target *url.URL) *WebsocketProxy {
	backend := func() *url.URL { return target }
	return &WebsocketProxy{Backend: backend}
}

// ServerHTTP implements the http.Handler that proxies WebSocket connections.
func (w *WebsocketProxy) ServerHTTP(rw http.ResponseWriter, req *http.Request) {
	connPub, err := upgrader.Upgrade(rw, req, nil)
	if err != nil {
		log.Println("websocketproxy: couldn't upgrade %s", err)
		return
	}
	defer connPub.Close()

	backendURL := w.Backend()

	connKite, _, err := websocket.DefaultDialer.Dial(backendURL.String(), nil)
	if err != nil {
		log.Println("websocketproxy: couldn't dial to remote backend url %s", err)
		return
	}
	defer connKite.Close()

	errc := make(chan error, 2)
	cp := func(dst io.Writer, src io.Reader) {
		_, err := io.Copy(dst, src)
		errc <- err
	}

	go cp(connKite.UnderlyingConn(), connPub.UnderlyingConn())
	go cp(connPub.UnderlyingConn(), connKite.UnderlyingConn())
	<-errc
}
<|endoftext|>


<commit_before>package server

import (
	"fmt"

	"go.pachyderm.com/pachyderm/src/pkg/deploy"
	"golang.org/x/net/context"

	"go.pedge.io/google-protobuf"
	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/api/unversioned"
	client "k8s.io/kubernetes/pkg/client/unversioned"
)

var (
	emptyInstance = &google_protobuf.Empty{}
	pfsdImage     = "pachyderm/pfsd"
	etcdImage     = "gcr.io/google_containers/etcd:2.0.12"
)

type apiServer struct {
	client *client.Client
}

func newAPIServer(client *client.Client) APIServer {
	return &apiServer{client}
}

func (a *apiServer) CreateCluster(ctx context.Context, request *deploy.CreateClusterRequest) (*google_protobuf.Empty, error) {
	if _, err := a.client.ReplicationControllers(api.NamespaceDefault).Create(etcdReplicationController()); err != nil {
		return nil, err
	}

	if _, err := a.client.Services(api.NamespaceDefault).Create(etcdService()); err != nil {
		return nil, err
	}
	if _, err := a.client.ReplicationControllers(api.NamespaceDefault).Create(
		pfsReplicationController(
			request.Cluster.Name,
			request.Nodes,
			request.Shards,
			request.Replicas,
		),
	); err != nil {
		return nil, err
	}
	return emptyInstance, nil
}

func (a *apiServer) UpdateCluster(ctx context.Context, request *deploy.UpdateClusterRequest) (*google_protobuf.Empty, error) {
	return emptyInstance, nil
}

func (a *apiServer) InspectCluster(ctx context.Context, request *deploy.InspectClusterRequest) (*deploy.ClusterInfo, error) {
	return nil, nil
}

func (a *apiServer) ListCluster(ctx context.Context, request *deploy.ListClusterRequest) (*deploy.ClusterInfos, error) {
	return nil, nil
}

func (a *apiServer) DeleteCluster(ctx context.Context, request *deploy.DeleteClusterRequest) (*google_protobuf.Empty, error) {
	return emptyInstance, nil
}

func pfsReplicationController(name string, nodes uint64, shards uint64, replicas uint64) *api.ReplicationController {
	app := fmt.Sprintf("pfsd-%s", name)
	return &api.ReplicationController{
		unversioned.TypeMeta{
			Kind:       "ReplicationController",
			APIVersion: "v1",
		},
		api.ObjectMeta{
			Name: fmt.Sprintf("pfsd-rc-%s", name),
			Labels: map[string]string{
				"app": app,
			},
		},
		api.ReplicationControllerSpec{
			Replicas: int(nodes),
			Selector: map[string]string{
				"app": app,
			},
			Template: &api.PodTemplateSpec{
				api.ObjectMeta{
					Name: fmt.Sprintf("pfsd-%s", name),
					Labels: map[string]string{
						"app": app,
					},
				},
				api.PodSpec{
					Containers: []api.Container{
						{
							Name:  "pfsd",
							Image: pfsdImage,
							Env: []api.EnvVar{
								{
									Name:  "PFS_DRIVER_ROOT",
									Value: "/pfs/btrfs",
								},
							},
							Ports: []api.ContainerPort{
								{
									ContainerPort: 650,
									Name:          "api-grpc-port",
								},
								{
									ContainerPort: 750,
									Name:          "api-http-port",
								},
								{
									ContainerPort: 1050,
									Name:          "trace-port",
								},
							},
							VolumeMounts: []api.VolumeMount{
								{
									Name:      "pfs-disk",
									MountPath: "/pfs/btrfs",
								},
							},
						},
					},
					Volumes: []api.Volume{
						{
							Name: "pfs-disk",
							//api.VolumeSource{
							//	GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{
							//		PDName: "pch-pfs",
							//		FSType: "btrfs",
							//	},
							//},
						},
					},
				},
			},
		},
		api.ReplicationControllerStatus{},
	}
}

func etcdReplicationController() *api.ReplicationController {
	app := "etcd"
	return &api.ReplicationController{
		unversioned.TypeMeta{
			Kind:       "ReplicationController",
			APIVersion: "v1",
		},
		api.ObjectMeta{
			Name: "etcd-rc",
			Labels: map[string]string{
				"app": app,
			},
		},
		api.ReplicationControllerSpec{
			Replicas: 1,
			Selector: map[string]string{
				"app": app,
			},
			Template: &api.PodTemplateSpec{
				api.ObjectMeta{
					Name: "etcd-pod",
					Labels: map[string]string{
						"app": app,
					},
				},
				api.PodSpec{
					Containers: []api.Container{
						{
							Name:  "etcd",
							Image: etcdImage,
							//TODO figure out how to get a cluster of these to talk to each other
							Command: []string{"/usr/local/bin/etcd", "--addr=127.0.0.1:4001", "--bind-addr=0.0.0.0:4001", "--data-dir=/var/etcd/data"},
							Env: []api.EnvVar{
								{
									Name:  "PFS_DRIVER_ROOT",
									Value: "/pfs/btrfs",
								},
							},
							Ports: []api.ContainerPort{
								{
									ContainerPort: 2379,
									Name:          "client-port",
								},
								{
									ContainerPort: 2380,
									Name:          "peer-port",
								},
							},
							VolumeMounts: []api.VolumeMount{
								{
									Name:      "etcd-storage",
									MountPath: "/data/etcd",
								},
							},
						},
					},
					Volumes: []api.Volume{
						{
							Name: "etcd-storage",
						},
					},
				},
			},
		},
		api.ReplicationControllerStatus{},
	}
}

func etcdService() *api.Service {
	app := "etcd"
	return &api.Service{
		unversioned.TypeMeta{
			Kind:       "Service",
			APIVersion: "v1",
		},
		api.ObjectMeta{
			Name: "etcd",
			Labels: map[string]string{
				"app": app,
			},
		},
		api.ServiceSpec{
			Selector: map[string]string{
				"app": app,
			},
			Ports: []api.ServicePort{
				{
					Port: 2379,
					Name: "client-port",
				},
				{
					Port: 2380,
					Name: "peer-port",
				},
			},
		},
		api.ServiceStatus{},
	}
}
<commit_msg>Fix a few bugs with etcd rc.<commit_after>package server

import (
	"fmt"

	"go.pachyderm.com/pachyderm/src/pkg/deploy"
	"golang.org/x/net/context"

	"go.pedge.io/google-protobuf"
	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/api/unversioned"
	client "k8s.io/kubernetes/pkg/client/unversioned"
)

var (
	emptyInstance = &google_protobuf.Empty{}
	pfsdImage     = "pachyderm/pfsd"
	etcdImage     = "gcr.io/google_containers/etcd:2.0.12"
)

type apiServer struct {
	client *client.Client
}

func newAPIServer(client *client.Client) APIServer {
	return &apiServer{client}
}

func (a *apiServer) CreateCluster(ctx context.Context, request *deploy.CreateClusterRequest) (*google_protobuf.Empty, error) {
	if _, err := a.client.ReplicationControllers(api.NamespaceDefault).Create(etcdReplicationController()); err != nil {
		return nil, err
	}

	if _, err := a.client.Services(api.NamespaceDefault).Create(etcdService()); err != nil {
		return nil, err
	}
	if _, err := a.client.ReplicationControllers(api.NamespaceDefault).Create(
		pfsReplicationController(
			request.Cluster.Name,
			request.Nodes,
			request.Shards,
			request.Replicas,
		),
	); err != nil {
		return nil, err
	}
	return emptyInstance, nil
}

func (a *apiServer) UpdateCluster(ctx context.Context, request *deploy.UpdateClusterRequest) (*google_protobuf.Empty, error) {
	return emptyInstance, nil
}

func (a *apiServer) InspectCluster(ctx context.Context, request *deploy.InspectClusterRequest) (*deploy.ClusterInfo, error) {
	return nil, nil
}

func (a *apiServer) ListCluster(ctx context.Context, request *deploy.ListClusterRequest) (*deploy.ClusterInfos, error) {
	return nil, nil
}

func (a *apiServer) DeleteCluster(ctx context.Context, request *deploy.DeleteClusterRequest) (*google_protobuf.Empty, error) {
	return emptyInstance, nil
}

func pfsReplicationController(name string, nodes uint64, shards uint64, replicas uint64) *api.ReplicationController {
	app := fmt.Sprintf("pfsd-%s", name)
	return &api.ReplicationController{
		unversioned.TypeMeta{
			Kind:       "ReplicationController",
			APIVersion: "v1",
		},
		api.ObjectMeta{
			Name: fmt.Sprintf("pfsd-rc-%s", name),
			Labels: map[string]string{
				"app": app,
			},
		},
		api.ReplicationControllerSpec{
			Replicas: int(nodes),
			Selector: map[string]string{
				"app": app,
			},
			Template: &api.PodTemplateSpec{
				api.ObjectMeta{
					Name: fmt.Sprintf("pfsd-%s", name),
					Labels: map[string]string{
						"app": app,
					},
				},
				api.PodSpec{
					Containers: []api.Container{
						{
							Name:  "pfsd",
							Image: pfsdImage,
							Env: []api.EnvVar{
								{
									Name:  "PFS_DRIVER_ROOT",
									Value: "/pfs/btrfs",
								},
							},
							Ports: []api.ContainerPort{
								{
									ContainerPort: 650,
									Name:          "api-grpc-port",
								},
								{
									ContainerPort: 750,
									Name:          "api-http-port",
								},
								{
									ContainerPort: 1050,
									Name:          "trace-port",
								},
							},
							VolumeMounts: []api.VolumeMount{
								{
									Name:      "pfs-disk",
									MountPath: "/pfs/btrfs",
								},
							},
						},
					},
					Volumes: []api.Volume{
						{
							Name: "pfs-disk",
							//api.VolumeSource{
							//	GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{
							//		PDName: "pch-pfs",
							//		FSType: "btrfs",
							//	},
							//},
						},
					},
				},
			},
		},
		api.ReplicationControllerStatus{},
	}
}

func etcdReplicationController() *api.ReplicationController {
	app := "etcd"
	return &api.ReplicationController{
		unversioned.TypeMeta{
			Kind:       "ReplicationController",
			APIVersion: "v1",
		},
		api.ObjectMeta{
			Name: "etcd-rc",
			Labels: map[string]string{
				"app": app,
			},
		},
		api.ReplicationControllerSpec{
			Replicas: 1,
			Selector: map[string]string{
				"app": app,
			},
			Template: &api.PodTemplateSpec{
				api.ObjectMeta{
					Name: "etcd-pod",
					Labels: map[string]string{
						"app": app,
					},
				},
				api.PodSpec{
					Containers: []api.Container{
						{
							Name:  "etcd",
							Image: etcdImage,
							//TODO figure out how to get a cluster of these to talk to each other
							Command: []string{"/usr/local/bin/etcd", "--bind-addr=0.0.0.0:2379", "--data-dir=/var/etcd/data"},
							Ports: []api.ContainerPort{
								{
									ContainerPort: 2379,
									Name:          "client-port",
								},
								{
									ContainerPort: 2380,
									Name:          "peer-port",
								},
							},
							VolumeMounts: []api.VolumeMount{
								{
									Name:      "etcd-storage",
									MountPath: "/var/data/etcd",
								},
							},
						},
					},
					Volumes: []api.Volume{
						{
							Name: "etcd-storage",
						},
					},
				},
			},
		},
		api.ReplicationControllerStatus{},
	}
}

func etcdService() *api.Service {
	app := "etcd"
	return &api.Service{
		unversioned.TypeMeta{
			Kind:       "Service",
			APIVersion: "v1",
		},
		api.ObjectMeta{
			Name: "etcd",
			Labels: map[string]string{
				"app": app,
			},
		},
		api.ServiceSpec{
			Selector: map[string]string{
				"app": app,
			},
			Ports: []api.ServicePort{
				{
					Port: 2379,
					Name: "client-port",
				},
				{
					Port: 2380,
					Name: "peer-port",
				},
			},
		},
		api.ServiceStatus{},
	}
}
<|endoftext|>


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

// +build race

package race_test

import (
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"strings"
	"testing"
)

func TestOutput(t *testing.T) {
	for _, test := range tests {
		dir, err := ioutil.TempDir("", "go-build")
		if err != nil {
			t.Fatalf("failed to create temp directory: %v", err)
		}
		defer os.RemoveAll(dir)
		src := filepath.Join(dir, "main.go")
		f, err := os.Create(src)
		if err != nil {
			t.Fatalf("failed to create file: %v", err)
		}
		_, err = f.WriteString(test.source)
		if err != nil {
			f.Close()
			t.Fatalf("failed to write: %v", err)
		}
		if err := f.Close(); err != nil {
			t.Fatalf("failed to close file: %v", err)
		}
		// Pass -l to the compiler to test stack traces.
		cmd := exec.Command("go", "run", "-race", "-gcflags=-l", src)
		// GODEBUG spoils program output, GOMAXPROCS makes it flaky.
		for _, env := range os.Environ() {
			if strings.HasPrefix(env, "GODEBUG=") ||
				strings.HasPrefix(env, "GOMAXPROCS=") {
				continue
			}
			cmd.Env = append(cmd.Env, env)
		}
		got, _ := cmd.CombinedOutput()
		if !regexp.MustCompile(test.re).MatchString(string(got)) {
			t.Fatalf("failed test case %v, expect:\n%v\ngot:\n%s",
				test.name, test.re, got)
		}
	}
}

var tests = []struct {
	name   string
	source string
	re     string
}{
	{"simple", `
package main
import "time"
func main() {
	done := make(chan bool)
	x := 0
	startRacer(&x, done)
	store(&x, 43)
	<-done
}
func store(x *int, v int) {
	*x = v
}
func startRacer(x *int, done chan bool) {
	go racer(x, done)
}
func racer(x *int, done chan bool) {
	time.Sleep(10*time.Millisecond)
	store(x, 42)
	done <- true
}
`, `==================
WARNING: DATA RACE
Write by goroutine [0-9]:
  main\.store\(\)
      .*/main\.go:12 \+0x[0-9,a-f]+
  main\.racer\(\)
      .*/main\.go:19 \+0x[0-9,a-f]+

Previous write by main goroutine:
  main\.store\(\)
      .*/main\.go:12 \+0x[0-9,a-f]+
  main\.main\(\)
      .*/main\.go:8 \+0x[0-9,a-f]+

Goroutine [0-9] \(running\) created at:
  main\.startRacer\(\)
      .*/main\.go:15 \+0x[0-9,a-f]+
  main\.main\(\)
      .*/main\.go:7 \+0x[0-9,a-f]+
==================
Found 1 data race\(s\)
exit status 66
`},
}
<commit_msg>runtime/race: add output tests for different GORACE params<commit_after>// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build race

package race_test

import (
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"strings"
	"testing"
)

func TestOutput(t *testing.T) {
	for _, test := range tests {
		dir, err := ioutil.TempDir("", "go-build")
		if err != nil {
			t.Fatalf("failed to create temp directory: %v", err)
		}
		defer os.RemoveAll(dir)
		src := filepath.Join(dir, "main.go")
		f, err := os.Create(src)
		if err != nil {
			t.Fatalf("failed to create file: %v", err)
		}
		_, err = f.WriteString(test.source)
		if err != nil {
			f.Close()
			t.Fatalf("failed to write: %v", err)
		}
		if err := f.Close(); err != nil {
			t.Fatalf("failed to close file: %v", err)
		}
		// Pass -l to the compiler to test stack traces.
		cmd := exec.Command("go", "run", "-race", "-gcflags=-l", src)
		// GODEBUG spoils program output, GOMAXPROCS makes it flaky.
		for _, env := range os.Environ() {
			if strings.HasPrefix(env, "GODEBUG=") ||
				strings.HasPrefix(env, "GOMAXPROCS=") ||
				strings.HasPrefix(env, "GORACE=") {
				continue
			}
			cmd.Env = append(cmd.Env, env)
		}
		cmd.Env = append(cmd.Env, "GORACE="+test.gorace)
		got, _ := cmd.CombinedOutput()
		if !regexp.MustCompile(test.re).MatchString(string(got)) {
			t.Fatalf("failed test case %v, expect:\n%v\ngot:\n%s",
				test.name, test.re, got)
		}
	}
}

var tests = []struct {
	name   string
	gorace string
	source string
	re     string
}{
	{"simple", "atexit_sleep_ms=0", `
package main
import "time"
func main() {
	done := make(chan bool)
	x := 0
	startRacer(&x, done)
	store(&x, 43)
	<-done
}
func store(x *int, v int) {
	*x = v
}
func startRacer(x *int, done chan bool) {
	go racer(x, done)
}
func racer(x *int, done chan bool) {
	time.Sleep(10*time.Millisecond)
	store(x, 42)
	done <- true
}
`, `==================
WARNING: DATA RACE
Write by goroutine [0-9]:
  main\.store\(\)
      .+/main\.go:12 \+0x[0-9,a-f]+
  main\.racer\(\)
      .+/main\.go:19 \+0x[0-9,a-f]+

Previous write by main goroutine:
  main\.store\(\)
      .+/main\.go:12 \+0x[0-9,a-f]+
  main\.main\(\)
      .+/main\.go:8 \+0x[0-9,a-f]+

Goroutine [0-9] \(running\) created at:
  main\.startRacer\(\)
      .+/main\.go:15 \+0x[0-9,a-f]+
  main\.main\(\)
      .+/main\.go:7 \+0x[0-9,a-f]+
==================
Found 1 data race\(s\)
exit status 66
`},

	{"exitcode", "atexit_sleep_ms=0 exitcode=13", `
package main
func main() {
	done := make(chan bool)
	x := 0
	go func() {
		x = 42
		done <- true
	}()
	x = 43
	<-done
}
`, `exit status 13`},

	{"strip_path_prefix", "atexit_sleep_ms=0 strip_path_prefix=/main.", `
package main
func main() {
	done := make(chan bool)
	x := 0
	go func() {
		x = 42
		done <- true
	}()
	x = 43
	<-done
}
`, `
      go:7 \+0x[0-9,a-f]+
`},

	{"halt_on_error", "atexit_sleep_ms=0 halt_on_error=1", `
package main
func main() {
	done := make(chan bool)
	x := 0
	go func() {
		x = 42
		done <- true
	}()
	x = 43
	<-done
}
`, `
==================
exit status 66
`},
}
<|endoftext|>