<commit_before>package server

type IncomingMessage struct {
	Client Client
	Player *Player
	Body   map[string]string
}

func newIncomingMessage(client Client, body map[string]string) *IncomingMessage {
	return &IncomingMessage{
		Client: client,
		Player: client.GetPlayer(),
		Body:   body,
	}
}

type Notification struct {
	MessageType string `json:"msg_type"`
}

type Response struct {
	MessageType string `json:"msg_type"`
	Successful  bool   `json:"success"`
	ResultCode  string `json:"result_code"`
}

type LoginResponse struct {
	Response
	Player *Player `json:"player"`
}

// handle an incoming login message
func (w *World) handleLogin(message *IncomingMessage) {
	// is this connection already authenticated?
	// see if we can find an existing player ..
	/*
		p := FindPlayerByClient(message.Client)
		if p != nil {
			// already authenticated, can't login again
			// TODO
			// note that this isn't really working; the same username can log on twice
			// instead the old player should be kicked and the new player take over
			p.Send(LoginResponse{
				Response: Response{
					MessageType: "login_response",
					Successful:  false,
					ResultCode:  "ALREADY_AUTHENTICATED",
				},
			})
			return
		}
	*/

	// todo authentication and stuff
	player := NewPlayer(message.Body["player_name"], message.Client)
	message.Client.SetPlayer(player)
	message.Player = player
	w.addPlayer(player)
	player.Send(LoginResponse{
		Response: Response{
			MessageType: "login_response",
			Successful:  true,
			ResultCode:  "OK",
		},
		Player: player,
	})
}

type TellNotification struct {
	Notification
	From  string `json:"from"`
	Value string `json:"value"`
}

func (w *World) handleTell(message *IncomingMessage) {
	fromName := message.Player.Name
	toPlayer := w.findPlayerByName(message.Body["to"])
	value := message.Body["value"]

	if toPlayer == nil {
		message.Player.Send(Response{
			MessageType: "tell",
			Successful:  false,
			ResultCode:  "TO_PLAYER_NOT_FOUND",
		})
	} else {
		toPlayer.Send(TellNotification{
			Notification: Notification{MessageType: "tell"},
			From:         fromName,
			Value:        value,
		})
		message.Player.Send(Response{
			MessageType: "tell",
			Successful:  true,
			ResultCode:  "OK",
		})
	}
}

type TellAllNotification struct {
	Notification
	Value  string `json:"value"`
	Sender string `json:"sender"`
}

// Tell everybody in the game something.
func (w *World) handleTellAll(message *IncomingMessage) {
	if val, ok := message.Body["value"]; ok {
		w.SendToAllPlayers(TellAllNotification{
			Notification: Notification{
				MessageType: "tell_all_notification",
			},
			Value:  val,
			Sender: message.Player.Name,
		})
	} else {
		message.Player.Send(Response{
			MessageType: "tell_all",
			Successful:  false,
			ResultCode:  "NO_VALUE",
		})
	}
}
<commit_msg>handling more error cases for login<commit_after>package server

type IncomingMessage struct {
	Client Client
	Player *Player
	Body   map[string]string
}

func newIncomingMessage(client Client, body map[string]string) *IncomingMessage {
	return &IncomingMessage{
		Client: client,
		Player: client.GetPlayer(),
		Body:   body,
	}
}

type Notification struct {
	MessageType string `json:"msg_type"`
}

type Response struct {
	MessageType string `json:"msg_type"`
	Successful  bool   `json:"success"`
	ResultCode  string `json:"result_code"`
}

type LoginResponse struct {
	Response
	Player *Player `json:"player"`
}

// handle an incoming login message
func (w *World) handleLogin(message *IncomingMessage) {
	// is this connection already authenticated?
	// see if we can find an existing player ..
	if message.Client.GetPlayer() != nil {
		// you've already got one
		message.Client.Send(LoginResponse{
			Response:Response{
				MessageType:"login_response",
				Successful: false,
				ResultCode: "PLAYER_ALREADY_ATTACHED",
			},
		})
		return
	}
	// what if player is logged in on a different client?
	// TODO
	/*
		p := FindPlayerByClient(message.Client)
		if p != nil {
			// already authenticated, can't login again
			// TODO
			// note that this isn't really working; the same username can log on twice
			// instead the old player should be kicked and the new player take over
			p.Send(LoginResponse{
				Response: Response{
					MessageType: "login_response",
					Successful:  false,
					ResultCode:  "ALREADY_AUTHENTICATED",
				},
			})
			return
		}
	*/

	// todo authentication and stuff
	player := NewPlayer(message.Body["player_name"], message.Client)
	message.Client.SetPlayer(player)
	message.Player = player
	w.addPlayer(player)
	player.Send(LoginResponse{
		Response: Response{
			MessageType: "login_response",
			Successful:  true,
			ResultCode:  "OK",
		},
		Player: player,
	})
}

type TellNotification struct {
	Notification
	From  string `json:"from"`
	Value string `json:"value"`
}

func (w *World) handleTell(message *IncomingMessage) {
	fromName := message.Player.Name
	toPlayer := w.findPlayerByName(message.Body["to"])
	value := message.Body["value"]

	if toPlayer == nil {
		message.Player.Send(Response{
			MessageType: "tell",
			Successful:  false,
			ResultCode:  "TO_PLAYER_NOT_FOUND",
		})
	} else {
		toPlayer.Send(TellNotification{
			Notification: Notification{MessageType: "tell"},
			From:         fromName,
			Value:        value,
		})
		message.Player.Send(Response{
			MessageType: "tell",
			Successful:  true,
			ResultCode:  "OK",
		})
	}
}

type TellAllNotification struct {
	Notification
	Value  string `json:"value"`
	Sender string `json:"sender"`
}

// Tell everybody in the game something.
func (w *World) handleTellAll(message *IncomingMessage) {
	if val, ok := message.Body["value"]; ok {
		w.SendToAllPlayers(TellAllNotification{
			Notification: Notification{
				MessageType: "tell_all_notification",
			},
			Value:  val,
			Sender: message.Player.Name,
		})
	} else {
		message.Player.Send(Response{
			MessageType: "tell_all",
			Successful:  false,
			ResultCode:  "NO_VALUE",
		})
	}
}
<|endoftext|>


<commit_before>package socks

import (
	"context"
	"net"
	"net/http"
	"os"
	"os/exec"
	"testing"
	"time"

	"github.com/cybozu-go/cmd"
)

func hasIPv6() bool {
	if os.Getenv("TRAVIS") == "true" {
		return false
	}
	ln, err := net.Listen("tcp", "[::1]:29343")
	if err != nil {
		return false
	}
	ln.Close()
	return true
}

func TestServerBasic(t *testing.T) {
	t.Parallel()

	_, err := exec.LookPath("curl")
	if err != nil {
		t.Skip("curl not found")
	}

	addr := "localhost:20080"
	env := cmd.NewEnvironment(context.Background())
	s := &Server{
		Env: env,
	}
	ln, err := net.Listen("tcp", ":20080")
	if err != nil {
		t.Skip(err)
	}
	s.Serve(ln)

	mux := http.NewServeMux()
	mux.HandleFunc("/ok", func(w http.ResponseWriter, r *http.Request) {})
	hs := &http.Server{
		Addr:    ":20081",
		Handler: mux,
	}
	go hs.ListenAndServe()

	time.Sleep(10 * time.Millisecond)

	url1 := "http://localhost:20081/ok"
	curl := exec.Command("curl", "-4", "-I", "--socks4", addr, url1)
	out, err := curl.Output()
	if err != nil {
		t.Error(err)
		t.Log(string(out))
	}

	curl = exec.Command("curl", "-4", "-I", "--socks4a", addr, url1)
	out, err = curl.Output()
	if err != nil {
		t.Error(err)
		t.Log(string(out))
	}

	curl = exec.Command("curl", "-4", "-I", "--socks5", addr, url1)
	out, err = curl.Output()
	if err != nil {
		t.Error(err)
		t.Log(string(out))
	}

	curl = exec.Command("curl", "-4", "-I", "--socks5-hostname", addr, url1)
	out, err = curl.Output()
	if err != nil {
		t.Error(err)
		t.Log(string(out))
	}

	if hasIPv6() {
		curl = exec.Command("curl", "-6", "-I", "--socks5", addr, url1)
		out, err = curl.Output()
		if err != nil {
			t.Error(err)
			t.Log(string(out))
		}

		curl = exec.Command("curl", "-6", "-I", "--socks5-hostname", addr, url1)
		out, err = curl.Output()
		if err != nil {
			t.Error(err)
			t.Log(string(out))
		}
	}

	env.Cancel(nil)
	err = env.Wait()
	if err != nil {
		t.Error(err)
	}
}

type authenticator struct{}

func (a authenticator) Authenticate(r *Request) bool {
	switch r.Username {
	case "root":
		return true
	case "user":
		return r.Password == "pass"
	}
	return false
}

func TestServerAuth(t *testing.T) {
	t.Parallel()

	_, err := exec.LookPath("curl")
	if err != nil {
		t.Skip("curl not found")
	}

	addr := "localhost:20082"
	env := cmd.NewEnvironment(context.Background())
	s := &Server{
		Auth: authenticator{},
		Env:  env,
	}
	ln, err := net.Listen("tcp", ":20082")
	if err != nil {
		t.Skip(err)
	}
	s.Serve(ln)

	mux := http.NewServeMux()
	mux.HandleFunc("/ok", func(w http.ResponseWriter, r *http.Request) {})
	hs := &http.Server{
		Addr:    ":20083",
		Handler: mux,
	}
	go hs.ListenAndServe()

	time.Sleep(10 * time.Millisecond)

	url1 := "http://localhost:20083/ok"
	curl := exec.Command("curl", "-4", "-I", "--socks4", addr, url1)
	err = curl.Run()
	if err == nil {
		t.Error("authentication is necessary")
	}

	curl = exec.Command("curl", "-4", "-I", "-U", "root:", "--socks4", addr, url1)
	out, err := curl.CombinedOutput()
	if err != nil {
		t.Error(err)
		t.Log(string(out))
	}

	curl = exec.Command("curl", "-4", "-I", "-U", "root:", "--socks4a", addr, url1)
	out, err = curl.CombinedOutput()
	if err != nil {
		t.Error(err)
		t.Log(string(out))
	}

	curl = exec.Command("curl", "-4", "-I", "--socks5", addr, url1)
	err = curl.Run()
	if err == nil {
		t.Error("authenticatoin is necessary")
	}

	curl = exec.Command("curl", "-4", "-I", "-U", "root:", "--socks5", addr, url1)
	out, err = curl.CombinedOutput()
	if err != nil {
		t.Error(err)
		t.Log(string(out))
	}

	curl = exec.Command("curl", "-4", "-I", "-U", "user:pass", "--socks5", addr, url1)
	out, err = curl.CombinedOutput()
	if err != nil {
		t.Error(err)
		t.Log(string(out))
	}

	curl = exec.Command("curl", "-4", "-I", "-U", "user:", "--socks5", addr, url1)
	out, err = curl.CombinedOutput()
	if err == nil {
		t.Error("authentication should fail")
	}

	curl = exec.Command("curl", "-4", "-I", "-U", "user:bad", "--socks5", addr, url1)
	out, err = curl.CombinedOutput()
	if err == nil {
		t.Error("authentication should fail")
	}

	if hasIPv6() {
		curl = exec.Command("curl", "-6", "-I", "-U", "user:pass", "--socks5", addr, url1)
		out, err = curl.CombinedOutput()
		if err != nil {
			t.Error(err)
			t.Log(string(out))
		}
	}

	env.Cancel(nil)
	err = env.Wait()
	if err != nil {
		t.Error(err)
	}
}

type rules struct{}

func (ru rules) Match(r *Request) bool {
	// Allow only request with hostname
	return len(r.Hostname) > 0
}

func TestServerRules(t *testing.T) {
	t.Parallel()

	_, err := exec.LookPath("curl")
	if err != nil {
		t.Skip("curl not found")
	}

	addr := "localhost:20084"
	env := cmd.NewEnvironment(context.Background())
	s := &Server{
		Rules: rules{},
		Env:   env,
	}
	ln, err := net.Listen("tcp", ":20084")
	if err != nil {
		t.Skip(err)
	}
	s.Serve(ln)

	mux := http.NewServeMux()
	mux.HandleFunc("/ok", func(w http.ResponseWriter, r *http.Request) {})
	hs := &http.Server{
		Addr:    ":20085",
		Handler: mux,
	}
	go hs.ListenAndServe()

	time.Sleep(10 * time.Millisecond)

	url1 := "http://localhost:20085/ok"
	curl := exec.Command("curl", "-4", "-I", "--socks4", addr, url1)
	err = curl.Run()
	if err == nil {
		t.Error("SOCKS4 should be denied")
	}

	curl = exec.Command("curl", "-4", "-I", "--socks4a", addr, url1)
	out, err := curl.CombinedOutput()
	if err != nil {
		t.Error(err)
		t.Log(string(out))
	}

	curl = exec.Command("curl", "-4", "-I", "--socks5", addr, url1)
	err = curl.Run()
	if err == nil {
		t.Error("SOCKS5 w/o hostname should be denied")
	}

	if hasIPv6() {
		curl = exec.Command("curl", "-6", "-I", "--socks5-hostname", addr, url1)
		out, err = curl.CombinedOutput()
		if err != nil {
			t.Error(err)
			t.Log(string(out))
		}
	}

	env.Cancel(nil)
	err = env.Wait()
	if err != nil {
		t.Error(err)
	}
}

func TestServerError(t *testing.T) {
	t.Parallel()

	_, err := exec.LookPath("curl")
	if err != nil {
		t.Skip("curl not found")
	}

	addr := "localhost:20086"
	env := cmd.NewEnvironment(context.Background())
	s := &Server{
		Env: env,
	}
	ln, err := net.Listen("tcp", ":20086")
	if err != nil {
		t.Skip(err)
	}
	s.Serve(ln)

	time.Sleep(10 * time.Millisecond)

	url1 := "http://localhost:20087/ok"
	curl := exec.Command("curl", "-4", "-I", "--socks4", addr, url1)
	out, err := curl.CombinedOutput()
	if err == nil {
		t.Error("no listener on localhost:20087")
	}
	t.Log(string(out))

	curl = exec.Command("curl", "-4", "-I", "--socks5", addr, url1)
	out, err = curl.CombinedOutput()
	if err == nil {
		t.Error("no listener on localhost:20087")
	}
	t.Log(string(out))

	env.Cancel(nil)
	err = env.Wait()
	if err != nil {
		t.Error(err)
	}
}
<commit_msg>Fix test for review.<commit_after>package socks

import (
	"context"
	"net"
	"net/http"
	"os"
	"os/exec"
	"testing"
	"time"

	"github.com/cybozu-go/cmd"
)

func hasIPv6() bool {
	if os.Getenv("TRAVIS") == "true" {
		return false
	}
	ln, err := net.Listen("tcp", "[::1]:29343")
	if err != nil {
		return false
	}
	ln.Close()
	return true
}

func TestServerBasic(t *testing.T) {
	t.Parallel()

	_, err := exec.LookPath("curl")
	if err != nil {
		t.Skip("curl not found")
	}

	addr := "localhost:20080"
	env := cmd.NewEnvironment(context.Background())
	s := &Server{
		Env: env,
	}
	ln, err := net.Listen("tcp", ":20080")
	if err != nil {
		t.Skip(err)
	}
	s.Serve(ln)

	mux := http.NewServeMux()
	mux.HandleFunc("/ok", func(w http.ResponseWriter, r *http.Request) {})
	hs := &http.Server{
		Addr:    ":20081",
		Handler: mux,
	}
	go hs.ListenAndServe()

	time.Sleep(10 * time.Millisecond)

	url1 := "http://localhost:20081/ok"
	curl := exec.Command("curl", "-4", "-I", "--socks4", addr, url1)
	out, err := curl.Output()
	if err != nil {
		t.Error(err)
		t.Log(string(out))
	}

	curl = exec.Command("curl", "-4", "-I", "--socks4a", addr, url1)
	out, err = curl.Output()
	if err != nil {
		t.Error(err)
		t.Log(string(out))
	}

	curl = exec.Command("curl", "-4", "-I", "--socks5", addr, url1)
	out, err = curl.Output()
	if err != nil {
		t.Error(err)
		t.Log(string(out))
	}

	curl = exec.Command("curl", "-4", "-I", "--socks5-hostname", addr, url1)
	out, err = curl.Output()
	if err != nil {
		t.Error(err)
		t.Log(string(out))
	}

	if !hasIPv6() {
		goto DONE
	}

	curl = exec.Command("curl", "-6", "-I", "--socks5", addr, url1)
	out, err = curl.Output()
	if err != nil {
		t.Error(err)
		t.Log(string(out))
	}

	curl = exec.Command("curl", "-6", "-I", "--socks5-hostname", addr, url1)
	out, err = curl.Output()
	if err != nil {
		t.Error(err)
		t.Log(string(out))
	}

DONE:
	env.Cancel(nil)
	err = env.Wait()
	if err != nil {
		t.Error(err)
	}
}

type authenticator struct{}

func (a authenticator) Authenticate(r *Request) bool {
	switch r.Username {
	case "root":
		return true
	case "user":
		return r.Password == "pass"
	}
	return false
}

func TestServerAuth(t *testing.T) {
	t.Parallel()

	_, err := exec.LookPath("curl")
	if err != nil {
		t.Skip("curl not found")
	}

	addr := "localhost:20082"
	env := cmd.NewEnvironment(context.Background())
	s := &Server{
		Auth: authenticator{},
		Env:  env,
	}
	ln, err := net.Listen("tcp", ":20082")
	if err != nil {
		t.Skip(err)
	}
	s.Serve(ln)

	mux := http.NewServeMux()
	mux.HandleFunc("/ok", func(w http.ResponseWriter, r *http.Request) {})
	hs := &http.Server{
		Addr:    ":20083",
		Handler: mux,
	}
	go hs.ListenAndServe()

	time.Sleep(10 * time.Millisecond)

	url1 := "http://localhost:20083/ok"
	curl := exec.Command("curl", "-4", "-I", "--socks4", addr, url1)
	err = curl.Run()
	if err == nil {
		t.Error("authentication is necessary")
	}

	curl = exec.Command("curl", "-4", "-I", "-U", "root:", "--socks4", addr, url1)
	out, err := curl.CombinedOutput()
	if err != nil {
		t.Error(err)
		t.Log(string(out))
	}

	curl = exec.Command("curl", "-4", "-I", "-U", "root:", "--socks4a", addr, url1)
	out, err = curl.CombinedOutput()
	if err != nil {
		t.Error(err)
		t.Log(string(out))
	}

	curl = exec.Command("curl", "-4", "-I", "--socks5", addr, url1)
	err = curl.Run()
	if err == nil {
		t.Error("authenticatoin is necessary")
	}

	curl = exec.Command("curl", "-4", "-I", "-U", "root:", "--socks5", addr, url1)
	out, err = curl.CombinedOutput()
	if err != nil {
		t.Error(err)
		t.Log(string(out))
	}

	curl = exec.Command("curl", "-4", "-I", "-U", "user:pass", "--socks5", addr, url1)
	out, err = curl.CombinedOutput()
	if err != nil {
		t.Error(err)
		t.Log(string(out))
	}

	curl = exec.Command("curl", "-4", "-I", "-U", "user:", "--socks5", addr, url1)
	out, err = curl.CombinedOutput()
	if err == nil {
		t.Error("authentication should fail")
	}

	curl = exec.Command("curl", "-4", "-I", "-U", "user:bad", "--socks5", addr, url1)
	out, err = curl.CombinedOutput()
	if err == nil {
		t.Error("authentication should fail")
	}

	if !hasIPv6() {
		goto DONE
	}

	curl = exec.Command("curl", "-6", "-I", "-U", "user:pass", "--socks5", addr, url1)
	out, err = curl.CombinedOutput()
	if err != nil {
		t.Error(err)
		t.Log(string(out))
	}

DONE:
	env.Cancel(nil)
	err = env.Wait()
	if err != nil {
		t.Error(err)
	}
}

type rules struct{}

func (ru rules) Match(r *Request) bool {
	// Allow only request with hostname
	return len(r.Hostname) > 0
}

func TestServerRules(t *testing.T) {
	t.Parallel()

	_, err := exec.LookPath("curl")
	if err != nil {
		t.Skip("curl not found")
	}

	addr := "localhost:20084"
	env := cmd.NewEnvironment(context.Background())
	s := &Server{
		Rules: rules{},
		Env:   env,
	}
	ln, err := net.Listen("tcp", ":20084")
	if err != nil {
		t.Skip(err)
	}
	s.Serve(ln)

	mux := http.NewServeMux()
	mux.HandleFunc("/ok", func(w http.ResponseWriter, r *http.Request) {})
	hs := &http.Server{
		Addr:    ":20085",
		Handler: mux,
	}
	go hs.ListenAndServe()

	time.Sleep(10 * time.Millisecond)

	url1 := "http://localhost:20085/ok"
	curl := exec.Command("curl", "-4", "-I", "--socks4", addr, url1)
	err = curl.Run()
	if err == nil {
		t.Error("SOCKS4 should be denied")
	}

	curl = exec.Command("curl", "-4", "-I", "--socks4a", addr, url1)
	out, err := curl.CombinedOutput()
	if err != nil {
		t.Error(err)
		t.Log(string(out))
	}

	curl = exec.Command("curl", "-4", "-I", "--socks5", addr, url1)
	err = curl.Run()
	if err == nil {
		t.Error("SOCKS5 w/o hostname should be denied")
	}

	curl = exec.Command("curl", "-4", "-I", "--socks5-hostname", addr, url1)
	out, err = curl.CombinedOutput()
	if err != nil {
		t.Error(err)
		t.Log(string(out))
	}

	if !hasIPv6() {
		goto DONE
	}

	curl = exec.Command("curl", "-6", "-I", "--socks5-hostname", addr, url1)
	out, err = curl.CombinedOutput()
	if err != nil {
		t.Error(err)
		t.Log(string(out))
	}

DONE:
	env.Cancel(nil)
	err = env.Wait()
	if err != nil {
		t.Error(err)
	}
}

func TestServerError(t *testing.T) {
	t.Parallel()

	_, err := exec.LookPath("curl")
	if err != nil {
		t.Skip("curl not found")
	}

	addr := "localhost:20086"
	env := cmd.NewEnvironment(context.Background())
	s := &Server{
		Env: env,
	}
	ln, err := net.Listen("tcp", ":20086")
	if err != nil {
		t.Skip(err)
	}
	s.Serve(ln)

	time.Sleep(10 * time.Millisecond)

	url1 := "http://localhost:20087/ok"
	curl := exec.Command("curl", "-4", "-I", "--socks4", addr, url1)
	out, err := curl.CombinedOutput()
	if err == nil {
		t.Error("no listener on localhost:20087")
	}
	t.Log(string(out))

	curl = exec.Command("curl", "-4", "-I", "--socks5", addr, url1)
	out, err = curl.CombinedOutput()
	if err == nil {
		t.Error("no listener on localhost:20087")
	}
	t.Log(string(out))

	env.Cancel(nil)
	err = env.Wait()
	if err != nil {
		t.Error(err)
	}
}
<|endoftext|>


<commit_before>package aws

import (
	"fmt"
	"testing"

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

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/service/rds"
)

func TestAccAWSDBSubnetGroup_basic(t *testing.T) {
	var v rds.DBSubnetGroup

	testCheck := func(*terraform.State) error {
		return nil
	}

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckDBSubnetGroupDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccDBSubnetGroupConfig,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckDBSubnetGroupExists(
						"aws_db_subnet_group.foo", &v),
					testCheck,
				),
			},
		},
	})
}

// Regression test for https://github.com/hashicorp/terraform/issues/2603 and
// https://github.com/hashicorp/terraform/issues/2664
func TestAccAWSDBSubnetGroup_withUnderscores(t *testing.T) {
	var v rds.DBSubnetGroup

	testCheck := func(*terraform.State) error {
		return nil
	}

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckDBSubnetGroupDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccDBSubnetGroupConfig_withUnderscoresAndPeriods,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckDBSubnetGroupExists(
						"aws_db_subnet_group.underscores", &v),
					testAccCheckDBSubnetGroupExists(
						"aws_db_subnet_group.periods", &v),
					testCheck,
				),
			},
		},
	})
}

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

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

		// Try to find the resource
		resp, err := conn.DescribeDBSubnetGroups(
			&rds.DescribeDBSubnetGroupsInput{DBSubnetGroupName: aws.String(rs.Primary.ID)})
		if err == nil {
			if len(resp.DBSubnetGroups) > 0 {
				return fmt.Errorf("still exist.")
			}

			return nil
		}

		// Verify the error is what we want
		rdserr, ok := err.(awserr.Error)
		if !ok {
			return err
		}
		if rdserr.Code() != "DBSubnetGroupNotFoundFault" {
			return err
		}
	}

	return nil
}

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

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

		conn := testAccProvider.Meta().(*AWSClient).rdsconn
		resp, err := conn.DescribeDBSubnetGroups(
			&rds.DescribeDBSubnetGroupsInput{DBSubnetGroupName: aws.String(rs.Primary.ID)})
		if err != nil {
			return err
		}
		if len(resp.DBSubnetGroups) == 0 {
			return fmt.Errorf("DbSubnetGroup not found")
		}

		*v = *resp.DBSubnetGroups[0]

		return nil
	}
}

const testAccDBSubnetGroupConfig = `
resource "aws_vpc" "foo" {
	cidr_block = "10.1.0.0/16"
}

resource "aws_subnet" "foo" {
	cidr_block = "10.1.1.0/24"
	availability_zone = "us-west-2a"
	vpc_id = "${aws_vpc.foo.id}"
	tags {
		Name = "tf-dbsubnet-test-1"
	}
}

resource "aws_subnet" "bar" {
	cidr_block = "10.1.2.0/24"
	availability_zone = "us-west-2b"
	vpc_id = "${aws_vpc.foo.id}"
	tags {
		Name = "tf-dbsubnet-test-2"
	}
}

resource "aws_db_subnet_group" "foo" {
	name = "FOO"
	description = "foo description"
	subnet_ids = ["${aws_subnet.foo.id}", "${aws_subnet.bar.id}"]
}
`

const testAccDBSubnetGroupConfig_withUnderscoresAndPeriods = `
resource "aws_vpc" "main" {
    cidr_block = "192.168.0.0/16"
}

resource "aws_subnet" "frontend" {
    vpc_id = "${aws_vpc.main.id}"
    availability_zone = "us-west-2b"
    cidr_block = "192.168.1.0/24"
}

resource "aws_subnet" "backend" {
    vpc_id = "${aws_vpc.main.id}"
    availability_zone = "us-west-2c"
    cidr_block = "192.168.2.0/24"
}

resource "aws_db_subnet_group" "underscores" {
    name = "with_underscores"
    description = "Our main group of subnets"
    subnet_ids = ["${aws_subnet.frontend.id}", "${aws_subnet.backend.id}"]
}

resource "aws_db_subnet_group" "periods" {
    name = "with.periods"
    description = "Our main group of subnets"
    subnet_ids = ["${aws_subnet.frontend.id}", "${aws_subnet.backend.id}"]
}
`
<commit_msg>provider/aws: Improve test name (underscores -> undocumentedCharacters)<commit_after>package aws

import (
	"fmt"
	"testing"

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

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/service/rds"
)

func TestAccAWSDBSubnetGroup_basic(t *testing.T) {
	var v rds.DBSubnetGroup

	testCheck := func(*terraform.State) error {
		return nil
	}

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckDBSubnetGroupDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccDBSubnetGroupConfig,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckDBSubnetGroupExists(
						"aws_db_subnet_group.foo", &v),
					testCheck,
				),
			},
		},
	})
}

// Regression test for https://github.com/hashicorp/terraform/issues/2603 and
// https://github.com/hashicorp/terraform/issues/2664
func TestAccAWSDBSubnetGroup_withUndocumentedCharacters(t *testing.T) {
	var v rds.DBSubnetGroup

	testCheck := func(*terraform.State) error {
		return nil
	}

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckDBSubnetGroupDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccDBSubnetGroupConfig_withUnderscoresAndPeriods,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckDBSubnetGroupExists(
						"aws_db_subnet_group.underscores", &v),
					testAccCheckDBSubnetGroupExists(
						"aws_db_subnet_group.periods", &v),
					testCheck,
				),
			},
		},
	})
}

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

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

		// Try to find the resource
		resp, err := conn.DescribeDBSubnetGroups(
			&rds.DescribeDBSubnetGroupsInput{DBSubnetGroupName: aws.String(rs.Primary.ID)})
		if err == nil {
			if len(resp.DBSubnetGroups) > 0 {
				return fmt.Errorf("still exist.")
			}

			return nil
		}

		// Verify the error is what we want
		rdserr, ok := err.(awserr.Error)
		if !ok {
			return err
		}
		if rdserr.Code() != "DBSubnetGroupNotFoundFault" {
			return err
		}
	}

	return nil
}

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

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

		conn := testAccProvider.Meta().(*AWSClient).rdsconn
		resp, err := conn.DescribeDBSubnetGroups(
			&rds.DescribeDBSubnetGroupsInput{DBSubnetGroupName: aws.String(rs.Primary.ID)})
		if err != nil {
			return err
		}
		if len(resp.DBSubnetGroups) == 0 {
			return fmt.Errorf("DbSubnetGroup not found")
		}

		*v = *resp.DBSubnetGroups[0]

		return nil
	}
}

const testAccDBSubnetGroupConfig = `
resource "aws_vpc" "foo" {
	cidr_block = "10.1.0.0/16"
}

resource "aws_subnet" "foo" {
	cidr_block = "10.1.1.0/24"
	availability_zone = "us-west-2a"
	vpc_id = "${aws_vpc.foo.id}"
	tags {
		Name = "tf-dbsubnet-test-1"
	}
}

resource "aws_subnet" "bar" {
	cidr_block = "10.1.2.0/24"
	availability_zone = "us-west-2b"
	vpc_id = "${aws_vpc.foo.id}"
	tags {
		Name = "tf-dbsubnet-test-2"
	}
}

resource "aws_db_subnet_group" "foo" {
	name = "FOO"
	description = "foo description"
	subnet_ids = ["${aws_subnet.foo.id}", "${aws_subnet.bar.id}"]
}
`

const testAccDBSubnetGroupConfig_withUnderscoresAndPeriods = `
resource "aws_vpc" "main" {
    cidr_block = "192.168.0.0/16"
}

resource "aws_subnet" "frontend" {
    vpc_id = "${aws_vpc.main.id}"
    availability_zone = "us-west-2b"
    cidr_block = "192.168.1.0/24"
}

resource "aws_subnet" "backend" {
    vpc_id = "${aws_vpc.main.id}"
    availability_zone = "us-west-2c"
    cidr_block = "192.168.2.0/24"
}

resource "aws_db_subnet_group" "underscores" {
    name = "with_underscores"
    description = "Our main group of subnets"
    subnet_ids = ["${aws_subnet.frontend.id}", "${aws_subnet.backend.id}"]
}

resource "aws_db_subnet_group" "periods" {
    name = "with.periods"
    description = "Our main group of subnets"
    subnet_ids = ["${aws_subnet.frontend.id}", "${aws_subnet.backend.id}"]
}
`
<|endoftext|>


<commit_before>package server

import (
	"github.com/micro/go-micro/broker"
	"github.com/micro/go-micro/registry"
	"github.com/micro/go-micro/transport"
)

type options struct {
	codecs    map[string]CodecFunc
	broker    broker.Broker
	registry  registry.Registry
	transport transport.Transport
	metadata  map[string]string
	name      string
	address   string
	advertise string
	id        string
	version   string
}

func newOptions(opt ...Option) options {
	opts := options{
		codecs: make(map[string]CodecFunc),
	}

	for _, o := range opt {
		o(&opts)
	}

	if opts.broker == nil {
		opts.broker = broker.DefaultBroker
	}

	if opts.registry == nil {
		opts.registry = registry.DefaultRegistry
	}

	if opts.transport == nil {
		opts.transport = transport.DefaultTransport
	}

	if len(opts.address) == 0 {
		opts.address = DefaultAddress
	}

	if len(opts.name) == 0 {
		opts.name = DefaultName
	}

	if len(opts.id) == 0 {
		opts.id = DefaultId
	}

	if len(opts.version) == 0 {
		opts.version = DefaultVersion
	}

	return opts
}

func (o options) Name() string {
	return o.name
}

func (o options) Id() string {
	return o.name + "-" + o.id
}

func (o options) Version() string {
	return o.version
}

func (o options) Address() string {
	return o.address
}

func (o options) Advertise() string {
	return o.advertise
}

func (o options) Metadata() map[string]string {
	return o.metadata
}

func Name(n string) Option {
	return func(o *options) {
		o.name = n
	}
}

func Id(id string) Option {
	return func(o *options) {
		o.id = id
	}
}

func Version(v string) Option {
	return func(o *options) {
		o.version = v
	}
}

func Address(a string) Option {
	return func(o *options) {
		o.address = a
	}
}

func Advertise(a string) Option {
	return func(o *options) {
		o.advertise = a
	}
}

func Broker(b broker.Broker) Option {
	return func(o *options) {
		o.broker = b
	}
}

func Codec(contentType string, cf CodecFunc) Option {
	return func(o *options) {
		o.codecs[contentType] = cf
	}
}

func Registry(r registry.Registry) Option {
	return func(o *options) {
		o.registry = r
	}
}

func Transport(t transport.Transport) Option {
	return func(o *options) {
		o.transport = t
	}
}

func Metadata(md map[string]string) Option {
	return func(o *options) {
		o.metadata = md
	}
}
<commit_msg>more comments<commit_after>package server

import (
	"github.com/micro/go-micro/broker"
	"github.com/micro/go-micro/registry"
	"github.com/micro/go-micro/transport"
)

type options struct {
	codecs    map[string]CodecFunc
	broker    broker.Broker
	registry  registry.Registry
	transport transport.Transport
	metadata  map[string]string
	name      string
	address   string
	advertise string
	id        string
	version   string
}

func newOptions(opt ...Option) options {
	opts := options{
		codecs: make(map[string]CodecFunc),
	}

	for _, o := range opt {
		o(&opts)
	}

	if opts.broker == nil {
		opts.broker = broker.DefaultBroker
	}

	if opts.registry == nil {
		opts.registry = registry.DefaultRegistry
	}

	if opts.transport == nil {
		opts.transport = transport.DefaultTransport
	}

	if len(opts.address) == 0 {
		opts.address = DefaultAddress
	}

	if len(opts.name) == 0 {
		opts.name = DefaultName
	}

	if len(opts.id) == 0 {
		opts.id = DefaultId
	}

	if len(opts.version) == 0 {
		opts.version = DefaultVersion
	}

	return opts
}

func (o options) Name() string {
	return o.name
}

func (o options) Id() string {
	return o.name + "-" + o.id
}

func (o options) Version() string {
	return o.version
}

func (o options) Address() string {
	return o.address
}

func (o options) Advertise() string {
	return o.advertise
}

func (o options) Metadata() map[string]string {
	return o.metadata
}

// Server name
func Name(n string) Option {
	return func(o *options) {
		o.name = n
	}
}

// Unique server id
func Id(id string) Option {
	return func(o *options) {
		o.id = id
	}
}

// Version of the service
func Version(v string) Option {
	return func(o *options) {
		o.version = v
	}
}

// Address to bind to - host:port
func Address(a string) Option {
	return func(o *options) {
		o.address = a
	}
}

// The address to advertise for discovery - host:port
func Advertise(a string) Option {
	return func(o *options) {
		o.advertise = a
	}
}

// Broker to use for pub/sub
func Broker(b broker.Broker) Option {
	return func(o *options) {
		o.broker = b
	}
}

// Codec to use to encode/decode requests for a given content type
func Codec(contentType string, cf CodecFunc) Option {
	return func(o *options) {
		o.codecs[contentType] = cf
	}
}

// Registry used for discovery
func Registry(r registry.Registry) Option {
	return func(o *options) {
		o.registry = r
	}
}

// Transport mechanism for communication e.g http, rabbitmq, etc
func Transport(t transport.Transport) Option {
	return func(o *options) {
		o.transport = t
	}
}

// Metadata associated with the server
func Metadata(md map[string]string) Option {
	return func(o *options) {
		o.metadata = md
	}
}
<|endoftext|>


<commit_before>package p2p

import (
	"sync"
)

/*
PeerSet is a special structure for keeping a table of peers.
Iteration over the peers is super fast and thread-safe.
*/
type PeerSet struct {
	mtx    sync.Mutex
	lookup map[string]*peerSetItem
	list   []*Peer
}

type peerSetItem struct {
	peer  *Peer
	index int
}

func NewPeerSet() *PeerSet {
	return &PeerSet{
		lookup: make(map[string]*peerSetItem),
		list:   make([]*Peer, 0, 256),
	}
}

func (ps *PeerSet) Add(peer *Peer) bool {
	ps.mtx.Lock()
	defer ps.mtx.Unlock()
	addr := peer.RemoteAddress().String()
	if ps.lookup[addr] != nil {
		return false
	}
	index := len(ps.list)
	// Appending is safe even with other goroutines
	// iterating over the ps.list slice.
	ps.list = append(ps.list, peer)
	ps.lookup[addr] = &peerSetItem{peer, index}
	return true
}

func (ps *PeerSet) Remove(peer *Peer) {
	ps.mtx.Lock()
	defer ps.mtx.Unlock()
	addr := peer.RemoteAddress().String()
	item := ps.lookup[addr]
	if item == nil {
		return
	}
	index := item.index
	// If it's the last peer, that's an easy special case.
	if index == len(ps.list)-1 {
		ps.list = ps.list[:len(ps.list)-1]
		return
	}
	// Copy the list but without the last element.
	newList := make([]*Peer, len(ps.list)-1)
	copy(newList, ps.list)
	// Move the last item from ps.list to "index" in list.
	lastPeer := ps.list[len(ps.list)-1]
	lastPeerAddr := lastPeer.RemoteAddress().String()
	lastPeerItem := ps.lookup[lastPeerAddr]
	newList[index] = lastPeer
	lastPeerItem.index = index
	ps.list = newList
	delete(ps.lookup, addr)
}

// threadsafe list of peers.
func (ps *PeerSet) List() []*Peer {
	ps.mtx.Lock()
	defer ps.mtx.Unlock()
	return ps.list
}
<commit_msg>fixed a bug<commit_after>package p2p

import (
	"sync"
)

/*
PeerSet is a special structure for keeping a table of peers.
Iteration over the peers is super fast and thread-safe.
*/
type PeerSet struct {
	mtx    sync.Mutex
	lookup map[string]*peerSetItem
	list   []*Peer
}

type peerSetItem struct {
	peer  *Peer
	index int
}

func NewPeerSet() *PeerSet {
	return &PeerSet{
		lookup: make(map[string]*peerSetItem),
		list:   make([]*Peer, 0, 256),
	}
}

func (ps *PeerSet) Add(peer *Peer) bool {
	ps.mtx.Lock()
	defer ps.mtx.Unlock()
	addr := peer.RemoteAddress().String()
	if ps.lookup[addr] != nil {
		return false
	}
	index := len(ps.list)
	// Appending is safe even with other goroutines
	// iterating over the ps.list slice.
	ps.list = append(ps.list, peer)
	ps.lookup[addr] = &peerSetItem{peer, index}
	return true
}

func (ps *PeerSet) Remove(peer *Peer) {
	ps.mtx.Lock()
	defer ps.mtx.Unlock()
	addr := peer.RemoteAddress().String()
	item := ps.lookup[addr]
	if item == nil {
		return
	}
	index := item.index
	// Copy the list but without the last element.
	// (we must copy because we're mutating the list)
	newList := make([]*Peer, len(ps.list)-1)
	copy(newList, ps.list)
	// If it's the last peer, that's an easy special case.
	if index == len(ps.list)-1 {
		ps.list = newList
		return
	}
	// Move the last item from ps.list to "index" in list.
	lastPeer := ps.list[len(ps.list)-1]
	lastPeerAddr := lastPeer.RemoteAddress().String()
	lastPeerItem := ps.lookup[lastPeerAddr]
	newList[index] = lastPeer
	lastPeerItem.index = index
	ps.list = newList
	delete(ps.lookup, addr)
}

// threadsafe list of peers.
func (ps *PeerSet) List() []*Peer {
	ps.mtx.Lock()
	defer ps.mtx.Unlock()
	return ps.list
}
<|endoftext|>


<commit_before>package server

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

	pb "github.com/kubernetes/kubernetes/pkg/kubelet/api/v1alpha1/runtime"
	"github.com/mrunalp/ocid/oci"
	"github.com/mrunalp/ocid/utils"
	"github.com/opencontainers/ocitools/generate"
	"golang.org/x/net/context"
)

// Version returns the runtime name, runtime version and runtime API version
func (s *Server) Version(ctx context.Context, req *pb.VersionRequest) (*pb.VersionResponse, error) {
	version, err := getGPRCVersion()
	if err != nil {
		return nil, err
	}

	runtimeVersion, err := s.runtime.Version()
	if err != nil {
		return nil, err
	}

	// taking const address
	rav := runtimeAPIVersion
	runtimeName := s.runtime.Name()

	return &pb.VersionResponse{
		Version:           &version,
		RuntimeName:       &runtimeName,
		RuntimeVersion:    &runtimeVersion,
		RuntimeApiVersion: &rav,
	}, nil
}

// CreatePodSandbox creates a pod-level sandbox.
// The definition of PodSandbox is at https://github.com/kubernetes/kubernetes/pull/25899
func (s *Server) CreatePodSandbox(ctx context.Context, req *pb.CreatePodSandboxRequest) (*pb.CreatePodSandboxResponse, error) {
	var err error

	if err := os.MkdirAll(s.sandboxDir, 0755); err != nil {
		return nil, err
	}

	// process req.Name
	name := req.GetConfig().GetName()
	if name == "" {
		return nil, fmt.Errorf("PodSandboxConfig.Name should not be empty")
	}

	podSandboxDir := filepath.Join(s.sandboxDir, name)
	if _, err := os.Stat(podSandboxDir); err == nil {
		return nil, fmt.Errorf("pod sandbox (%s) already exists", podSandboxDir)
	}

	if err := os.MkdirAll(podSandboxDir, 0755); err != nil {
		return nil, err
	}

	// creates a spec Generator with the default spec.
	g := generate.New()

	// setup defaults for the pod sandbox
	g.SetRootPath("/var/lib/ocid/graph/vfs/pause")
	g.SetRootReadonly(true)
	g.SetProcessArgs([]string{"/pause"})

	// process req.Hostname
	hostname := req.GetConfig().GetHostname()
	if hostname != "" {
		g.SetHostname(hostname)
	}

	// process req.LogDirectory
	logDir := req.GetConfig().GetLogDirectory()
	if logDir == "" {
		logDir = fmt.Sprintf("/var/log/ocid/pods/%s", name)
	}

	dnsServers := req.GetConfig().GetDnsOptions().GetServers()
	dnsSearches := req.GetConfig().GetDnsOptions().GetSearches()
	resolvPath := fmt.Sprintf("%s/resolv.conf", podSandboxDir)
	if err := parseDNSOptions(dnsServers, dnsSearches, resolvPath); err != nil {
		if err1 := removeFile(resolvPath); err1 != nil {
			return nil, fmt.Errorf("%v; failed to remove %s: %v", err, resolvPath, err1)
		}
		return nil, err
	}

	g.AddBindMount(resolvPath, "/etc/resolv.conf", "ro")

	labels := req.GetConfig().GetLabels()
	s.addSandbox(&sandbox{
		name:       name,
		logDir:     logDir,
		labels:     labels,
		containers: []*oci.Container{},
	})

	annotations := req.GetConfig().GetAnnotations()
	for k, v := range annotations {
		g.AddAnnotation(k, v)
	}

	cgroupParent := req.GetConfig().GetLinux().GetCgroupParent()
	if cgroupParent != "" {
		g.SetLinuxCgroupsPath(cgroupParent)
	}

	// set up namespaces
	if req.GetConfig().GetLinux().GetNamespaceOptions().GetHostNetwork() {
		err := g.RemoveLinuxNamespace("network")
		if err != nil {
			return nil, err
		}
	}

	if req.GetConfig().GetLinux().GetNamespaceOptions().GetHostPid() {
		err := g.RemoveLinuxNamespace("pid")
		if err != nil {
			return nil, err
		}
	}

	if req.GetConfig().GetLinux().GetNamespaceOptions().GetHostIpc() {
		err := g.RemoveLinuxNamespace("ipc")
		if err != nil {
			return nil, err
		}
	}

	err = g.SaveToFile(filepath.Join(podSandboxDir, "config.json"))
	if err != nil {
		return nil, err
	}

	containerName := name + "-infra"
	container, err := oci.NewContainer(containerName, podSandboxDir, podSandboxDir, labels, name)
	if err != nil {
		return nil, err
	}

	if err := s.runtime.CreateContainer(container); err != nil {
		return nil, err
	}

	if err := s.runtime.StartContainer(container); err != nil {
		return nil, err
	}

	s.addContainer(container)

	return &pb.CreatePodSandboxResponse{PodSandboxId: &name}, nil
}

// StopPodSandbox stops the sandbox. If there are any running containers in the
// sandbox, they should be force terminated.
func (s *Server) StopPodSandbox(context.Context, *pb.StopPodSandboxRequest) (*pb.StopPodSandboxResponse, error) {
	return nil, nil
}

// DeletePodSandbox deletes the sandbox. If there are any running containers in the
// sandbox, they should be force deleted.
func (s *Server) RemovePodSandbox(context.Context, *pb.RemovePodSandboxRequest) (*pb.RemovePodSandboxResponse, error) {
	return nil, nil
}

// PodSandboxStatus returns the Status of the PodSandbox.
func (s *Server) PodSandboxStatus(context.Context, *pb.PodSandboxStatusRequest) (*pb.PodSandboxStatusResponse, error) {
	return nil, nil
}

// ListPodSandbox returns a list of SandBox.
func (s *Server) ListPodSandbox(context.Context, *pb.ListPodSandboxRequest) (*pb.ListPodSandboxResponse, error) {
	return nil, nil
}

// CreateContainer creates a new container in specified PodSandbox
func (s *Server) CreateContainer(ctx context.Context, req *pb.CreateContainerRequest) (*pb.CreateContainerResponse, error) {
	// The id of the PodSandbox
	podSandboxId := req.GetPodSandboxId()
	if !s.hasSandbox(podSandboxId) {
		return nil, fmt.Errorf("the pod sandbox (%s) does not exist", podSandboxId)
	}

	// The config of the container
	containerConfig := req.GetConfig()
	if containerConfig == nil {
		return nil, fmt.Errorf("CreateContainerRequest.ContainerConfig is nil")
	}

	name := containerConfig.GetName()
	if name == "" {
		return nil, fmt.Errorf("CreateContainerRequest.ContainerConfig.Name is empty")
	}

	// containerDir is the dir for the container bundle.
	containerDir := filepath.Join(s.runtime.ContainerDir(), name)

	if _, err := os.Stat(containerDir); err == nil {
		return nil, fmt.Errorf("container (%s) already exists", containerDir)
	}

	if err := os.MkdirAll(containerDir, 0755); err != nil {
		return nil, err
	}

	imageSpec := containerConfig.GetImage()
	if imageSpec == nil {
		return nil, fmt.Errorf("CreateContainerRequest.ContainerConfig.Image is nil")
	}

	image := imageSpec.GetImage()
	if image == "" {
		return nil, fmt.Errorf("CreateContainerRequest.ContainerConfig.Image.Image is empty")
	}

	// creates a spec Generator with the default spec.
	specgen := generate.New()

	// by default, the root path is an empty string.
	// here set it to be "rootfs".
	specgen.SetRootPath("rootfs")

	args := containerConfig.GetArgs()
	if args == nil {
		args = []string{"/bin/sh"}
	}
	specgen.SetProcessArgs(args)

	cwd := containerConfig.GetWorkingDir()
	if cwd == "" {
		cwd = "/"
	}
	specgen.SetProcessCwd(cwd)

	envs := containerConfig.GetEnvs()
	if envs != nil {
		for _, item := range envs {
			key := item.GetKey()
			value := item.GetValue()
			if key == "" {
				continue
			}
			env := fmt.Sprintf("%s=%s", key, value)
			specgen.AddProcessEnv(env)
		}
	}

	mounts := containerConfig.GetMounts()
	for _, mount := range mounts {
		dest := mount.GetContainerPath()
		if dest == "" {
			return nil, fmt.Errorf("Mount.ContainerPath is empty")
		}

		src := mount.GetHostPath()
		if src == "" {
			return nil, fmt.Errorf("Mount.HostPath is empty")
		}

		options := "rw"
		if mount.GetReadonly() {
			options = "ro"
		}

		//TODO(hmeng): how to use this info? Do we need to handle relabel a FS with Selinux?
		selinuxRelabel := mount.GetSelinuxRelabel()
		fmt.Printf("selinuxRelabel: %v\n", selinuxRelabel)

		specgen.AddBindMount(src, dest, options)

	}

	labels := containerConfig.GetLabels()

	annotations := containerConfig.GetAnnotations()
	if annotations != nil {
		for k, v := range annotations {
			specgen.AddAnnotation(k, v)
		}
	}

	if containerConfig.GetPrivileged() {
		specgen.SetupPrivileged(true)
	}

	if containerConfig.GetReadonlyRootfs() {
		specgen.SetRootReadonly(true)
	}

	logPath := containerConfig.GetLogPath()

	if containerConfig.GetTty() {
		specgen.SetProcessTerminal(true)
	}

	linux := containerConfig.GetLinux()
	if linux != nil {
		resources := linux.GetResources()
		if resources != nil {
			cpuPeriod := resources.GetCpuPeriod()
			if cpuPeriod != 0 {
				specgen.SetLinuxResourcesCPUPeriod(uint64(cpuPeriod))
			}

			cpuQuota := resources.GetCpuQuota()
			if cpuQuota != 0 {
				specgen.SetLinuxResourcesCPUQuota(uint64(cpuQuota))
			}

			cpuShares := resources.GetCpuShares()
			if cpuShares != 0 {
				specgen.SetLinuxResourcesCPUShares(uint64(cpuShares))
			}

			memoryLimit := resources.GetMemoryLimitInBytes()
			if memoryLimit != 0 {
				specgen.SetLinuxResourcesMemoryLimit(uint64(memoryLimit))
			}

			oomScoreAdj := resources.GetOomScoreAdj()
			specgen.SetLinuxResourcesOOMScoreAdj(int(oomScoreAdj))
		}

		capabilities := linux.GetCapabilities()
		if capabilities != nil {
			addCaps := capabilities.GetAddCapabilities()
			if addCaps != nil {
				for _, cap := range addCaps {
					if err := specgen.AddProcessCapability(cap); err != nil {
						return nil, err
					}
				}
			}

			dropCaps := capabilities.GetDropCapabilities()
			if dropCaps != nil {
				for _, cap := range dropCaps {
					if err := specgen.DropProcessCapability(cap); err != nil {
						return nil, err
					}
				}
			}
		}

		selinuxOptions := linux.GetSelinuxOptions()
		if selinuxOptions != nil {
			user := selinuxOptions.GetUser()
			if user == "" {
				return nil, fmt.Errorf("SELinuxOption.User is empty")
			}

			role := selinuxOptions.GetRole()
			if role == "" {
				return nil, fmt.Errorf("SELinuxOption.Role is empty")
			}

			t := selinuxOptions.GetType()
			if t == "" {
				return nil, fmt.Errorf("SELinuxOption.Type is empty")
			}

			level := selinuxOptions.GetLevel()
			if level == "" {
				return nil, fmt.Errorf("SELinuxOption.Level is empty")
			}

			specgen.SetProcessSelinuxLabel(fmt.Sprintf("%s:%s:%s:%s", user, role, t, level))
		}

		user := linux.GetUser()
		if user != nil {
			uid := user.GetUid()
			specgen.SetProcessUID(uint32(uid))

			gid := user.GetGid()
			specgen.SetProcessGID(uint32(gid))

			groups := user.GetAdditionalGids()
			if groups != nil {
				for _, group := range groups {
					specgen.AddProcessAdditionalGid(uint32(group))
				}
			}
		}
	}

	// The config of the PodSandbox
	sandboxConfig := req.GetSandboxConfig()
	fmt.Printf("sandboxConfig: %v\n", sandboxConfig)

	if err := specgen.SaveToFile(filepath.Join(containerDir, "config.json")); err != nil {
		return nil, err
	}

	// TODO: copy the rootfs into the bundle.
	// Currently, utils.CreateFakeRootfs is used to populate the rootfs.
	if err := utils.CreateFakeRootfs(containerDir, image); err != nil {
		return nil, err
	}

	container, err := oci.NewContainer(name, containerDir, logPath, labels, podSandboxId)
	if err != nil {
		return nil, err
	}

	if err := s.runtime.CreateContainer(container); err != nil {
		return nil, err
	}

	s.addContainer(container)

	return &pb.CreateContainerResponse{
		ContainerId: &name,
	}, nil
}

// StartContainer starts the container.
func (s *Server) StartContainer(context.Context, *pb.StartContainerRequest) (*pb.StartContainerResponse, error) {
	return nil, nil
}

// StopContainer stops a running container with a grace period (i.e., timeout).
func (s *Server) StopContainer(context.Context, *pb.StopContainerRequest) (*pb.StopContainerResponse, error) {
	return nil, nil
}

// RemoveContainer removes the container. If the container is running, the container
// should be force removed.
func (s *Server) RemoveContainer(context.Context, *pb.RemoveContainerRequest) (*pb.RemoveContainerResponse, error) {
	return nil, nil
}

// ListContainers lists all containers by filters.
func (s *Server) ListContainers(context.Context, *pb.ListContainersRequest) (*pb.ListContainersResponse, error) {
	return nil, nil
}

// ContainerStatus returns status of the container.
func (s *Server) ContainerStatus(context.Context, *pb.ContainerStatusRequest) (*pb.ContainerStatusResponse, error) {
	return nil, nil
}

// Exec executes the command in the container.
func (s *Server) Exec(pb.RuntimeService_ExecServer) error {
	return nil
}
<commit_msg>Add implementation for Stop Pod Sandbox<commit_after>package server

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

	pb "github.com/kubernetes/kubernetes/pkg/kubelet/api/v1alpha1/runtime"
	"github.com/mrunalp/ocid/oci"
	"github.com/mrunalp/ocid/utils"
	"github.com/opencontainers/ocitools/generate"
	"golang.org/x/net/context"
)

// Version returns the runtime name, runtime version and runtime API version
func (s *Server) Version(ctx context.Context, req *pb.VersionRequest) (*pb.VersionResponse, error) {
	version, err := getGPRCVersion()
	if err != nil {
		return nil, err
	}

	runtimeVersion, err := s.runtime.Version()
	if err != nil {
		return nil, err
	}

	// taking const address
	rav := runtimeAPIVersion
	runtimeName := s.runtime.Name()

	return &pb.VersionResponse{
		Version:           &version,
		RuntimeName:       &runtimeName,
		RuntimeVersion:    &runtimeVersion,
		RuntimeApiVersion: &rav,
	}, nil
}

// CreatePodSandbox creates a pod-level sandbox.
// The definition of PodSandbox is at https://github.com/kubernetes/kubernetes/pull/25899
func (s *Server) CreatePodSandbox(ctx context.Context, req *pb.CreatePodSandboxRequest) (*pb.CreatePodSandboxResponse, error) {
	var err error

	if err := os.MkdirAll(s.sandboxDir, 0755); err != nil {
		return nil, err
	}

	// process req.Name
	name := req.GetConfig().GetName()
	if name == "" {
		return nil, fmt.Errorf("PodSandboxConfig.Name should not be empty")
	}

	podSandboxDir := filepath.Join(s.sandboxDir, name)
	if _, err := os.Stat(podSandboxDir); err == nil {
		return nil, fmt.Errorf("pod sandbox (%s) already exists", podSandboxDir)
	}

	if err := os.MkdirAll(podSandboxDir, 0755); err != nil {
		return nil, err
	}

	// creates a spec Generator with the default spec.
	g := generate.New()

	// setup defaults for the pod sandbox
	g.SetRootPath("/var/lib/ocid/graph/vfs/pause")
	g.SetRootReadonly(true)
	g.SetProcessArgs([]string{"/pause"})

	// process req.Hostname
	hostname := req.GetConfig().GetHostname()
	if hostname != "" {
		g.SetHostname(hostname)
	}

	// process req.LogDirectory
	logDir := req.GetConfig().GetLogDirectory()
	if logDir == "" {
		logDir = fmt.Sprintf("/var/log/ocid/pods/%s", name)
	}

	dnsServers := req.GetConfig().GetDnsOptions().GetServers()
	dnsSearches := req.GetConfig().GetDnsOptions().GetSearches()
	resolvPath := fmt.Sprintf("%s/resolv.conf", podSandboxDir)
	if err := parseDNSOptions(dnsServers, dnsSearches, resolvPath); err != nil {
		if err1 := removeFile(resolvPath); err1 != nil {
			return nil, fmt.Errorf("%v; failed to remove %s: %v", err, resolvPath, err1)
		}
		return nil, err
	}

	g.AddBindMount(resolvPath, "/etc/resolv.conf", "ro")

	labels := req.GetConfig().GetLabels()
	s.addSandbox(&sandbox{
		name:       name,
		logDir:     logDir,
		labels:     labels,
		containers: []*oci.Container{},
	})

	annotations := req.GetConfig().GetAnnotations()
	for k, v := range annotations {
		g.AddAnnotation(k, v)
	}

	cgroupParent := req.GetConfig().GetLinux().GetCgroupParent()
	if cgroupParent != "" {
		g.SetLinuxCgroupsPath(cgroupParent)
	}

	// set up namespaces
	if req.GetConfig().GetLinux().GetNamespaceOptions().GetHostNetwork() {
		err := g.RemoveLinuxNamespace("network")
		if err != nil {
			return nil, err
		}
	}

	if req.GetConfig().GetLinux().GetNamespaceOptions().GetHostPid() {
		err := g.RemoveLinuxNamespace("pid")
		if err != nil {
			return nil, err
		}
	}

	if req.GetConfig().GetLinux().GetNamespaceOptions().GetHostIpc() {
		err := g.RemoveLinuxNamespace("ipc")
		if err != nil {
			return nil, err
		}
	}

	err = g.SaveToFile(filepath.Join(podSandboxDir, "config.json"))
	if err != nil {
		return nil, err
	}

	containerName := name + "-infra"
	container, err := oci.NewContainer(containerName, podSandboxDir, podSandboxDir, labels, name)
	if err != nil {
		return nil, err
	}

	if err := s.runtime.CreateContainer(container); err != nil {
		return nil, err
	}

	if err := s.runtime.StartContainer(container); err != nil {
		return nil, err
	}

	s.addContainer(container)

	return &pb.CreatePodSandboxResponse{PodSandboxId: &name}, nil
}

// StopPodSandbox stops the sandbox. If there are any running containers in the
// sandbox, they should be force terminated.
func (s *Server) StopPodSandbox(ctx context.Context, req *pb.StopPodSandboxRequest) (*pb.StopPodSandboxResponse, error) {
	sbName := req.PodSandboxId
	if *sbName == "" {
		return nil, fmt.Errorf("PodSandboxConfig.Name should not be empty")
	}
	sb := s.state.sandboxes[*sbName]
	if sb == nil {
		return nil, fmt.Errorf("specified sandbox not found: %s", *sbName)
	}

	for _, c := range sb.containers {
		if err := s.runtime.StopContainer(c); err != nil {
			return nil, fmt.Errorf("failed to stop container %s in sandbox %s: %v", c.Name(), *sbName, err)
		}
	}

	return &pb.StopPodSandboxResponse{}, nil
}

// DeletePodSandbox deletes the sandbox. If there are any running containers in the
// sandbox, they should be force deleted.
func (s *Server) RemovePodSandbox(context.Context, *pb.RemovePodSandboxRequest) (*pb.RemovePodSandboxResponse, error) {
	return nil, nil
}

// PodSandboxStatus returns the Status of the PodSandbox.
func (s *Server) PodSandboxStatus(context.Context, *pb.PodSandboxStatusRequest) (*pb.PodSandboxStatusResponse, error) {
	return nil, nil
}

// ListPodSandbox returns a list of SandBox.
func (s *Server) ListPodSandbox(context.Context, *pb.ListPodSandboxRequest) (*pb.ListPodSandboxResponse, error) {
	return nil, nil
}

// CreateContainer creates a new container in specified PodSandbox
func (s *Server) CreateContainer(ctx context.Context, req *pb.CreateContainerRequest) (*pb.CreateContainerResponse, error) {
	// The id of the PodSandbox
	podSandboxId := req.GetPodSandboxId()
	if !s.hasSandbox(podSandboxId) {
		return nil, fmt.Errorf("the pod sandbox (%s) does not exist", podSandboxId)
	}

	// The config of the container
	containerConfig := req.GetConfig()
	if containerConfig == nil {
		return nil, fmt.Errorf("CreateContainerRequest.ContainerConfig is nil")
	}

	name := containerConfig.GetName()
	if name == "" {
		return nil, fmt.Errorf("CreateContainerRequest.ContainerConfig.Name is empty")
	}

	// containerDir is the dir for the container bundle.
	containerDir := filepath.Join(s.runtime.ContainerDir(), name)

	if _, err := os.Stat(containerDir); err == nil {
		return nil, fmt.Errorf("container (%s) already exists", containerDir)
	}

	if err := os.MkdirAll(containerDir, 0755); err != nil {
		return nil, err
	}

	imageSpec := containerConfig.GetImage()
	if imageSpec == nil {
		return nil, fmt.Errorf("CreateContainerRequest.ContainerConfig.Image is nil")
	}

	image := imageSpec.GetImage()
	if image == "" {
		return nil, fmt.Errorf("CreateContainerRequest.ContainerConfig.Image.Image is empty")
	}

	// creates a spec Generator with the default spec.
	specgen := generate.New()

	// by default, the root path is an empty string.
	// here set it to be "rootfs".
	specgen.SetRootPath("rootfs")

	args := containerConfig.GetArgs()
	if args == nil {
		args = []string{"/bin/sh"}
	}
	specgen.SetProcessArgs(args)

	cwd := containerConfig.GetWorkingDir()
	if cwd == "" {
		cwd = "/"
	}
	specgen.SetProcessCwd(cwd)

	envs := containerConfig.GetEnvs()
	if envs != nil {
		for _, item := range envs {
			key := item.GetKey()
			value := item.GetValue()
			if key == "" {
				continue
			}
			env := fmt.Sprintf("%s=%s", key, value)
			specgen.AddProcessEnv(env)
		}
	}

	mounts := containerConfig.GetMounts()
	for _, mount := range mounts {
		dest := mount.GetContainerPath()
		if dest == "" {
			return nil, fmt.Errorf("Mount.ContainerPath is empty")
		}

		src := mount.GetHostPath()
		if src == "" {
			return nil, fmt.Errorf("Mount.HostPath is empty")
		}

		options := "rw"
		if mount.GetReadonly() {
			options = "ro"
		}

		//TODO(hmeng): how to use this info? Do we need to handle relabel a FS with Selinux?
		selinuxRelabel := mount.GetSelinuxRelabel()
		fmt.Printf("selinuxRelabel: %v\n", selinuxRelabel)

		specgen.AddBindMount(src, dest, options)

	}

	labels := containerConfig.GetLabels()

	annotations := containerConfig.GetAnnotations()
	if annotations != nil {
		for k, v := range annotations {
			specgen.AddAnnotation(k, v)
		}
	}

	if containerConfig.GetPrivileged() {
		specgen.SetupPrivileged(true)
	}

	if containerConfig.GetReadonlyRootfs() {
		specgen.SetRootReadonly(true)
	}

	logPath := containerConfig.GetLogPath()

	if containerConfig.GetTty() {
		specgen.SetProcessTerminal(true)
	}

	linux := containerConfig.GetLinux()
	if linux != nil {
		resources := linux.GetResources()
		if resources != nil {
			cpuPeriod := resources.GetCpuPeriod()
			if cpuPeriod != 0 {
				specgen.SetLinuxResourcesCPUPeriod(uint64(cpuPeriod))
			}

			cpuQuota := resources.GetCpuQuota()
			if cpuQuota != 0 {
				specgen.SetLinuxResourcesCPUQuota(uint64(cpuQuota))
			}

			cpuShares := resources.GetCpuShares()
			if cpuShares != 0 {
				specgen.SetLinuxResourcesCPUShares(uint64(cpuShares))
			}

			memoryLimit := resources.GetMemoryLimitInBytes()
			if memoryLimit != 0 {
				specgen.SetLinuxResourcesMemoryLimit(uint64(memoryLimit))
			}

			oomScoreAdj := resources.GetOomScoreAdj()
			specgen.SetLinuxResourcesOOMScoreAdj(int(oomScoreAdj))
		}

		capabilities := linux.GetCapabilities()
		if capabilities != nil {
			addCaps := capabilities.GetAddCapabilities()
			if addCaps != nil {
				for _, cap := range addCaps {
					if err := specgen.AddProcessCapability(cap); err != nil {
						return nil, err
					}
				}
			}

			dropCaps := capabilities.GetDropCapabilities()
			if dropCaps != nil {
				for _, cap := range dropCaps {
					if err := specgen.DropProcessCapability(cap); err != nil {
						return nil, err
					}
				}
			}
		}

		selinuxOptions := linux.GetSelinuxOptions()
		if selinuxOptions != nil {
			user := selinuxOptions.GetUser()
			if user == "" {
				return nil, fmt.Errorf("SELinuxOption.User is empty")
			}

			role := selinuxOptions.GetRole()
			if role == "" {
				return nil, fmt.Errorf("SELinuxOption.Role is empty")
			}

			t := selinuxOptions.GetType()
			if t == "" {
				return nil, fmt.Errorf("SELinuxOption.Type is empty")
			}

			level := selinuxOptions.GetLevel()
			if level == "" {
				return nil, fmt.Errorf("SELinuxOption.Level is empty")
			}

			specgen.SetProcessSelinuxLabel(fmt.Sprintf("%s:%s:%s:%s", user, role, t, level))
		}

		user := linux.GetUser()
		if user != nil {
			uid := user.GetUid()
			specgen.SetProcessUID(uint32(uid))

			gid := user.GetGid()
			specgen.SetProcessGID(uint32(gid))

			groups := user.GetAdditionalGids()
			if groups != nil {
				for _, group := range groups {
					specgen.AddProcessAdditionalGid(uint32(group))
				}
			}
		}
	}

	// The config of the PodSandbox
	sandboxConfig := req.GetSandboxConfig()
	fmt.Printf("sandboxConfig: %v\n", sandboxConfig)

	if err := specgen.SaveToFile(filepath.Join(containerDir, "config.json")); err != nil {
		return nil, err
	}

	// TODO: copy the rootfs into the bundle.
	// Currently, utils.CreateFakeRootfs is used to populate the rootfs.
	if err := utils.CreateFakeRootfs(containerDir, image); err != nil {
		return nil, err
	}

	container, err := oci.NewContainer(name, containerDir, logPath, labels, podSandboxId)
	if err != nil {
		return nil, err
	}

	if err := s.runtime.CreateContainer(container); err != nil {
		return nil, err
	}

	s.addContainer(container)

	return &pb.CreateContainerResponse{
		ContainerId: &name,
	}, nil
}

// StartContainer starts the container.
func (s *Server) StartContainer(context.Context, *pb.StartContainerRequest) (*pb.StartContainerResponse, error) {
	return nil, nil
}

// StopContainer stops a running container with a grace period (i.e., timeout).
func (s *Server) StopContainer(context.Context, *pb.StopContainerRequest) (*pb.StopContainerResponse, error) {
	return nil, nil
}

// RemoveContainer removes the container. If the container is running, the container
// should be force removed.
func (s *Server) RemoveContainer(context.Context, *pb.RemoveContainerRequest) (*pb.RemoveContainerResponse, error) {
	return nil, nil
}

// ListContainers lists all containers by filters.
func (s *Server) ListContainers(context.Context, *pb.ListContainersRequest) (*pb.ListContainersResponse, error) {
	return nil, nil
}

// ContainerStatus returns status of the container.
func (s *Server) ContainerStatus(context.Context, *pb.ContainerStatusRequest) (*pb.ContainerStatusResponse, error) {
	return nil, nil
}

// Exec executes the command in the container.
func (s *Server) Exec(pb.RuntimeService_ExecServer) error {
	return nil
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os/exec"
)

func WeaIns(sw string) (f string, err error){
	f, err = exec.LookPath(sw)
	if err != nil {
		fmt.Println("Not install", sw)
	}
	fmt.Println(f)
	return f, err
}

func main(){
	//cmd := exec.Command("echo", "Hello, world!");
	//cmd.Run();
	list := []string{"php", "mysql", "java", "python"}
	for  _, sw := range list {
		WeaIns(sw)
	}
}
<commit_msg>show version<commit_after>package main

import (
	"fmt"
	"io/ioutil"
	"os/exec"
)

func getv(sw string, vmap map[string]string) (version string, version2 string) {
	argv := []string{"-v", "-V", "-version", "--version"}
	list := []string{"php", "mysql", "java", "python"}
	vstr := "-v"
	for i, v := range argv {
		if list[i] == sw {
			vstr = v
		}
	}
	if true {
		cmd := exec.Command(sw, vstr)
		stdout, _ := cmd.StdoutPipe()
		stderr, _ := cmd.StderrPipe()
		if err := cmd.Start(); err != nil {
			//fmt.Println("Start: ", err.Error())
			//return
		}
		bytesErr, _ := ioutil.ReadAll(stderr)
		if len(bytesErr) != 0 {
			//fmt.Printf("%s", bytesErr)
			//return
		}
		bytes, _ := ioutil.ReadAll(stdout)
		if err := cmd.Wait(); err != nil {
			//fmt.Println("Wait: ", err.Error())
			//return
		}
		return string(bytes), string(bytesErr)
	}
	return "no", "error"
}

func WeaIns(sw string, vmap map[string]string) (f string, err error) {
	f, err = exec.LookPath(sw)
	fmt.Println(sw, "------------------------install check")
	if err != nil {
		fmt.Println("Not install", sw)
	} else {
		fmt.Println("Already installed")
		fmt.Println("PATH: ", f)

		fmt.Println(sw, "--------Version check")
		version, version2 := getv(sw, vmap)
		fmt.Println("VERSION INFO1: \n" + version)
		fmt.Println("VERSION INFO2: \n" + version2)
		if version == vmap[sw] {
			fmt.Println(sw, "'s version is right")
			fmt.Println(sw, "------------------------is working")
		} else {
			fmt.Println(sw, "'s version is not right, we need install version ", vmap[sw])
			fmt.Println(sw, "------------------------need fix")
		}
	}
	return f, err
}

func main() {
	var vmap map[string]string
	vmap = make(map[string]string)
	vmap["php"] = "5.5.9"
	vmap["mysql"] = "5"
	vmap["java"] = "7"
	vmap["python"] = "2.7.3"
	list := []string{"php", "mysql", "java", "python"}
	for _, sw := range list {
		fmt.Println("")
		WeaIns(sw, vmap)
		fmt.Println("")
	}
}
<|endoftext|>


<commit_before>package aws

import (
	"fmt"
	"testing"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/service/iam"
	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/terraform"
)

func TestAccAWSGroupMembership_basic(t *testing.T) {
	var group iam.GetGroupOutput

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckAWSGroupMembershipDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccAWSGroupMemberConfig,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAWSGroupMembershipExists("aws_iam_group_membership.team", &group),
					testAccCheckAWSGroupMembershipAttributes(&group, []string{"test-user"}),
				),
			},

			resource.TestStep{
				Config: testAccAWSGroupMemberConfigUpdate,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAWSGroupMembershipExists("aws_iam_group_membership.team", &group),
					testAccCheckAWSGroupMembershipAttributes(&group, []string{"test-user-two", "test-user-three"}),
				),
			},

			resource.TestStep{
				Config: testAccAWSGroupMemberConfigUpdateDown,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAWSGroupMembershipExists("aws_iam_group_membership.team", &group),
					testAccCheckAWSGroupMembershipAttributes(&group, []string{"test-user-three"}),
				),
			},
		},
	})
}

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

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

		group := rs.Primary.Attributes["group"]

		_, err := conn.GetGroup(&iam.GetGroupInput{
			GroupName: aws.String(group),
		})
		if err != nil {
			// Verify the error is what we want
			if ae, ok := err.(awserr.Error); ok && ae.Code() == "NoSuchEntity" {
				continue
			}
			return err
		}

		return fmt.Errorf("still exists")
	}

	return nil
}

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

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

		conn := testAccProvider.Meta().(*AWSClient).iamconn
		gn := rs.Primary.Attributes["group"]

		resp, err := conn.GetGroup(&iam.GetGroupInput{
			GroupName: aws.String(gn),
		})

		if err != nil {
			return fmt.Errorf("Error: Group (%s) not found", gn)
		}

		*g = *resp

		return nil
	}
}

func testAccCheckAWSGroupMembershipAttributes(group *iam.GetGroupOutput, users []string) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		if *group.Group.GroupName != "test-group" {
			return fmt.Errorf("Bad group membership: expected %s, got %s", "test-group", *group.Group.GroupName)
		}

		uc := len(users)
		for _, u := range users {
			for _, gu := range group.Users {
				if u == *gu.UserName {
					uc--
				}
			}
		}

		if uc > 0 {
			return fmt.Errorf("Bad group membership count, expected (%d), but only (%d) found", len(users), uc)
		}
		return nil
	}
}

const testAccAWSGroupMemberConfig = `
resource "aws_iam_group" "group" {
	name = "test-group"
	path = "/"
}

resource "aws_iam_user" "user" {
	name = "test-user"
	path = "/"
}

resource "aws_iam_group_membership" "team" {
	name = "tf-testing-group-membership"
	users = ["${aws_iam_user.user.name}"]
	group = "${aws_iam_group.group.name}"
}
`

const testAccAWSGroupMemberConfigUpdate = `
resource "aws_iam_group" "group" {
	name = "test-group"
	path = "/"
}

resource "aws_iam_user" "user" {
	name = "test-user"
	path = "/"
}

resource "aws_iam_user" "user_two" {
	name = "test-user-two"
	path = "/"
}

resource "aws_iam_user" "user_three" {
	name = "test-user-three"
	path = "/"
}

resource "aws_iam_group_membership" "team" {
	name = "tf-testing-group-membership"
	users = [
		"${aws_iam_user.user_two.name}",
		"${aws_iam_user.user_three.name}",
	]
	group = "${aws_iam_group.group.name}"
}
`

const testAccAWSGroupMemberConfigUpdateDown = `
resource "aws_iam_group" "group" {
	name = "test-group"
	path = "/"
}

resource "aws_iam_user" "user_three" {
	name = "test-user-three"
	path = "/"
}

resource "aws_iam_group_membership" "team" {
	name = "tf-testing-group-membership"
	users = [
		"${aws_iam_user.user_three.name}",
	]
	group = "${aws_iam_group.group.name}"
}
`
<commit_msg>provider/aws: Add some randomization for this IAM test<commit_after>package aws

import (
	"fmt"
	"strings"
	"testing"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/service/iam"
	"github.com/hashicorp/terraform/helper/acctest"
	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/terraform"
)

func TestAccAWSGroupMembership_basic(t *testing.T) {
	var group iam.GetGroupOutput

	rString := acctest.RandStringFromCharSet(10, acctest.CharSetAlpha)
	configBase := fmt.Sprintf(testAccAWSGroupMemberConfig, rString, rString, rString)
	configUpdate := fmt.Sprintf(testAccAWSGroupMemberConfigUpdate, rString, rString, rString, rString)
	configUpdateDown := fmt.Sprintf(testAccAWSGroupMemberConfigUpdateDown, rString, rString, rString)

	testUser := fmt.Sprintf("test-user-%s", rString)
	testUserTwo := fmt.Sprintf("test-user-two-%s", rString)
	testUserThree := fmt.Sprintf("test-user-three-%s", rString)

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckAWSGroupMembershipDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: configBase,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAWSGroupMembershipExists("aws_iam_group_membership.team", &group),
					testAccCheckAWSGroupMembershipAttributes(&group, []string{testUser}),
				),
			},

			resource.TestStep{
				Config: configUpdate,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAWSGroupMembershipExists("aws_iam_group_membership.team", &group),
					testAccCheckAWSGroupMembershipAttributes(&group, []string{testUserTwo, testUserThree}),
				),
			},

			resource.TestStep{
				Config: configUpdateDown,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAWSGroupMembershipExists("aws_iam_group_membership.team", &group),
					testAccCheckAWSGroupMembershipAttributes(&group, []string{testUserThree}),
				),
			},
		},
	})
}

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

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

		group := rs.Primary.Attributes["group"]

		_, err := conn.GetGroup(&iam.GetGroupInput{
			GroupName: aws.String(group),
		})
		if err != nil {
			// Verify the error is what we want
			if ae, ok := err.(awserr.Error); ok && ae.Code() == "NoSuchEntity" {
				continue
			}
			return err
		}

		return fmt.Errorf("still exists")
	}

	return nil
}

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

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

		conn := testAccProvider.Meta().(*AWSClient).iamconn
		gn := rs.Primary.Attributes["group"]

		resp, err := conn.GetGroup(&iam.GetGroupInput{
			GroupName: aws.String(gn),
		})

		if err != nil {
			return fmt.Errorf("Error: Group (%s) not found", gn)
		}

		*g = *resp

		return nil
	}
}

func testAccCheckAWSGroupMembershipAttributes(group *iam.GetGroupOutput, users []string) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		if !strings.Contains(*group.Group.GroupName, "test-group") {
			return fmt.Errorf("Bad group membership: expected %d, got %d", "test-group", *group.Group.GroupName)
		}

		uc := len(users)
		for _, u := range users {
			for _, gu := range group.Users {
				if u == *gu.UserName {
					uc--
				}
			}
		}

		if uc > 0 {
			return fmt.Errorf("Bad group membership count, expected (%d), but only (%d) found", len(users), uc)
		}
		return nil
	}
}

const testAccAWSGroupMemberConfig = `
resource "aws_iam_group" "group" {
	name = "test-group-%s"
	path = "/"
}

resource "aws_iam_user" "user" {
	name = "test-user-%s"
	path = "/"
}

resource "aws_iam_group_membership" "team" {
	name = "tf-testing-group-membership-%s"
	users = ["${aws_iam_user.user.name}"]
	group = "${aws_iam_group.group.name}"
}
`

const testAccAWSGroupMemberConfigUpdate = `
resource "aws_iam_group" "group" {
	name = "test-group-%s"
	path = "/"
}

resource "aws_iam_user" "user" {
	name = "test-user-%s"
	path = "/"
}

resource "aws_iam_user" "user_two" {
	name = "test-user-two-%s"
	path = "/"
}

resource "aws_iam_user" "user_three" {
	name = "test-user-three-%s"
	path = "/"
}

resource "aws_iam_group_membership" "team" {
	name = "tf-testing-group-membership-%s"
	users = [
		"${aws_iam_user.user_two.name}",
		"${aws_iam_user.user_three.name}",
	]
	group = "${aws_iam_group.group.name}"
}
`

const testAccAWSGroupMemberConfigUpdateDown = `
resource "aws_iam_group" "group" {
	name = "test-group-%s"
	path = "/"
}

resource "aws_iam_user" "user_three" {
	name = "test-user-three-%s"
	path = "/"
}

resource "aws_iam_group_membership" "team" {
	name = "tf-testing-group-membership-%s"
	users = [
		"${aws_iam_user.user_three.name}",
	]
	group = "${aws_iam_group.group.name}"
}
`
<|endoftext|>


<commit_before>//  Copyright (c) 2014 Couchbase, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 		http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package simple

import (
	"container/heap"
	"fmt"

	"github.com/blevesearch/bleve/document"
	"github.com/blevesearch/bleve/registry"
	"github.com/blevesearch/bleve/search"
	"github.com/blevesearch/bleve/search/highlight"
)

const Name = "simple"
const DefaultSeparator = "…"

type Highlighter struct {
	fragmenter highlight.Fragmenter
	formatter  highlight.FragmentFormatter
	sep        string
}

func NewHighlighter(fragmenter highlight.Fragmenter, formatter highlight.FragmentFormatter, separator string) *Highlighter {
	return &Highlighter{
		fragmenter: fragmenter,
		formatter:  formatter,
		sep:        separator,
	}
}

func (s *Highlighter) Fragmenter() highlight.Fragmenter {
	return s.fragmenter
}

func (s *Highlighter) SetFragmenter(f highlight.Fragmenter) {
	s.fragmenter = f
}

func (s *Highlighter) FragmentFormatter() highlight.FragmentFormatter {
	return s.formatter
}

func (s *Highlighter) SetFragmentFormatter(f highlight.FragmentFormatter) {
	s.formatter = f
}

func (s *Highlighter) Separator() string {
	return s.sep
}

func (s *Highlighter) SetSeparator(sep string) {
	s.sep = sep
}

func (s *Highlighter) BestFragmentInField(dm *search.DocumentMatch, doc *document.Document, field string) string {
	fragments := s.BestFragmentsInField(dm, doc, field, 1)
	if len(fragments) > 0 {
		return fragments[0]
	}
	return ""
}

func (s *Highlighter) BestFragmentsInField(dm *search.DocumentMatch, doc *document.Document, field string, num int) []string {
	tlm := dm.Locations[field]
	orderedTermLocations := highlight.OrderTermLocations(tlm)
	scorer := NewFragmentScorer(tlm)

	// score the fragments and put them into a priority queue ordered by score
	fq := make(FragmentQueue, 0)
	heap.Init(&fq)
	for _, f := range doc.Fields {
		if f.Name() == field {
			_, ok := f.(*document.TextField)
			if ok {
				termLocationsSameArrayPosition := make(highlight.TermLocations, 0)
				for _, otl := range orderedTermLocations {
					if highlight.SameArrayPositions(f.ArrayPositions(), otl.ArrayPositions) {
						termLocationsSameArrayPosition = append(termLocationsSameArrayPosition, otl)
					}
				}

				fieldData := f.Value()
				fragments := s.fragmenter.Fragment(fieldData, termLocationsSameArrayPosition)
				for _, fragment := range fragments {
					fragment.ArrayPositions = f.ArrayPositions()
					scorer.Score(fragment)
					heap.Push(&fq, fragment)
				}
			}
		}
	}

	// now find the N best non-overlapping fragments
	bestFragments := make([]*highlight.Fragment, 0)
	if len(fq) > 0 {
		candidate := heap.Pop(&fq)
	OUTER:
		for candidate != nil && len(bestFragments) < num {
			// see if this overlaps with any of the best already identified
			if len(bestFragments) > 0 {
				for _, frag := range bestFragments {
					if candidate.(*highlight.Fragment).Overlaps(frag) {
						if len(fq) < 1 {
							break OUTER
						}
						candidate = heap.Pop(&fq)
						continue OUTER
					}
				}
				bestFragments = append(bestFragments, candidate.(*highlight.Fragment))
			} else {
				bestFragments = append(bestFragments, candidate.(*highlight.Fragment))
			}

			if len(fq) < 1 {
				break
			}
			candidate = heap.Pop(&fq)
		}
	}

	// now that we have the best fragments, we can format them
	orderedTermLocations.MergeOverlapping()
	formattedFragments := make([]string, len(bestFragments))
	for i, fragment := range bestFragments {
		formattedFragments[i] = ""
		if fragment.Start != 0 {
			formattedFragments[i] += s.sep
		}
		formattedFragments[i] += s.formatter.Format(fragment, orderedTermLocations)
		if fragment.End != len(fragment.Orig) {
			formattedFragments[i] += s.sep
		}
	}

	if dm.Fragments == nil {
		dm.Fragments = make(search.FieldFragmentMap, 0)
	}
	if len(formattedFragments) > 0 {
		dm.Fragments[field] = formattedFragments
	}

	return formattedFragments
}

// FragmentQueue implements heap.Interface and holds Items.
type FragmentQueue []*highlight.Fragment

func (fq FragmentQueue) Len() int { return len(fq) }

func (fq FragmentQueue) Less(i, j int) bool {
	// We want Pop to give us the highest, not lowest, priority so we use greater-than here.
	return fq[i].Score > fq[j].Score
}

func (fq FragmentQueue) Swap(i, j int) {
	fq[i], fq[j] = fq[j], fq[i]
	fq[i].Index = i
	fq[j].Index = j
}

func (fq *FragmentQueue) Push(x interface{}) {
	n := len(*fq)
	item := x.(*highlight.Fragment)
	item.Index = n
	*fq = append(*fq, item)
}

func (fq *FragmentQueue) Pop() interface{} {
	old := *fq
	n := len(old)
	item := old[n-1]
	item.Index = -1 // for safety
	*fq = old[0 : n-1]
	return item
}

func Constructor(config map[string]interface{}, cache *registry.Cache) (highlight.Highlighter, error) {
	separator := DefaultSeparator
	separatorVal, ok := config["separator"].(string)
	if ok {
		separator = separatorVal
	}

	fragmenterName, ok := config["fragmenter"].(string)
	if !ok {
		return nil, fmt.Errorf("must specify fragmenter")
	}
	fragmenter, err := cache.FragmenterNamed(fragmenterName)
	if err != nil {
		return nil, fmt.Errorf("error building fragmenter: %v", err)
	}

	formatterName, ok := config["formatter"].(string)
	if !ok {
		return nil, fmt.Errorf("must specify formatter")
	}
	formatter, err := cache.FragmentFormatterNamed(formatterName)
	if err != nil {
		return nil, fmt.Errorf("error building fragment formatter: %v", err)
	}

	return NewHighlighter(fragmenter, formatter, separator), nil
}

func init() {
	registry.RegisterHighlighter(Name, Constructor)
}
<commit_msg>more golint fixes<commit_after>//  Copyright (c) 2014 Couchbase, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 		http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package simple

import (
	"container/heap"
	"fmt"

	"github.com/blevesearch/bleve/document"
	"github.com/blevesearch/bleve/registry"
	"github.com/blevesearch/bleve/search"
	"github.com/blevesearch/bleve/search/highlight"
)

const Name = "simple"
const DefaultSeparator = "…"

type Highlighter struct {
	fragmenter highlight.Fragmenter
	formatter  highlight.FragmentFormatter
	sep        string
}

func NewHighlighter(fragmenter highlight.Fragmenter, formatter highlight.FragmentFormatter, separator string) *Highlighter {
	return &Highlighter{
		fragmenter: fragmenter,
		formatter:  formatter,
		sep:        separator,
	}
}

func (s *Highlighter) Fragmenter() highlight.Fragmenter {
	return s.fragmenter
}

func (s *Highlighter) SetFragmenter(f highlight.Fragmenter) {
	s.fragmenter = f
}

func (s *Highlighter) FragmentFormatter() highlight.FragmentFormatter {
	return s.formatter
}

func (s *Highlighter) SetFragmentFormatter(f highlight.FragmentFormatter) {
	s.formatter = f
}

func (s *Highlighter) Separator() string {
	return s.sep
}

func (s *Highlighter) SetSeparator(sep string) {
	s.sep = sep
}

func (s *Highlighter) BestFragmentInField(dm *search.DocumentMatch, doc *document.Document, field string) string {
	fragments := s.BestFragmentsInField(dm, doc, field, 1)
	if len(fragments) > 0 {
		return fragments[0]
	}
	return ""
}

func (s *Highlighter) BestFragmentsInField(dm *search.DocumentMatch, doc *document.Document, field string, num int) []string {
	tlm := dm.Locations[field]
	orderedTermLocations := highlight.OrderTermLocations(tlm)
	scorer := NewFragmentScorer(tlm)

	// score the fragments and put them into a priority queue ordered by score
	fq := make(FragmentQueue, 0)
	heap.Init(&fq)
	for _, f := range doc.Fields {
		if f.Name() == field {
			_, ok := f.(*document.TextField)
			if ok {
				termLocationsSameArrayPosition := make(highlight.TermLocations, 0)
				for _, otl := range orderedTermLocations {
					if highlight.SameArrayPositions(f.ArrayPositions(), otl.ArrayPositions) {
						termLocationsSameArrayPosition = append(termLocationsSameArrayPosition, otl)
					}
				}

				fieldData := f.Value()
				fragments := s.fragmenter.Fragment(fieldData, termLocationsSameArrayPosition)
				for _, fragment := range fragments {
					fragment.ArrayPositions = f.ArrayPositions()
					scorer.Score(fragment)
					heap.Push(&fq, fragment)
				}
			}
		}
	}

	// now find the N best non-overlapping fragments
	var bestFragments []*highlight.Fragment
	if len(fq) > 0 {
		candidate := heap.Pop(&fq)
	OUTER:
		for candidate != nil && len(bestFragments) < num {
			// see if this overlaps with any of the best already identified
			if len(bestFragments) > 0 {
				for _, frag := range bestFragments {
					if candidate.(*highlight.Fragment).Overlaps(frag) {
						if len(fq) < 1 {
							break OUTER
						}
						candidate = heap.Pop(&fq)
						continue OUTER
					}
				}
				bestFragments = append(bestFragments, candidate.(*highlight.Fragment))
			} else {
				bestFragments = append(bestFragments, candidate.(*highlight.Fragment))
			}

			if len(fq) < 1 {
				break
			}
			candidate = heap.Pop(&fq)
		}
	}

	// now that we have the best fragments, we can format them
	orderedTermLocations.MergeOverlapping()
	formattedFragments := make([]string, len(bestFragments))
	for i, fragment := range bestFragments {
		formattedFragments[i] = ""
		if fragment.Start != 0 {
			formattedFragments[i] += s.sep
		}
		formattedFragments[i] += s.formatter.Format(fragment, orderedTermLocations)
		if fragment.End != len(fragment.Orig) {
			formattedFragments[i] += s.sep
		}
	}

	if dm.Fragments == nil {
		dm.Fragments = make(search.FieldFragmentMap, 0)
	}
	if len(formattedFragments) > 0 {
		dm.Fragments[field] = formattedFragments
	}

	return formattedFragments
}

// FragmentQueue implements heap.Interface and holds Items.
type FragmentQueue []*highlight.Fragment

func (fq FragmentQueue) Len() int { return len(fq) }

func (fq FragmentQueue) Less(i, j int) bool {
	// We want Pop to give us the highest, not lowest, priority so we use greater-than here.
	return fq[i].Score > fq[j].Score
}

func (fq FragmentQueue) Swap(i, j int) {
	fq[i], fq[j] = fq[j], fq[i]
	fq[i].Index = i
	fq[j].Index = j
}

func (fq *FragmentQueue) Push(x interface{}) {
	n := len(*fq)
	item := x.(*highlight.Fragment)
	item.Index = n
	*fq = append(*fq, item)
}

func (fq *FragmentQueue) Pop() interface{} {
	old := *fq
	n := len(old)
	item := old[n-1]
	item.Index = -1 // for safety
	*fq = old[0 : n-1]
	return item
}

func Constructor(config map[string]interface{}, cache *registry.Cache) (highlight.Highlighter, error) {
	separator := DefaultSeparator
	separatorVal, ok := config["separator"].(string)
	if ok {
		separator = separatorVal
	}

	fragmenterName, ok := config["fragmenter"].(string)
	if !ok {
		return nil, fmt.Errorf("must specify fragmenter")
	}
	fragmenter, err := cache.FragmenterNamed(fragmenterName)
	if err != nil {
		return nil, fmt.Errorf("error building fragmenter: %v", err)
	}

	formatterName, ok := config["formatter"].(string)
	if !ok {
		return nil, fmt.Errorf("must specify formatter")
	}
	formatter, err := cache.FragmentFormatterNamed(formatterName)
	if err != nil {
		return nil, fmt.Errorf("error building fragment formatter: %v", err)
	}

	return NewHighlighter(fragmenter, formatter, separator), nil
}

func init() {
	registry.RegisterHighlighter(Name, Constructor)
}
<|endoftext|>


<commit_before>package gorfxtrx

import (
	"encoding/binary"
	"errors"
	"fmt"
	"strconv"
)

// Struct for the Chime packets.
type Chime struct {
	typeId         byte
	SequenceNumber byte
	id             uint16
	Chime          byte
	Battery        byte
	Rssi           byte
}

var chimeTypes = map[byte]string{
	0x00: "Byron SX",
}

func NewChime(typeId byte, id string, chime byte) (*Chime, error) {
	if len(id) != 4 {
		return nil, errors.New("id should be 4 characters (eg. 007b)")
	}
	iid, err := strconv.ParseInt(id, 16, 16)
	if err != nil {
		return nil, err
	}
	return &Chime{
		typeId: typeId,
		id:     uint16(iid),
		Chime:  chime,
	}, nil
}

func (self *Chime) Receive(data []byte) {
	// 07 16 00 03 00 7a 01 70
	self.typeId = data[2]
	self.SequenceNumber = data[3]
	self.id = binary.BigEndian.Uint16(data[4:6])
	self.Chime = data[6]
	self.Battery = (data[7] & 0x0f) * 10
	self.Rssi = data[7] >> 4
}

// Id of the device.
func (self *Chime) Id() string {
	return fmt.Sprintf("%02x:%02x", self.id>>8, self.id&0xff)
}

// Type of the device.
func (self *Chime) Type() string {
	return chimeTypes[self.typeId]
}

func (self *Chime) Send() []byte {
	b := []byte{0x07, 0x16, self.typeId, self.SequenceNumber,
		0, 0, self.Chime, 0}
	binary.BigEndian.PutUint16(b[4:6], self.id)
	return b
}
<commit_msg>Add more chime types<commit_after>package gorfxtrx

import (
	"encoding/binary"
	"errors"
	"fmt"
	"strconv"
)

// Struct for the Chime packets.
type Chime struct {
	typeId         byte
	SequenceNumber byte
	id             uint16
	Chime          byte
	Battery        byte
	Rssi           byte
}

var chimeTypes = map[byte]string{
	0x00: "Byron SX",
	0x01: "Byron MP001",
	0x02: "Easy Chime",
	0x03: "RFU",
	0x04: "Envivo",
}

func NewChime(typeId byte, id string, chime byte) (*Chime, error) {
	if len(id) != 4 {
		return nil, errors.New("id should be 4 characters (eg. 007b)")
	}
	iid, err := strconv.ParseInt(id, 16, 16)
	if err != nil {
		return nil, err
	}
	return &Chime{
		typeId: typeId,
		id:     uint16(iid),
		Chime:  chime,
	}, nil
}

func (self *Chime) Receive(data []byte) {
	// 07 16 00 03 00 7a 01 70
	self.typeId = data[2]
	self.SequenceNumber = data[3]
	self.id = binary.BigEndian.Uint16(data[4:6])
	self.Chime = data[6]
	self.Battery = (data[7] & 0x0f) * 10
	self.Rssi = data[7] >> 4
}

// Id of the device.
func (self *Chime) Id() string {
	return fmt.Sprintf("%02x:%02x", self.id>>8, self.id&0xff)
}

// Type of the device.
func (self *Chime) Type() string {
	return chimeTypes[self.typeId]
}

func (self *Chime) Send() []byte {
	b := []byte{0x07, 0x16, self.typeId, self.SequenceNumber,
		0, 0, self.Chime, 0}
	binary.BigEndian.PutUint16(b[4:6], self.id)
	return b
}
<|endoftext|>