<commit_before>package gotest

import (
	"testing"
	"os"
	"os/exec"
	"bytes"
	"strings"
)

// HELPER
// copy test source file `*.c` to tmp dir
func copyCSourceFile(name string, t *testing.T) (string, string) {
	t.Logf("Copying file %s ...", name)

	absPath, _ := os.Getwd()
	baseDir, projectDir := absPath+"/tmp", absPath+"/../.."
	os.MkdirAll(baseDir, os.ModePerm)

	cpCmd := exec.Command("cp", projectDir+"/src/test/resources/c/"+name, baseDir+"/Main.c")
	cpErr := cpCmd.Run()

	if cpErr != nil {
		os.RemoveAll(baseDir + "/")
		t.Error(cpErr.Error())
		t.FailNow()
	}

	t.Log("Done")
	return baseDir, projectDir
}

// HELPER
// compile C source file
func compileC(name, baseDir, projectDir string, t *testing.T) (string) {
	t.Logf("Compiling file %s ...", name)

	var compilerStderr bytes.Buffer
	compilerCmd := exec.Command(projectDir+"/bin/c_compiler", "-basedir="+baseDir)
	compilerCmd.Stderr = &compilerStderr
	compilerErr := compilerCmd.Run()

	if compilerErr != nil {
		os.RemoveAll(baseDir + "/")
		t.Error(compilerErr.Error())
		t.FailNow()
	}

	t.Log("Done")
	return compilerStderr.String()
}

// HELPER
// run C binary in our container
func runC(baseDir, projectDir, memory, timeout string, t *testing.T) (string) {
	t.Log("Running binary /Main ...")

	var containerStdout bytes.Buffer
	containerArgs := []string{"-basedir=" + baseDir, "-input=10:10:23PM", "-expected=22:10:23", "-memory=" + memory, "-timeout=" + timeout}
	containerCmd := exec.Command(projectDir+"/bin/c_container", containerArgs...)
	containerCmd.Stdout = &containerStdout
	containerErr := containerCmd.Run()

	if containerErr != nil {
		os.RemoveAll(baseDir + "/")
		t.Error(containerErr.Error())
		t.FailNow()
	}

	t.Log("Done")
	return containerStdout.String()
}

func Test_C_AC(t *testing.T) {
	name := "ac.c"
	baseDir, projectDir := copyCSourceFile(name, t)
	compilerStderr := compileC(name, baseDir, projectDir, t)

	if len(compilerStderr) > 0 {
		os.RemoveAll(baseDir + "/")
		t.Error(compilerStderr)
		t.FailNow()
	}

	containerErr := runC(baseDir, projectDir, "64", "1000", t)
	if !strings.Contains(containerErr, "\"status\":0") {
		os.RemoveAll(baseDir + "/")
		t.Error(containerErr + " => status != 0")
		t.FailNow()
	}

	os.RemoveAll(baseDir + "/")
}

func Test_C_Compiler_Bomb_0(t *testing.T) {
	name := "compiler_bomb_0.c"
	baseDir, projectDir := copyCSourceFile(name, t)
	compilerStderr := compileC(name, baseDir, projectDir, t)

	if !strings.Contains(compilerStderr, "signal: killed") {
		os.RemoveAll(baseDir + "/")
		t.Error(compilerStderr + " => Compile error does not contain string `signal: killed`")
		t.FailNow()
	}

	os.RemoveAll(baseDir + "/")
}

func Test_C_Compiler_Bomb_1(t *testing.T) {
	name := "compiler_bomb_1.c"
	baseDir, projectDir := copyCSourceFile(name, t)
	compilerStderr := compileC(name, baseDir, projectDir, t)

	if !strings.Contains(compilerStderr, "signal: killed") {
		os.RemoveAll(baseDir + "/")
		t.Error(compilerStderr + " => Compile error does not contain string `signal: killed`")
		t.FailNow()
	}

	os.RemoveAll(baseDir + "/")
}

func Test_C_Compiler_Bomb_2(t *testing.T) {
	name := "compiler_bomb_2.c"
	baseDir, projectDir := copyCSourceFile(name, t)
	compilerStderr := compileC(name, baseDir, projectDir, t)

	if !strings.Contains(compilerStderr, "signal: killed") {
		os.RemoveAll(baseDir + "/")
		t.Error(compilerStderr + " => Compile error does not contain string `signal: killed`")
		t.FailNow()
	}

	os.RemoveAll(baseDir + "/")
}

func Test_C_Fork_Bomb(t *testing.T) {
	name := "fork_bomb.c"
	baseDir, projectDir := copyCSourceFile(name, t)
	compilerStderr := compileC(name, baseDir, projectDir, t)

	if len(compilerStderr) > 0 {
		os.RemoveAll(baseDir + "/")
		t.Error(compilerStderr)
		t.FailNow()
	}

	containerErr := runC(baseDir, projectDir, "64", "1000", t)

	if !strings.Contains(containerErr, "Runtime Error") {
		os.RemoveAll(baseDir + "/")
		t.Error(containerErr)
		t.FailNow()
	}

	os.RemoveAll(baseDir + "/")
}

func Test_C_Get_Host_By_Name(t *testing.T) {
	name := "get_host_by_name.c"
	baseDir, projectDir := copyCSourceFile(name, t)
	compilerStderr := compileC(name, baseDir, projectDir, t)

	if len(compilerStderr) > 0 {
		os.RemoveAll(baseDir + "/")
		t.Error(compilerStderr)
		t.FailNow()
	}

	containerErr := runC(baseDir, projectDir, "64", "1000", t)

	// Main.c:(.text+0x28): warning: Using 'gethostbyname' in statically linked applications
	// requires at runtime the shared libraries from the glibc version used for linking
	if !strings.Contains(containerErr, "\"status\":2") {
		os.RemoveAll(baseDir + "/")
		t.Error(containerErr)
		t.FailNow()
	}

	os.RemoveAll(baseDir + "/")
}

func Test_C_Include_Leaks(t *testing.T) {
	name := "include_leaks.c"
	baseDir, projectDir := copyCSourceFile(name, t)
	compilerStderr := compileC(name, baseDir, projectDir, t)

	if !strings.Contains(compilerStderr, "/etc/shadow") {
		os.RemoveAll(baseDir + "/")
		t.Error(compilerStderr + " => Compile error does not contain string `/etc/shadow`")
		t.FailNow()
	}

	os.RemoveAll(baseDir + "/")
}

func Test_C_Infinite_Loop(t *testing.T) {
	name := "infinite_loop.c"
	baseDir, projectDir := copyCSourceFile(name, t)
	compilerStderr := compileC(name, baseDir, projectDir, t)

	if len(compilerStderr) > 0 {
		os.RemoveAll(baseDir + "/")
		t.Error(compilerStderr)
		t.FailNow()
	}

	containerErr := runC(baseDir, projectDir, "64", "1000", t)

	if !strings.Contains(containerErr, "Runtime Error") {
		os.RemoveAll(baseDir + "/")
		t.Error(containerErr)
		t.FailNow()
	}

	os.RemoveAll(baseDir + "/")
}

func Test_C_Memory_Allocation(t *testing.T) {
	name := "memory_allocation.c"
	baseDir, projectDir := copyCSourceFile(name, t)
	compilerStderr := compileC(name, baseDir, projectDir, t)

	if len(compilerStderr) > 0 {
		os.RemoveAll(baseDir + "/")
		t.Error(compilerStderr)
		t.FailNow()
	}

	containerErr := runC(baseDir, projectDir, "16", "15000", t)

	// `Killed` is sent to tty by kernel (and record will also be kept in /var/log/message)
	// both stdout and stderr are empty which will lead to status WA
	if !strings.Contains(containerErr, "\"status\":5") {
		os.RemoveAll(baseDir + "/")
		t.Error(containerErr)
		t.FailNow()
	}

	os.RemoveAll(baseDir + "/")
}

func Test_C_Plain_Text(t *testing.T) {
	name := "plain_text.c"
	baseDir, projectDir := copyCSourceFile(name, t)

	compilerStderr := compileC(name, baseDir, projectDir, t)

	if !strings.Contains(compilerStderr, "error") {
		os.RemoveAll(baseDir + "/")
		t.Error(compilerStderr + " => Compile error does not contain string `error`")
		t.FailNow()
	}

	os.RemoveAll(baseDir + "/")
}

func Test_C_Run_Command_Line_0(t *testing.T) {
	name := "run_command_line_0.c"
	baseDir, projectDir := copyCSourceFile(name, t)
	compilerStderr := compileC(name, baseDir, projectDir, t)

	if len(compilerStderr) > 0 {
		os.RemoveAll(baseDir + "/")
		t.Error(compilerStderr)
		t.FailNow()
	}

	containerErr := runC(baseDir, projectDir, "16", "1000", t)

	if !strings.Contains(containerErr, "\"status\":5") {
		os.RemoveAll(baseDir + "/")
		t.Error(containerErr)
		t.FailNow()
	}

	os.RemoveAll(baseDir + "/")
}

func Test_C_Run_Command_Line_1(t *testing.T) {
	name := "run_command_line_1.c"
	baseDir, projectDir := copyCSourceFile(name, t)
	compilerStderr := compileC(name, baseDir, projectDir, t)

	if len(compilerStderr) > 0 {
		os.RemoveAll(baseDir + "/")
		t.Error(compilerStderr)
		t.FailNow()
	}

	containerErr := runC(baseDir, projectDir, "16", "1000", t)

	if !strings.Contains(containerErr, "\"status\":5") {
		os.RemoveAll(baseDir + "/")
		t.Error(containerErr)
		t.FailNow()
	}

	os.RemoveAll(baseDir + "/")
}

func Test_C_Syscall_0(t *testing.T) {
	name := "syscall_0.c"
	baseDir, projectDir := copyCSourceFile(name, t)
	compilerStderr := compileC(name, baseDir, projectDir, t)

	if len(compilerStderr) > 0 {
		os.RemoveAll(baseDir + "/")
		t.Error(compilerStderr)
		t.FailNow()
	}

	containerErr := runC(baseDir, projectDir, "16", "1000", t)

	if !strings.Contains(containerErr, "\"status\":5") {
		os.RemoveAll(baseDir + "/")
		t.Error(containerErr)
		t.FailNow()
	}

	os.RemoveAll(baseDir + "/")
}
<commit_msg>update test case: memory limitation<commit_after>package gotest

import (
	"testing"
	"os"
	"os/exec"
	"bytes"
	"strings"
)

// HELPER
// copy test source file `*.c` to tmp dir
func copyCSourceFile(name string, t *testing.T) (string, string) {
	t.Logf("Copying file %s ...", name)

	absPath, _ := os.Getwd()
	baseDir, projectDir := absPath+"/tmp", absPath+"/../.."
	os.MkdirAll(baseDir, os.ModePerm)

	cpCmd := exec.Command("cp", projectDir+"/src/test/resources/c/"+name, baseDir+"/Main.c")
	cpErr := cpCmd.Run()

	if cpErr != nil {
		os.RemoveAll(baseDir + "/")
		t.Error(cpErr.Error())
		t.FailNow()
	}

	t.Log("Done")
	return baseDir, projectDir
}

// HELPER
// compile C source file
func compileC(name, baseDir, projectDir string, t *testing.T) (string) {
	t.Logf("Compiling file %s ...", name)

	var compilerStderr bytes.Buffer
	compilerCmd := exec.Command(projectDir+"/bin/c_compiler", "-basedir="+baseDir)
	compilerCmd.Stderr = &compilerStderr
	compilerErr := compilerCmd.Run()

	if compilerErr != nil {
		os.RemoveAll(baseDir + "/")
		t.Error(compilerErr.Error())
		t.FailNow()
	}

	t.Log("Done")
	return compilerStderr.String()
}

// HELPER
// run C binary in our container
func runC(baseDir, projectDir, memory, timeout string, t *testing.T) (string) {
	t.Log("Running binary /Main ...")

	var containerStdout bytes.Buffer
	containerArgs := []string{"-basedir=" + baseDir, "-input=10:10:23PM", "-expected=22:10:23", "-memory=" + memory, "-timeout=" + timeout}
	containerCmd := exec.Command(projectDir+"/bin/c_container", containerArgs...)
	containerCmd.Stdout = &containerStdout
	containerErr := containerCmd.Run()

	if containerErr != nil {
		os.RemoveAll(baseDir + "/")
		t.Error(containerErr.Error())
		t.FailNow()
	}

	t.Log("Done")
	return containerStdout.String()
}

func Test_C_AC(t *testing.T) {
	name := "ac.c"
	baseDir, projectDir := copyCSourceFile(name, t)
	compilerStderr := compileC(name, baseDir, projectDir, t)

	if len(compilerStderr) > 0 {
		os.RemoveAll(baseDir + "/")
		t.Error(compilerStderr)
		t.FailNow()
	}

	containerErr := runC(baseDir, projectDir, "64", "1000", t)
	if !strings.Contains(containerErr, "\"status\":0") {
		os.RemoveAll(baseDir + "/")
		t.Error(containerErr + " => status != 0")
		t.FailNow()
	}

	os.RemoveAll(baseDir + "/")
}

func Test_C_Compiler_Bomb_0(t *testing.T) {
	name := "compiler_bomb_0.c"
	baseDir, projectDir := copyCSourceFile(name, t)
	compilerStderr := compileC(name, baseDir, projectDir, t)

	if !strings.Contains(compilerStderr, "signal: killed") {
		os.RemoveAll(baseDir + "/")
		t.Error(compilerStderr + " => Compile error does not contain string `signal: killed`")
		t.FailNow()
	}

	os.RemoveAll(baseDir + "/")
}

func Test_C_Compiler_Bomb_1(t *testing.T) {
	name := "compiler_bomb_1.c"
	baseDir, projectDir := copyCSourceFile(name, t)
	compilerStderr := compileC(name, baseDir, projectDir, t)

	if !strings.Contains(compilerStderr, "signal: killed") {
		os.RemoveAll(baseDir + "/")
		t.Error(compilerStderr + " => Compile error does not contain string `signal: killed`")
		t.FailNow()
	}

	os.RemoveAll(baseDir + "/")
}

func Test_C_Compiler_Bomb_2(t *testing.T) {
	name := "compiler_bomb_2.c"
	baseDir, projectDir := copyCSourceFile(name, t)
	compilerStderr := compileC(name, baseDir, projectDir, t)

	if !strings.Contains(compilerStderr, "signal: killed") {
		os.RemoveAll(baseDir + "/")
		t.Error(compilerStderr + " => Compile error does not contain string `signal: killed`")
		t.FailNow()
	}

	os.RemoveAll(baseDir + "/")
}

func Test_C_Fork_Bomb(t *testing.T) {
	name := "fork_bomb.c"
	baseDir, projectDir := copyCSourceFile(name, t)
	compilerStderr := compileC(name, baseDir, projectDir, t)

	if len(compilerStderr) > 0 {
		os.RemoveAll(baseDir + "/")
		t.Error(compilerStderr)
		t.FailNow()
	}

	containerErr := runC(baseDir, projectDir, "64", "1000", t)

	if !strings.Contains(containerErr, "Runtime Error") {
		os.RemoveAll(baseDir + "/")
		t.Error(containerErr)
		t.FailNow()
	}

	os.RemoveAll(baseDir + "/")
}

func Test_C_Get_Host_By_Name(t *testing.T) {
	name := "get_host_by_name.c"
	baseDir, projectDir := copyCSourceFile(name, t)
	compilerStderr := compileC(name, baseDir, projectDir, t)

	if len(compilerStderr) > 0 {
		os.RemoveAll(baseDir + "/")
		t.Error(compilerStderr)
		t.FailNow()
	}

	containerErr := runC(baseDir, projectDir, "64", "1000", t)

	// Main.c:(.text+0x28): warning: Using 'gethostbyname' in statically linked applications
	// requires at runtime the shared libraries from the glibc version used for linking
	if !strings.Contains(containerErr, "\"status\":2") {
		os.RemoveAll(baseDir + "/")
		t.Error(containerErr)
		t.FailNow()
	}

	os.RemoveAll(baseDir + "/")
}

func Test_C_Include_Leaks(t *testing.T) {
	name := "include_leaks.c"
	baseDir, projectDir := copyCSourceFile(name, t)
	compilerStderr := compileC(name, baseDir, projectDir, t)

	if !strings.Contains(compilerStderr, "/etc/shadow") {
		os.RemoveAll(baseDir + "/")
		t.Error(compilerStderr + " => Compile error does not contain string `/etc/shadow`")
		t.FailNow()
	}

	os.RemoveAll(baseDir + "/")
}

func Test_C_Infinite_Loop(t *testing.T) {
	name := "infinite_loop.c"
	baseDir, projectDir := copyCSourceFile(name, t)
	compilerStderr := compileC(name, baseDir, projectDir, t)

	if len(compilerStderr) > 0 {
		os.RemoveAll(baseDir + "/")
		t.Error(compilerStderr)
		t.FailNow()
	}

	containerErr := runC(baseDir, projectDir, "64", "1000", t)

	if !strings.Contains(containerErr, "Runtime Error") {
		os.RemoveAll(baseDir + "/")
		t.Error(containerErr)
		t.FailNow()
	}

	os.RemoveAll(baseDir + "/")
}

func Test_C_Memory_Allocation(t *testing.T) {
	name := "memory_allocation.c"
	baseDir, projectDir := copyCSourceFile(name, t)
	compilerStderr := compileC(name, baseDir, projectDir, t)

	if len(compilerStderr) > 0 {
		os.RemoveAll(baseDir + "/")
		t.Error(compilerStderr)
		t.FailNow()
	}

	containerErr := runC(baseDir, projectDir, "8", "15000", t)

	// `Killed` is sent to tty by kernel (and record will also be kept in /var/log/message)
	// both stdout and stderr are empty which will lead to status WA
	if !strings.Contains(containerErr, "\"status\":5") {
		os.RemoveAll(baseDir + "/")
		t.Error(containerErr)
		t.FailNow()
	}

	os.RemoveAll(baseDir + "/")
}

func Test_C_Plain_Text(t *testing.T) {
	name := "plain_text.c"
	baseDir, projectDir := copyCSourceFile(name, t)

	compilerStderr := compileC(name, baseDir, projectDir, t)

	if !strings.Contains(compilerStderr, "error") {
		os.RemoveAll(baseDir + "/")
		t.Error(compilerStderr + " => Compile error does not contain string `error`")
		t.FailNow()
	}

	os.RemoveAll(baseDir + "/")
}

func Test_C_Run_Command_Line_0(t *testing.T) {
	name := "run_command_line_0.c"
	baseDir, projectDir := copyCSourceFile(name, t)
	compilerStderr := compileC(name, baseDir, projectDir, t)

	if len(compilerStderr) > 0 {
		os.RemoveAll(baseDir + "/")
		t.Error(compilerStderr)
		t.FailNow()
	}

	containerErr := runC(baseDir, projectDir, "16", "1000", t)

	if !strings.Contains(containerErr, "\"status\":5") {
		os.RemoveAll(baseDir + "/")
		t.Error(containerErr)
		t.FailNow()
	}

	os.RemoveAll(baseDir + "/")
}

func Test_C_Run_Command_Line_1(t *testing.T) {
	name := "run_command_line_1.c"
	baseDir, projectDir := copyCSourceFile(name, t)
	compilerStderr := compileC(name, baseDir, projectDir, t)

	if len(compilerStderr) > 0 {
		os.RemoveAll(baseDir + "/")
		t.Error(compilerStderr)
		t.FailNow()
	}

	containerErr := runC(baseDir, projectDir, "16", "1000", t)

	if !strings.Contains(containerErr, "\"status\":5") {
		os.RemoveAll(baseDir + "/")
		t.Error(containerErr)
		t.FailNow()
	}

	os.RemoveAll(baseDir + "/")
}

func Test_C_Syscall_0(t *testing.T) {
	name := "syscall_0.c"
	baseDir, projectDir := copyCSourceFile(name, t)
	compilerStderr := compileC(name, baseDir, projectDir, t)

	if len(compilerStderr) > 0 {
		os.RemoveAll(baseDir + "/")
		t.Error(compilerStderr)
		t.FailNow()
	}

	containerErr := runC(baseDir, projectDir, "16", "1000", t)

	if !strings.Contains(containerErr, "\"status\":5") {
		os.RemoveAll(baseDir + "/")
		t.Error(containerErr)
		t.FailNow()
	}

	os.RemoveAll(baseDir + "/")
}
<|endoftext|>


<commit_before>package main

import (
	"errors"
	"fmt"

	"github.com/hyperledger/fabric/core/chaincode/shim"
)

// SampleChaincode struct required to implement the shim.Chaincode interface
type SampleChaincode struct {
}

// Init method is called when the chaincode is first deployed onto the blockchain network
func (t *SampleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	if len(args) != 1 {
		return nil, errors.New("Incorrect number of arguments. Expecting 1")
	}

	err := stub.PutState("hello_world", []byte(args[0]))
	if err != nil {
		return nil, err
	}

	return nil, nil
}

// Query method is invoked whenever any read/get/query operation needs to be performed on the blockchain state.
func (t *SampleChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	fmt.Println("query is running " + function)

	// Handle different functions
	if function == "read" { //read a variable
		return t.read(stub, args)
	}
	fmt.Println("query did not find func: " + function)

	return nil, errors.New("Received unknown function query")
}

// Invoke method is invoked whenever the state of the blockchain is to be modified.
func (t *SampleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	fmt.Println("invoke is running " + function)

	// Handle different functions
	if function == "init" {
		return t.Init(stub, "init", args)
	} else if function == "write" {
		return t.write(stub, args)
	}
	fmt.Println("invoke did not find func: " + function)

	return nil, errors.New("Received unknown function invocation")
}

func (t *SampleChaincode) read(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
	var name, jsonResp string
	var err error

	if len(args) != 1 {
		return nil, errors.New("Incorrect number of arguments. Expecting name of the var to query")
	}

	name = args[0]
	valAsbytes, err := stub.GetState(name)
	if err != nil {
		jsonResp = "{\"Error\":\"Failed to get state for " + name + "\"}"
		return nil, errors.New(jsonResp)
	}

	return valAsbytes, nil
}

func (t *SampleChaincode) write(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
	var name, value string
	var err error
	fmt.Println("running write()")

	if len(args) != 2 {
		return nil, errors.New("Incorrect number of arguments. Expecting 2. name of the variable and value to set")
	}

	name = args[0] //rename for fun
	value = args[1]
	err = stub.PutState(name, []byte(value)) //write the variable into the chaincode state
	if err != nil {
		return nil, err
	}
	return nil, nil
}

func main() {
	err := shim.Start(new(SampleChaincode))
	if err != nil {
		fmt.Println("Could not start SampleChaincode")
	} else {
		fmt.Println("SampleChaincode successfully started")
	}

}
<commit_msg>commitng acquirer code<commit_after>package main

import (
	"errors"
	"fmt"
	"strconv"
	"time"

	"strings"

	"github.com/hyperledger/fabric/core/chaincode/shim"
	"github.com/hyperledger/fabric/core/util"
)

var serviceCharge = 5

var logger = shim.NewLogger("ftLogger")

// SimpleChaincode example simple Chaincode implementation
type SimpleChaincode struct {
}

// Init initializes the chaincode
func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	var err error
	if len(args) > 0 {
		return nil, errors.New("Incorrect number of arguments. Expecting 0")
	}

	// Write the state to the ledger
	err = stub.PutState("IBI-CC[init]: "+time.Now().String(), []byte("starting ABI chaincode"))
	if err != nil {
		return nil, err
	}

	return nil, nil
}

// Invoke queries another chaincode and updates its own state
func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	var jsonResp, customer, name, amount, state string
	var response []byte
	var err error

	if len(args) != 2 {
		return nil, errors.New("Incorrect number of arguments. Expecting 2")
	}

	chaincodeURL := args[0] //https://github.com/sauravhaloi/chaincode/issuer
	operation := args[1]
	customer = args[2]

	switch operation {
	case "GetAccountBalance":
		f := "Query"
		queryArgs := util.ToChaincodeArgs(f, "GetAccountBalance", customer)
		response, err = stub.QueryChaincode(chaincodeURL, queryArgs)
		if err != nil {
			errStr := fmt.Sprintf("Failed to query chaincode. Got error: %s", err.Error())
			jsonResp = "{\"Error\":\"" + errStr + "\"}"
			return nil, errors.New(jsonResp)
		}

	case "WithdrawFund":
		f := "Invoke"
		name = strings.Split(customer, ",")[0]
		amount = strings.Split(customer, ",")[1]
		queryArgs := util.ToChaincodeArgs(f, "Withdraw", name, amount)

		response, err = stub.QueryChaincode(chaincodeURL, queryArgs)
		if err != nil {
			errStr := fmt.Sprintf("Failed to invoke chaincode. Got error: %s", err.Error())
			jsonResp = "{\"Error\":\"" + errStr + "\"}"
			return nil, errors.New(jsonResp)
		}

	default:
		jsonResp = "{\"Error\":\"Invalid operaton requested: " + operation + "\"}"
		return nil, errors.New(jsonResp)
	}

	jsonResp = "{\"Response\":\"" + string(response) + "\"}"

	// transaction was successful, charge Issuer
	settlement, err := strconv.Atoi(amount)
	if err != nil {
		return nil, err
	}

	settlement = settlement + serviceCharge

	state = fmt.Sprintf("IBI owes ABI " + strconv.Itoa(settlement))

	// Write amount which IBI owes to ABI back to the ledger
	err = stub.PutState("IBI->ABI", []byte(state))
	if err != nil {
		return nil, err
	}

	fmt.Printf("Invoke chaincode successful. IBI Owes ABI %d\n", settlement)
	return []byte(state), nil
}

// Query callback representing the query of a chaincode
func (t *SimpleChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	if function != "Query" {
		return nil, errors.New("Invalid query function name. Expecting \"Query\"")
	}
	var jsonResp string
	var err error

	if len(args) != 1 {
		return nil, errors.New("Incorrect number of arguments. Expecting 1")
	}

	transactionName := args[0]

	valAsbytes, err := stub.GetState(transactionName)
	if err != nil {
		jsonResp = "{\"Error\":\"Failed to get state for " + transactionName + "\"}"
		return nil, errors.New(jsonResp)
	}

	fmt.Printf("Query chaincode successful. Got IBI->ABI %s\n", string(valAsbytes))
	jsonResp = "{\"IBI Owes ABI\":\"" + string(valAsbytes) + "\"}"
	fmt.Printf("Query Response:%s\n", jsonResp)
	return []byte(valAsbytes), nil

}

func main() {
	var err error
	lld, _ := shim.LogLevel("DEBUG")
	fmt.Println(lld)

	logger.SetLevel(lld)
	fmt.Println(logger.IsEnabledFor(lld))

	err = shim.Start(new(SimpleChaincode))
	if err != nil {
		fmt.Println("Could not start SimpleChaincode")
	} else {
		fmt.Println("SimpleChaincode successfully started")
	}
}
<|endoftext|>


<commit_before>package integration_tests

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

	. "github.com/onsi/ginkgo"
)

// creates a package repository mirror on the given node.
func createPackageRepositoryMirror(repoNode NodeDeets, distro linuxDistro, sshKey string) error {
	var mirrorScript string
	switch distro {
	case CentOS7:
		mirrorScript = "mirror-rpms.sh"
	case Ubuntu1604LTS:
		mirrorScript = "mirror-debs.sh"
	default:
		return fmt.Errorf("unable to create repo mirror for distro %q", distro)
	}
	start := time.Now()
	err := copyFileToRemote("test-resources/disconnected-installation/"+mirrorScript, "/tmp/"+mirrorScript, repoNode, sshKey, 10*time.Second)
	if err != nil {
		return fmt.Errorf("failed to copy script to remote node: %v", err)
	}
	cmds := []string{"chmod +x /tmp/" + mirrorScript, "sudo /tmp/" + mirrorScript}
	err = runViaSSH(cmds, []NodeDeets{repoNode}, sshKey, 60*time.Minute)
	if err != nil {
		return fmt.Errorf("error running mirroring script: %v", err)
	}
	elapsed := time.Since(start)
	fmt.Println("Creating a package repository took", elapsed)
	return nil
}

// seeds a container image registry using the kismatic seed-registry command
func seedRegistry(repoNode NodeDeets, registryCAFile string, registryPort int, sshKey string) error {
	By("Adding the docker registry self-signed cert to the registry node")
	registry := fmt.Sprintf("%s:%d", repoNode.PublicIP, registryPort)
	err := copyFileToRemote(registryCAFile, "/tmp/docker-registry-ca.crt", repoNode, sshKey, 30*time.Second)
	if err != nil {
		return fmt.Errorf("Failed to copy registry cert to registry node: %v", err)
	}
	cmds := []string{
		fmt.Sprintf("sudo mkdir -p /etc/docker/certs.d/%s", registry),
		fmt.Sprintf("sudo mv /tmp/docker-registry-ca.crt /etc/docker/certs.d/%s/ca.crt", registry),
	}
	err = runViaSSH(cmds, []NodeDeets{repoNode}, sshKey, 10*time.Minute)
	if err != nil {
		return fmt.Errorf("Error adding self-signed cert to registry node: %v", err)
	}

	By("Copying KET to the registry node for seeding")
	err = copyFileToRemote(filepath.Join(currentKismaticDir, "kismatic.tar.gz"), "/tmp/kismatic.tar.gz", repoNode, sshKey, 5*time.Minute)
	if err != nil {
		return fmt.Errorf("Error copying KET to the registry node: %v", err)
	}

	By("Seeding the registry")
	start := time.Now()
	cmds = []string{
		fmt.Sprintf("sudo docker login -u kismaticuser -p kismaticpassword %s", registry),
		"sudo tar -xf /tmp/kismatic.tar.gz",
		fmt.Sprintf("sudo ./kismatic seed-registry --server %s", registry),
	}
	err = runViaSSH(cmds, []NodeDeets{repoNode}, sshKey, 30*time.Minute)
	if err != nil {
		return fmt.Errorf("failed to seed the registry: %v", err)
	}
	elapsed := time.Since(start)
	fmt.Println("Seeding the registry took", elapsed)
	return nil
}
<commit_msg>Increase seed registry timeout for tests<commit_after>package integration_tests

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

	. "github.com/onsi/ginkgo"
)

// creates a package repository mirror on the given node.
func createPackageRepositoryMirror(repoNode NodeDeets, distro linuxDistro, sshKey string) error {
	var mirrorScript string
	switch distro {
	case CentOS7:
		mirrorScript = "mirror-rpms.sh"
	case Ubuntu1604LTS:
		mirrorScript = "mirror-debs.sh"
	default:
		return fmt.Errorf("unable to create repo mirror for distro %q", distro)
	}
	start := time.Now()
	err := copyFileToRemote("test-resources/disconnected-installation/"+mirrorScript, "/tmp/"+mirrorScript, repoNode, sshKey, 10*time.Second)
	if err != nil {
		return fmt.Errorf("failed to copy script to remote node: %v", err)
	}
	cmds := []string{"chmod +x /tmp/" + mirrorScript, "sudo /tmp/" + mirrorScript}
	err = runViaSSH(cmds, []NodeDeets{repoNode}, sshKey, 60*time.Minute)
	if err != nil {
		return fmt.Errorf("error running mirroring script: %v", err)
	}
	elapsed := time.Since(start)
	fmt.Println("Creating a package repository took", elapsed)
	return nil
}

// seeds a container image registry using the kismatic seed-registry command
func seedRegistry(repoNode NodeDeets, registryCAFile string, registryPort int, sshKey string) error {
	By("Adding the docker registry self-signed cert to the registry node")
	registry := fmt.Sprintf("%s:%d", repoNode.PublicIP, registryPort)
	err := copyFileToRemote(registryCAFile, "/tmp/docker-registry-ca.crt", repoNode, sshKey, 30*time.Second)
	if err != nil {
		return fmt.Errorf("Failed to copy registry cert to registry node: %v", err)
	}
	cmds := []string{
		fmt.Sprintf("sudo mkdir -p /etc/docker/certs.d/%s", registry),
		fmt.Sprintf("sudo mv /tmp/docker-registry-ca.crt /etc/docker/certs.d/%s/ca.crt", registry),
	}
	err = runViaSSH(cmds, []NodeDeets{repoNode}, sshKey, 10*time.Minute)
	if err != nil {
		return fmt.Errorf("Error adding self-signed cert to registry node: %v", err)
	}

	By("Copying KET to the registry node for seeding")
	err = copyFileToRemote(filepath.Join(currentKismaticDir, "kismatic.tar.gz"), "/tmp/kismatic.tar.gz", repoNode, sshKey, 5*time.Minute)
	if err != nil {
		return fmt.Errorf("Error copying KET to the registry node: %v", err)
	}

	By("Seeding the registry")
	start := time.Now()
	cmds = []string{
		fmt.Sprintf("sudo docker login -u kismaticuser -p kismaticpassword %s", registry),
		"sudo tar -xf /tmp/kismatic.tar.gz",
		fmt.Sprintf("sudo ./kismatic seed-registry --server %s", registry),
	}
	err = runViaSSH(cmds, []NodeDeets{repoNode}, sshKey, 60*time.Minute)
	if err != nil {
		return fmt.Errorf("failed to seed the registry: %v", err)
	}
	elapsed := time.Since(start)
	fmt.Println("Seeding the registry took", elapsed)
	return nil
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"encoding/binary"
	"fmt"
	"errors"
	"log"
	"math/rand"
	"net"
	"net/url"
	"strconv"
	"time"
)

type UdpTracker struct {
	*tracker
	connectionId  uint64
	transactionId uint32
	serverAddr    *net.UDPAddr
	conn          *net.UDPConn
}

type connectRequest struct {
	connectionId  uint64
	action        uint32
	transactionId uint32
}

type connectResponse struct {
	action        uint32
	transactionId uint32
	connectionId  uint64
}

type errorResponse struct {
	action        uint32
	transactionId uint32
	message       string
}

type shortString []byte

type announceRequest struct {
	connectionId  uint64
	action        uint32
	transactionId uint32
	infoHash      shortString
	peerId        shortString
	downloaded    uint64
	left          uint64
	uploaded      uint64
	event         uint32
	ipAddr        uint32
	key           uint32
	numWant       int32
	port          uint16
}

type announceResponse struct {
	action        uint32
	transactionId uint32
	interval      uint32
	leechers      uint32
	seeders       uint32
	peers         []PeerTuple
}

func (r *connectRequest) MarshalBinary() ([]byte, error) {
	buf := new(bytes.Buffer)
	err := binary.Write(buf, binary.BigEndian, r.connectionId)
	err = binary.Write(buf, binary.BigEndian, r.action)
	err = binary.Write(buf, binary.BigEndian, r.transactionId)
	return buf.Bytes(), err
}

func (r *connectResponse) UnmarshalBinary(data []byte) error {
	buf := bytes.NewReader(data[4:])
	actionBytes := append([]byte{0, 0, 0}, data[0])
	err := binary.Read(bytes.NewReader(actionBytes), binary.BigEndian, &r.action)
	err = binary.Read(buf, binary.BigEndian, &r.transactionId)
	err = binary.Read(buf, binary.BigEndian, &r.connectionId)
	return err
}

func (r *connectResponse) MarshalBinary() ([]byte, error) {
	var b bytes.Buffer
	fmt.Fprintln(&b, r.connectionId, r.action, r.transactionId)
	return b.Bytes(), nil
}

func (r *errorResponse) UnmarshalBinary(data []byte) error {
	actionBytes := append([]byte{0, 0, 0}, data[0])
	err := binary.Read(bytes.NewReader(actionBytes), binary.BigEndian, &r.action)
	err = binary.Read(bytes.NewReader(data[4:]), binary.BigEndian, &r.transactionId)
	r.message = string(data[8:])
	return err
}

func (r *announceRequest) MarshalBinary() ([]byte, error) {
	buf := new(bytes.Buffer)
	err := binary.Write(buf, binary.BigEndian, r.connectionId)
	err = binary.Write(buf, binary.BigEndian, r.action)
	err = binary.Write(buf, binary.BigEndian, r.transactionId)
	err = binary.Write(buf, binary.BigEndian, r.infoHash)
	err = binary.Write(buf, binary.BigEndian, r.peerId)
	err = binary.Write(buf, binary.BigEndian, r.downloaded)
	err = binary.Write(buf, binary.BigEndian, r.left)
	err = binary.Write(buf, binary.BigEndian, r.uploaded)
	err = binary.Write(buf, binary.BigEndian, r.event)
	err = binary.Write(buf, binary.BigEndian, r.ipAddr)
	err = binary.Write(buf, binary.BigEndian, r.key)
	err = binary.Write(buf, binary.BigEndian, r.numWant)
	err = binary.Write(buf, binary.BigEndian, r.port)
	return buf.Bytes(), err
}

func (r *announceResponse) UnmarshalBinary(data []byte) error {
	buf := bytes.NewReader(data[4:])
	actionBytes := append([]byte{0, 0, 0}, data[0])
	err := binary.Read(bytes.NewReader(actionBytes), binary.BigEndian, &r.action)
	err = binary.Read(buf, binary.BigEndian, &r.transactionId)
	err = binary.Read(buf, binary.BigEndian, &r.interval)
	err = binary.Read(buf, binary.BigEndian, &r.leechers)
	err = binary.Read(buf, binary.BigEndian, &r.seeders)

	peerBytes := data[20:]
	peers := len(peerBytes)/6

	for i := 0; i < peers; i++{
		peer := PeerTuple{}

		ipBytes := peerBytes[i*6:i*6+4]
		//log.Printf("ipbytes: %v\n", ipBytes)
		peer.IP = net.IPv4(ipBytes[0], ipBytes[1], ipBytes[2], ipBytes[3])
		binary.Read(bytes.NewReader(peerBytes[i*6+4:i*6+6]), binary.BigEndian, &peer.Port)

		log.Printf("peer: %s:%d\n", peer.IP.String(), peer.Port)
		r.peers = append(r.peers, peer)
	}

	return err
}

func NewUdpTracker(key string, chans trackerPeerChans, port uint16, infoHash []byte, announce *url.URL) *UdpTracker {
	return &UdpTracker{&tracker{key: key, peerChans: chans, port: port, infoHash: infoHash, announceURL: announce}, 0, 0, &net.UDPAddr{}, &net.UDPConn{}}
}

func (p *PeerTuple) String () string {
	return fmt.Sprintf("%s:%d\n", p.IP.String(), p.Port)
}

func (tr *UdpTracker) Announce(event int) {
	err := tr.connect()
	if err != nil {
		log.Println("Could not connect to tracker")
		return
	}

	log.Println("udp announce")
	key, _ := strconv.ParseUint(tr.key, 16, 4)
	announce := &announceRequest{
		connectionId:  tr.connectionId,
		action:        1,
		transactionId: tr.transactionId,
		infoHash:      tr.infoHash,
		peerId:        PeerID[:],
		downloaded:    uint64(tr.stats.Downloaded),
		left:          uint64(tr.stats.Left),
		uploaded:      uint64(tr.stats.Uploaded),
		event:         uint32(event),
		ipAddr:        0,
		key:           uint32(key),
		numWant:       -1,
		port:          6881,
	}
	announceBytes, _ := announce.MarshalBinary()
	tr.conn.WriteTo(announceBytes, tr.serverAddr)

	buff := make([]byte, 600)

	tr.conn.ReadFrom(buff)
	var response announceResponse
	response.UnmarshalBinary(buff)

	log.Printf("announce response: %+v\n", response.peers)

	if event != Stopped {
		if response.interval != 0 {
			nextAnnounce := time.Second * 120
			log.Printf("Tracker : Announce : Scheduling next announce in %v\n", nextAnnounce)
			tr.timer = time.After(nextAnnounce)
		}

		for _, peer := range response.peers {
			tr.peerChans.peers <- peer
		}
	}
}

func (tr *UdpTracker) connect () error {
	log.Printf("Tracker : Connect (%v)", tr.announceURL)

	connectReq := connectRequest{connectionId: 0x41727101980, action: 0, transactionId: tr.transactionId}
	connectBytes, _ := connectReq.MarshalBinary()

	buff := make([]byte, 150)
	tr.conn.WriteTo(connectBytes, tr.serverAddr)
	tr.conn.ReadFrom(buff)

	var response connectResponse
	response.UnmarshalBinary(buff)

	if response.action == 3 || tr.transactionId != response.transactionId {
		error := errorResponse{}
		error.UnmarshalBinary(buff)
		return errors.New("Response Error: " + error.message)
	}

	tr.connectionId = response.connectionId
	return nil
}

func (tr *UdpTracker) Run() {
	log.Printf("Tracker : Run : Started (%s)\n", tr.announceURL)
	defer log.Printf("Tracker : Run : Completed (%s)\n", tr.announceURL)

	rand.Seed(time.Now().UnixNano())

	serverAddr, err := net.ResolveUDPAddr("udp", tr.announceURL.Host)
	if err != nil {
		log.Println("Tracker : Could not resolve tracker host!")
		return
	}

	var conn *net.UDPConn
	for port := 6881; err == nil && port < 6890; port++ {
		conn, err = net.ListenUDP("udp", &net.UDPAddr{Port: port})
	}
	if err != nil {
		log.Println("Tracker : Could not bind to any port in range 6881-6889")
		return
	}

	tr.transactionId = rand.Uint32()
	tr.serverAddr = serverAddr
	tr.conn = conn
	tr.Announce(Started)

	for {
		select {
		case <-tr.quit:
			log.Println("Tracker : Stop : Stopping")
			tr.Announce(Stopped)
			return
		case <-tr.completedCh:
			go tr.Announce(Completed)
		case <-tr.timer:
			log.Printf("Tracker : Run : Interval Timer Expired (%s)\n", tr.announceURL)
			go tr.Announce(Interval)
		case stats := <-tr.peerChans.stats:
			log.Println("read from stats", stats)
		}
	}
}
<commit_msg>Added timeout capability for tracker requests<commit_after>package main

import (
	"bytes"
	"encoding/binary"
	"errors"
	"fmt"
	"log"
	"math"
	"math/rand"
	"net"
	"net/url"
	"strconv"
	"time"
)

type UdpTracker struct {
	*tracker
	connectionId  uint64
	transactionId uint32
	serverAddr    *net.UDPAddr
	conn          *net.UDPConn
}

type connectRequest struct {
	connectionId  uint64
	action        uint32
	transactionId uint32
}

type connectResponse struct {
	action        uint32
	transactionId uint32
	connectionId  uint64
}

type errorResponse struct {
	action        uint32
	transactionId uint32
	message       string
}

type shortString []byte

type announceRequest struct {
	connectionId  uint64
	action        uint32
	transactionId uint32
	infoHash      shortString
	peerId        shortString
	downloaded    uint64
	left          uint64
	uploaded      uint64
	event         uint32
	ipAddr        uint32
	key           uint32
	numWant       int32
	port          uint16
}

type announceResponse struct {
	action        uint32
	transactionId uint32
	interval      uint32
	leechers      uint32
	seeders       uint32
	peers         []PeerTuple
}

func (r *connectRequest) MarshalBinary() ([]byte, error) {
	buf := new(bytes.Buffer)
	err := binary.Write(buf, binary.BigEndian, r.connectionId)
	err = binary.Write(buf, binary.BigEndian, r.action)
	err = binary.Write(buf, binary.BigEndian, r.transactionId)
	return buf.Bytes(), err
}

func (r *connectResponse) UnmarshalBinary(data []byte) error {
	buf := bytes.NewReader(data[4:])
	actionBytes := append([]byte{0, 0, 0}, data[0])
	err := binary.Read(bytes.NewReader(actionBytes), binary.BigEndian, &r.action)
	err = binary.Read(buf, binary.BigEndian, &r.transactionId)
	err = binary.Read(buf, binary.BigEndian, &r.connectionId)
	return err
}

func (r *connectResponse) MarshalBinary() ([]byte, error) {
	var b bytes.Buffer
	fmt.Fprintln(&b, r.connectionId, r.action, r.transactionId)
	return b.Bytes(), nil
}

func (r *errorResponse) UnmarshalBinary(data []byte) error {
	actionBytes := append([]byte{0, 0, 0}, data[0])
	err := binary.Read(bytes.NewReader(actionBytes), binary.BigEndian, &r.action)
	err = binary.Read(bytes.NewReader(data[4:]), binary.BigEndian, &r.transactionId)
	r.message = string(data[8:])
	return err
}

func (r *announceRequest) MarshalBinary() ([]byte, error) {
	buf := new(bytes.Buffer)
	err := binary.Write(buf, binary.BigEndian, r.connectionId)
	err = binary.Write(buf, binary.BigEndian, r.action)
	err = binary.Write(buf, binary.BigEndian, r.transactionId)
	err = binary.Write(buf, binary.BigEndian, r.infoHash)
	err = binary.Write(buf, binary.BigEndian, r.peerId)
	err = binary.Write(buf, binary.BigEndian, r.downloaded)
	err = binary.Write(buf, binary.BigEndian, r.left)
	err = binary.Write(buf, binary.BigEndian, r.uploaded)
	err = binary.Write(buf, binary.BigEndian, r.event)
	err = binary.Write(buf, binary.BigEndian, r.ipAddr)
	err = binary.Write(buf, binary.BigEndian, r.key)
	err = binary.Write(buf, binary.BigEndian, r.numWant)
	err = binary.Write(buf, binary.BigEndian, r.port)
	return buf.Bytes(), err
}

func (r *announceResponse) UnmarshalBinary(data []byte) error {
	buf := bytes.NewReader(data[4:])
	actionBytes := append([]byte{0, 0, 0}, data[0])
	err := binary.Read(bytes.NewReader(actionBytes), binary.BigEndian, &r.action)
	err = binary.Read(buf, binary.BigEndian, &r.transactionId)
	err = binary.Read(buf, binary.BigEndian, &r.interval)
	err = binary.Read(buf, binary.BigEndian, &r.leechers)
	err = binary.Read(buf, binary.BigEndian, &r.seeders)

	peerBytes := data[20:]
	peers := len(peerBytes) / 6

	for i := 0; i < peers; i++ {
		peer := PeerTuple{}

		ipBytes := peerBytes[i*6 : i*6+4]
		//log.Printf("ipbytes: %v\n", ipBytes)
		peer.IP = net.IPv4(ipBytes[0], ipBytes[1], ipBytes[2], ipBytes[3])
		binary.Read(bytes.NewReader(peerBytes[i*6+4:i*6+6]), binary.BigEndian, &peer.Port)

		log.Printf("peer: %s:%d\n", peer.IP.String(), peer.Port)
		r.peers = append(r.peers, peer)
	}

	return err
}

func NewUdpTracker(key string, chans trackerPeerChans, port uint16, infoHash []byte, announce *url.URL) *UdpTracker {
	return &UdpTracker{&tracker{key: key, peerChans: chans, port: port, infoHash: infoHash, announceURL: announce}, 0, 0, &net.UDPAddr{}, &net.UDPConn{}}
}

func (p *PeerTuple) String() string {
	return fmt.Sprintf("%s:%d\n", p.IP.String(), p.Port)
}

func (tr *UdpTracker) Announce(event int) {
	err := tr.connect()
	if err != nil {
		log.Printf("Tracker : Could not connect to tracker %s\n", tr.announceURL.String())
		return
	}

	key, _ := strconv.ParseUint(tr.key, 16, 4)
	announce := &announceRequest{
		connectionId:  tr.connectionId,
		action:        1,
		transactionId: tr.transactionId,
		infoHash:      tr.infoHash,
		peerId:        PeerID[:],
		downloaded:    uint64(tr.stats.Downloaded),
		left:          uint64(tr.stats.Left),
		uploaded:      uint64(tr.stats.Uploaded),
		event:         uint32(event),
		ipAddr:        0,
		key:           uint32(key),
		numWant:       -1,
		port:          6881,
	}
	announceBytes, _ := announce.MarshalBinary()

	buff := make([]byte, 600)
	length := tr.request(announceBytes, buff)

	var response announceResponse
	response.UnmarshalBinary(buff[:length])

	log.Printf("announce response: %+v\n", response.peers)

	if event != Stopped {
		if response.interval != 0 {
			nextAnnounce := time.Second * 120
			log.Printf("Tracker : Announce : Scheduling next announce in %v\n", nextAnnounce)
			tr.timer = time.After(nextAnnounce)
		}

		for _, peer := range response.peers {
			tr.peerChans.peers <- peer
		}
	}
}

func (tr *UdpTracker) connect() error {
	log.Printf("Tracker : Connect (%v)", tr.announceURL)

	connectReq := connectRequest{connectionId: 0x41727101980, action: 0, transactionId: tr.transactionId}
	connectBytes, _ := connectReq.MarshalBinary()

	buff := make([]byte, 150)
	length := tr.request(connectBytes, buff)

	var response connectResponse
	response.UnmarshalBinary(buff[:length])

	if response.action == 3 || tr.transactionId != response.transactionId {
		error := errorResponse{}
		error.UnmarshalBinary(buff)
		return errors.New("Response Error: " + error.message)
	}

	tr.connectionId = response.connectionId
	return nil
}

func (tr *UdpTracker) Run() {
	log.Printf("Tracker : Run : Started (%s)\n", tr.announceURL)
	defer log.Printf("Tracker : Run : Completed (%s)\n", tr.announceURL)

	rand.Seed(time.Now().UnixNano())

	serverAddr, err := net.ResolveUDPAddr("udp", tr.announceURL.Host)
	if err != nil {
		log.Println("Tracker : Could not resolve tracker host!")
		return
	}

	var conn *net.UDPConn
	for port := 6881; err == nil && port < 6890; port++ {
		conn, err = net.ListenUDP("udp", &net.UDPAddr{Port: port})
	}
	if err != nil {
		log.Println("Tracker : Could not bind to any port in range 6881-6889")
		return
	}

	tr.transactionId = rand.Uint32()
	tr.serverAddr = serverAddr
	tr.conn = conn
	tr.Announce(Started)

	for {
		select {
		case <-tr.quit:
			log.Println("Tracker : Stop : Stopping")
			tr.Announce(Stopped)
			return
		case <-tr.completedCh:
			go tr.Announce(Completed)
		case <-tr.timer:
			log.Printf("Tracker : Run : Interval Timer Expired (%s)\n", tr.announceURL)
			go tr.Announce(Interval)
		case stats := <-tr.peerChans.stats:
			log.Println("read from stats", stats)
		}
	}
}

func (tr *UdpTracker) request(payload []byte, dest []byte) int {
	attempt := 1
	recvChan := make(chan bool)

	go func() {
		tr.conn.WriteTo(payload, tr.serverAddr)
		for {
			timeout := time.Second * time.Duration(15*math.Pow(2.0, float64(attempt)))
			timer := time.After(timeout)

			select {
			case <-recvChan:
				break
			case <-timer:
				tr.conn.WriteTo(payload, tr.serverAddr)
				if attempt < 8 {
					attempt++
				}
			}
		}
	}()

	length := 0
	for length == 0 {
		length, _, _ = tr.conn.ReadFrom(dest)
	}
	recvChan <- true
	return length
}
<|endoftext|>


<commit_before>package pivotaltracker

import (
	// Stdlib
	"fmt"

	// Vendor
	"github.com/salsita/go-pivotaltracker/v5/pivotal"
)

type commonStory struct {
	client *pivotal.Client
	story  *pivotal.Story
}

func (s *commonStory) OnReviewRequestOpened(rrID, rrURL string) error {
	return s.addComment(fmt.Sprintf("Review request [#%v](%v) opened.", rrID, rrURL))
}

func (s *commonStory) OnReviewRequestClosed(rrID, rrURL string) error {
	return nil
}

func (s *commonStory) OnReviewRequestReopened(rrID, rrURL string) error {
	// Prune workflow labels.
	// Reset to started.
	state := pivotal.StoryStateStarted
	labels := pruneLabels(*s.story.Labels)

	// Update the story.
	req := &pivotal.Story{
		State:  state,
		Labels: &labels,
	}
	story, _, err := s.client.Stories.Update(s.story.ProjectId, s.story.Id, req)
	if err != nil {
		return err
	}

	s.story = story
	return nil
}

func (s *commonStory) MarkAsReviewed() error {
	// Get PT config.
	config := GetConfig()

	// Prune workflow labels.
	// Add the reviewed label.
	// Reset to started.
	state := pivotal.StoryStateStarted
	labels := append(pruneLabels(*s.story.Labels), &pivotal.Label{
		Name: config.ReviewedLabel,
	})

	// Update the story.
	req := &pivotal.Story{
		State:  state,
		Labels: &labels,
	}
	story, _, err := s.client.Stories.Update(s.story.ProjectId, s.story.Id, req)
	if err != nil {
		return err
	}

	s.story = story
	return nil
}

func (s *commonStory) addComment(text string) error {
	var (
		pid = s.story.ProjectId
		sid = s.story.Id
	)
	comment, _, err := s.client.Stories.AddComment(pid, sid, &pivotal.Comment{
		Text: text,
	})
	if err != nil {
		return err
	}

	commentIds := append(*s.story.CommentIds, comment.Id)
	s.story.CommentIds = &commentIds
	return nil
}

func pruneLabels(labels []*pivotal.Label) []*pivotal.Label {
	ls := make([]*pivotal.Label, 0, len(labels))
	for _, label := range labels {
		switch label.Name {
		case config.ReviewedLabel:
		case config.TestingPassedLabel:
		case config.TestingFailedLabel:
		case config.ImplementedLabel:
		default:
			ls = append(labels, &pivotal.Label{
				Id: label.Id,
			})
		}
	}
	return ls
}
<commit_msg>pivotaltracker: Aligh with go-pivotaltracker<commit_after>package pivotaltracker

import (
	// Stdlib
	"fmt"

	// Vendor
	"github.com/salsita/go-pivotaltracker/v5/pivotal"
)

type commonStory struct {
	client *pivotal.Client
	story  *pivotal.Story
}

func (s *commonStory) OnReviewRequestOpened(rrID, rrURL string) error {
	return s.addComment(fmt.Sprintf("Review request [#%v](%v) opened.", rrID, rrURL))
}

func (s *commonStory) OnReviewRequestClosed(rrID, rrURL string) error {
	return nil
}

func (s *commonStory) OnReviewRequestReopened(rrID, rrURL string) error {
	// Prune workflow labels.
	// Reset to started.
	state := pivotal.StoryStateStarted
	labels := pruneLabels(s.story.Labels)

	// Update the story.
	req := &pivotal.StoryRequest{
		State:  state,
		Labels: &labels,
	}
	story, _, err := s.client.Stories.Update(s.story.ProjectId, s.story.Id, req)
	if err != nil {
		return err
	}

	s.story = story
	return nil
}

func (s *commonStory) MarkAsReviewed() error {
	// Get PT config.
	config := GetConfig()

	// Prune workflow labels.
	// Add the reviewed label.
	// Reset to started.
	state := pivotal.StoryStateStarted
	labels := append(pruneLabels(s.story.Labels), &pivotal.Label{
		Name: config.ReviewedLabel,
	})

	// Update the story.
	req := &pivotal.StoryRequest{
		State:  state,
		Labels: &labels,
	}
	story, _, err := s.client.Stories.Update(s.story.ProjectId, s.story.Id, req)
	if err != nil {
		return err
	}

	s.story = story
	return nil
}

func (s *commonStory) addComment(text string) error {
	var (
		pid = s.story.ProjectId
		sid = s.story.Id
	)
	comment, _, err := s.client.Stories.AddComment(pid, sid, &pivotal.Comment{
		Text: text,
	})
	if err != nil {
		return err
	}

	s.story.CommentIds = append(s.story.CommentIds, comment.Id)
	return nil
}

func pruneLabels(labels []*pivotal.Label) []*pivotal.Label {
	ls := make([]*pivotal.Label, 0, len(labels))
	for _, label := range labels {
		switch label.Name {
		case config.ReviewedLabel:
		case config.TestingPassedLabel:
		case config.TestingFailedLabel:
		case config.ImplementedLabel:
		default:
			ls = append(labels, &pivotal.Label{
				Id: label.Id,
			})
		}
	}
	return ls
}
<|endoftext|>


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

// +build integration

package docker

import (
	"bytes"
	"testing"

	dockerclient "github.com/fsouza/go-dockerclient"
	. "gopkg.in/check.v1"
)

func TestDocker(t *testing.T) { TestingT(t) }

type DockerSuite struct {
	dc     *dockerclient.Client
	docker *DockerClient
	regid  string
}

var _ = Suite(&DockerSuite{})

func (s *DockerSuite) SetUpSuite(c *C) {
	var err error
	s.dc, err = dockerclient.NewClient(DefaultSocket)
	if err != nil {
		c.Fatalf("Could not connect to docker client: %s", err)
	}
	s.docker = &DockerClient{dc: s.dc}
	if ctr, err := s.dc.InspectContainer("regtestserver"); err == nil {
		s.dc.KillContainer(dockerclient.KillContainerOptions{ID: ctr.ID})
		opts := dockerclient.RemoveContainerOptions{
			ID:            ctr.ID,
			RemoveVolumes: true,
			Force:         true,
		}
		s.dc.RemoveContainer(opts)
	} else {
		opts := dockerclient.PullImageOptions{
			Repository: "registry",
			Tag:        "2.1.1",
		}
		auth := dockerclient.AuthConfiguration{}
		s.dc.PullImage(opts, auth)
	}
	// Start the docker registry
	opts := dockerclient.CreateContainerOptions{Name: "regtestserver"}
	opts.Config = &dockerclient.Config{Image: "registry:2.1.1"}
	opts.HostConfig = &dockerclient.HostConfig{
		PortBindings: map[dockerclient.Port][]dockerclient.PortBinding{
			"5000/tcp": []dockerclient.PortBinding{
				{HostIP: "localhost", HostPort: "5000"},
			},
		},
	}
	ctr, err := s.dc.CreateContainer(opts)
	if err != nil {
		c.Fatalf("Could not initialize docker registry: %s", err)
	}
	s.regid = ctr.ID
	if err := s.dc.StartContainer(ctr.ID, nil); err != nil {
		c.Fatalf("Could not start docker registry: %s", err)
	}
}

func (s *DockerSuite) TearDownSuite(c *C) {
	// Shut down the docker registry
	s.dc.StopContainer(s.regid, 10)
	opts := dockerclient.RemoveContainerOptions{
		ID:            s.regid,
		RemoveVolumes: true,
		Force:         true,
	}
	s.dc.RemoveContainer(opts)
}

func (s *DockerSuite) SetUpTest(c *C) {
	opts := dockerclient.PullImageOptions{Repository: "busybox", Tag: "latest"}
	auth := dockerclient.AuthConfiguration{}
	if err := s.dc.PullImage(opts, auth); err != nil {
		c.Fatalf("Could not pull test image: %s", err)
	}
}

func (s *DockerSuite) TestFindImage(c *C) {
	_, err := s.docker.FindImage("fakebox")
	c.Assert(err, Equals, dockerclient.ErrNoSuchImage)
	expected, err := s.dc.InspectImage("busybox")
	c.Assert(err, IsNil)
	actual, err := s.docker.FindImage("busybox")
	c.Assert(err, IsNil)
	c.Assert(actual, DeepEquals, expected)
}

func (s *DockerSuite) TestSaveImages(c *C) {
	buffer := bytes.NewBufferString("")
	err := s.docker.SaveImages([]string{"busybox"}, buffer)
	c.Assert(err, IsNil)
	err = s.dc.RemoveImage("busybox")
	c.Assert(err, IsNil)
	err = s.dc.LoadImage(dockerclient.LoadImageOptions{InputStream: buffer})
	c.Assert(err, IsNil)
	_, err = s.dc.InspectImage("busybox")
	c.Assert(err, IsNil)
}

func (s *DockerSuite) TestLoadImage(c *C) {
	buffer := bytes.NewBufferString("")
	err := s.dc.ExportImages(dockerclient.ExportImagesOptions{Names: []string{"busybox"}, OutputStream: buffer})
	c.Assert(err, IsNil)
	err = s.dc.RemoveImage("busybox")
	c.Assert(err, IsNil)
	err = s.docker.LoadImage(buffer)
	c.Assert(err, IsNil)
	_, err = s.dc.InspectImage("busybox")
	c.Assert(err, IsNil)
}

func (s *DockerSuite) TestPushImage(c *C) {
	defer s.dc.RemoveImage("localhost:5000/busybox:push")
	err := s.docker.PushImage("localhost:5000/busybox:push")
	c.Assert(err, NotNil)
	err = s.dc.TagImage("busybox", dockerclient.TagImageOptions{Repo: "localhost:5000/busybox", Tag: "push"})
	c.Assert(err, IsNil)
	err = s.docker.PushImage("localhost:5000/busybox:push")
	c.Assert(err, IsNil)
	err = s.dc.RemoveImage("localhost:5000/busybox:push")
	c.Assert(err, IsNil)
	opts := dockerclient.PullImageOptions{
		Repository: "localhost:5000/busybox",
		Registry:   "localhost:5000",
		Tag:        "push",
	}
	auth := dockerclient.AuthConfiguration{}
	err = s.dc.PullImage(opts, auth)
	c.Assert(err, IsNil)
	_, err = s.dc.InspectImage("localhost:5000/busybox:push")
	c.Assert(err, IsNil)
}

func (s *DockerSuite) TestPullImage(c *C) {
	defer s.dc.RemoveImage("localhost:5000/busybox:pull")
	err := s.docker.PullImage("localhost:5000/busybox:pull")
	c.Assert(err, NotNil)
	err = s.dc.TagImage("busybox", dockerclient.TagImageOptions{Repo: "localhost:5000/busybox", Tag: "pull"})
	c.Assert(err, IsNil)
	opts := dockerclient.PushImageOptions{
		Name:     "localhost:5000/busybox",
		Tag:      "pull",
		Registry: "localhost:5000",
	}
	auth := dockerclient.AuthConfiguration{}
	err = s.dc.PushImage(opts, auth)
	c.Assert(err, IsNil)
	err = s.dc.RemoveImage("localhost:5000/busybox:pull")
	c.Assert(err, IsNil)
	err = s.docker.PullImage("localhost:5000/busybox:pull")
	c.Assert(err, IsNil)
	_, err = s.dc.InspectImage("localhost:5000/busybox:pull")
	c.Assert(err, IsNil)
}

func (s *DockerSuite) TestTagImage(c *C) {
	defer s.dc.RemoveImage("localhost:5000/busybox:tag")
	err := s.docker.TagImage("fakebox", "localhost:5000/busybox:tag")
	c.Assert(err, NotNil)
	err = s.docker.TagImage("busybox", "localhost:5000/busybox:tag")
	c.Assert(err, IsNil)
	_, err = s.dc.InspectImage("localhost:5000/busybox:tag")
	c.Assert(err, IsNil)
}

func (s *DockerSuite) TestRemoveImage(c *C) {
	defer s.dc.RemoveImage("localhost:5000/busybox:remove")
	err := s.docker.RemoveImage("localhost:5000/busybox:remove")
	c.Assert(err, NotNil)
	err = s.dc.TagImage("busybox", dockerclient.TagImageOptions{Repo: "localhost:5000/busybox", Tag: "remove"})
	c.Assert(err, IsNil)
	err = s.docker.RemoveImage("localhost:5000/busybox:remove")
	c.Assert(err, IsNil)
	_, err = s.dc.InspectImage("localhost:5000/busybox:remove")
	c.Assert(err, NotNil)
}

func (s *DockerSuite) TestFindContainer(c *C) {
	_, err := s.docker.FindContainer("fakecontainer")
	c.Assert(err, NotNil)
	opts := dockerclient.CreateContainerOptions{}
	opts.Config = &dockerclient.Config{Image: "busybox"}
	expected, err := s.dc.CreateContainer(opts)
	c.Assert(err, IsNil)
	defer s.dc.RemoveContainer(dockerclient.RemoveContainerOptions{ID: expected.ID, RemoveVolumes: true, Force: true})
	actual, err := s.docker.FindContainer(expected.ID)
	c.Assert(err, IsNil)
	c.Assert(actual.ID, DeepEquals, expected.ID)
}

func (s *DockerSuite) TestCommitContainer(c *C) {
	defer s.dc.RemoveImage("localhost:5000/busybox:commit")
	opts := dockerclient.CreateContainerOptions{}
	opts.Config = &dockerclient.Config{Image: "busybox"}
	ctr, err := s.dc.CreateContainer(opts)
	c.Assert(err, IsNil)
	defer s.dc.RemoveContainer(dockerclient.RemoveContainerOptions{ID: ctr.ID, RemoveVolumes: true, Force: true})
	expected, err := s.docker.CommitContainer(ctr.ID, "localhost:5000/busybox:commit")
	c.Assert(err, IsNil)
	actual, err := s.dc.InspectImage("localhost:5000/busybox:commit")
	c.Assert(err, IsNil)
	c.Assert(actual.ID, DeepEquals, expected.ID)
}

func (s *DockerSuite) TestGetImageHash(c *C) {
	_, err := s.docker.GetImageHash("fakebox")
	c.Assert(err, Equals, dockerclient.ErrNoSuchImage)
	hash1, err1 := s.docker.GetImageHash("busybox")
	hash2, err2 := s.docker.GetImageHash("registry")
	c.Assert(err1, IsNil)
	c.Assert(err2, IsNil)
	c.Assert(hash1, Not(Equals), "")
	c.Assert(hash2, Not(Equals), "")
	c.Assert(hash1, Not(Equals), hash2)
}
<commit_msg>fixed docker unit test<commit_after>// Copyright 2015 The Serviced Authors.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// +build integration

package docker

import (
	"bytes"
	"testing"

	dockerclient "github.com/fsouza/go-dockerclient"
	. "gopkg.in/check.v1"
)

func TestDocker(t *testing.T) { TestingT(t) }

type DockerSuite struct {
	dc     *dockerclient.Client
	docker *DockerClient
	regid  string
}

var _ = Suite(&DockerSuite{})

func (s *DockerSuite) SetUpSuite(c *C) {
	var err error
	s.dc, err = dockerclient.NewClient(DefaultSocket)
	if err != nil {
		c.Fatalf("Could not connect to docker client: %s", err)
	}
	s.docker = &DockerClient{dc: s.dc}
	if ctr, err := s.dc.InspectContainer("regtestserver"); err == nil {
		s.dc.KillContainer(dockerclient.KillContainerOptions{ID: ctr.ID})
		opts := dockerclient.RemoveContainerOptions{
			ID:            ctr.ID,
			RemoveVolumes: true,
			Force:         true,
		}
		s.dc.RemoveContainer(opts)
	} else {
		opts := dockerclient.PullImageOptions{
			Repository: "registry",
			Tag:        "2.1.1",
		}
		auth := dockerclient.AuthConfiguration{}
		s.dc.PullImage(opts, auth)
	}
	// Start the docker registry
	opts := dockerclient.CreateContainerOptions{Name: "regtestserver"}
	opts.Config = &dockerclient.Config{Image: "registry:2.1.1"}
	opts.HostConfig = &dockerclient.HostConfig{
		PortBindings: map[dockerclient.Port][]dockerclient.PortBinding{
			"5000/tcp": []dockerclient.PortBinding{
				{HostIP: "localhost", HostPort: "5000"},
			},
		},
	}
	ctr, err := s.dc.CreateContainer(opts)
	if err != nil {
		c.Fatalf("Could not initialize docker registry: %s", err)
	}
	s.regid = ctr.ID
	if err := s.dc.StartContainer(ctr.ID, nil); err != nil {
		c.Fatalf("Could not start docker registry: %s", err)
	}
}

func (s *DockerSuite) TearDownSuite(c *C) {
	// Shut down the docker registry
	s.dc.StopContainer(s.regid, 10)
	opts := dockerclient.RemoveContainerOptions{
		ID:            s.regid,
		RemoveVolumes: true,
		Force:         true,
	}
	s.dc.RemoveContainer(opts)
}

func (s *DockerSuite) SetUpTest(c *C) {
	opts := dockerclient.PullImageOptions{Repository: "busybox", Tag: "latest"}
	auth := dockerclient.AuthConfiguration{}
	if err := s.dc.PullImage(opts, auth); err != nil {
		c.Fatalf("Could not pull test image: %s", err)
	}
}

func (s *DockerSuite) TestFindImage(c *C) {
	_, err := s.docker.FindImage("fakebox")
	c.Assert(err, Equals, dockerclient.ErrNoSuchImage)
	expected, err := s.dc.InspectImage("busybox")
	c.Assert(err, IsNil)
	actual, err := s.docker.FindImage("busybox")
	c.Assert(err, IsNil)
	c.Assert(actual, DeepEquals, expected)
}

func (s *DockerSuite) TestSaveImages(c *C) {
	buffer := bytes.NewBufferString("")
	err := s.docker.SaveImages([]string{"busybox"}, buffer)
	c.Assert(err, IsNil)
	err = s.dc.RemoveImage("busybox")
	c.Assert(err, IsNil)
	err = s.dc.LoadImage(dockerclient.LoadImageOptions{InputStream: buffer})
	c.Assert(err, IsNil)
	_, err = s.dc.InspectImage("busybox")
	c.Assert(err, IsNil)
}

func (s *DockerSuite) TestLoadImage(c *C) {
	buffer := bytes.NewBufferString("")
	err := s.dc.ExportImages(dockerclient.ExportImagesOptions{Names: []string{"busybox"}, OutputStream: buffer})
	c.Assert(err, IsNil)
	err = s.dc.RemoveImage("busybox")
	c.Assert(err, IsNil)
	err = s.docker.LoadImage(buffer)
	c.Assert(err, IsNil)
	_, err = s.dc.InspectImage("busybox")
	c.Assert(err, IsNil)
}

func (s *DockerSuite) TestPushImage(c *C) {
	defer s.dc.RemoveImage("localhost:5000/busybox:push")
	err := s.docker.PushImage("localhost:5000/busybox:push")
	c.Assert(err, NotNil)
	err = s.dc.TagImage("busybox", dockerclient.TagImageOptions{Repo: "localhost:5000/busybox", Tag: "push"})
	c.Assert(err, IsNil)
	err = s.docker.PushImage("localhost:5000/busybox:push")
	c.Assert(err, IsNil)
	err = s.dc.RemoveImage("localhost:5000/busybox:push")
	c.Assert(err, IsNil)
	opts := dockerclient.PullImageOptions{
		Repository: "localhost:5000/busybox",
		Registry:   "localhost:5000",
		Tag:        "push",
	}
	auth := dockerclient.AuthConfiguration{}
	err = s.dc.PullImage(opts, auth)
	c.Assert(err, IsNil)
	_, err = s.dc.InspectImage("localhost:5000/busybox:push")
	c.Assert(err, IsNil)
}

func (s *DockerSuite) TestPullImage(c *C) {
	defer s.dc.RemoveImage("localhost:5000/busybox:pull")
	err := s.docker.PullImage("localhost:5000/busybox:pull")
	c.Assert(err, NotNil)
	err = s.dc.TagImage("busybox", dockerclient.TagImageOptions{Repo: "localhost:5000/busybox", Tag: "pull"})
	c.Assert(err, IsNil)
	opts := dockerclient.PushImageOptions{
		Name:     "localhost:5000/busybox",
		Tag:      "pull",
		Registry: "localhost:5000",
	}
	auth := dockerclient.AuthConfiguration{}
	err = s.dc.PushImage(opts, auth)
	c.Assert(err, IsNil)
	err = s.dc.RemoveImage("localhost:5000/busybox:pull")
	c.Assert(err, IsNil)
	err = s.docker.PullImage("localhost:5000/busybox:pull")
	c.Assert(err, IsNil)
	_, err = s.dc.InspectImage("localhost:5000/busybox:pull")
	c.Assert(err, IsNil)
}

func (s *DockerSuite) TestTagImage(c *C) {
	defer s.dc.RemoveImage("localhost:5000/busybox:tag")
	err := s.docker.TagImage("fakebox", "localhost:5000/busybox:tag")
	c.Assert(err, NotNil)
	err = s.docker.TagImage("busybox", "localhost:5000/busybox:tag")
	c.Assert(err, IsNil)
	_, err = s.dc.InspectImage("localhost:5000/busybox:tag")
	c.Assert(err, IsNil)
}

func (s *DockerSuite) TestRemoveImage(c *C) {
	defer s.dc.RemoveImage("localhost:5000/busybox:remove")
	err := s.docker.RemoveImage("localhost:5000/busybox:remove")
	c.Assert(err, NotNil)
	err = s.dc.TagImage("busybox", dockerclient.TagImageOptions{Repo: "localhost:5000/busybox", Tag: "remove"})
	c.Assert(err, IsNil)
	err = s.docker.RemoveImage("localhost:5000/busybox:remove")
	c.Assert(err, IsNil)
	_, err = s.dc.InspectImage("localhost:5000/busybox:remove")
	c.Assert(err, NotNil)
}

func (s *DockerSuite) TestFindContainer(c *C) {
	_, err := s.docker.FindContainer("fakecontainer")
	c.Assert(err, NotNil)
	opts := dockerclient.CreateContainerOptions{}
	opts.Config = &dockerclient.Config{Image: "busybox"}
	expected, err := s.dc.CreateContainer(opts)
	c.Assert(err, IsNil)
	defer s.dc.RemoveContainer(dockerclient.RemoveContainerOptions{ID: expected.ID, RemoveVolumes: true, Force: true})
	actual, err := s.docker.FindContainer(expected.ID)
	c.Assert(err, IsNil)
	c.Assert(actual.ID, DeepEquals, expected.ID)
}

func (s *DockerSuite) TestCommitContainer(c *C) {
	defer s.dc.RemoveImage("localhost:5000/busybox:commit")
	opts := dockerclient.CreateContainerOptions{}
	opts.Config = &dockerclient.Config{Image: "busybox"}
	ctr, err := s.dc.CreateContainer(opts)
	c.Assert(err, IsNil)
	defer s.dc.RemoveContainer(dockerclient.RemoveContainerOptions{ID: ctr.ID, RemoveVolumes: true, Force: true})
	expected, err := s.docker.CommitContainer(ctr.ID, "localhost:5000/busybox:commit")
	c.Assert(err, IsNil)
	actual, err := s.dc.InspectImage("localhost:5000/busybox:commit")
	c.Assert(err, IsNil)
	c.Assert(actual.ID, DeepEquals, expected.ID)
}

func (s *DockerSuite) TestGetImageHash(c *C) {
	_, err := s.docker.GetImageHash("fakebox")
	c.Assert(err, Equals, dockerclient.ErrNoSuchImage)
	hash1, err1 := s.docker.GetImageHash("busybox")
	hash2, err2 := s.docker.GetImageHash("registry:2.1.1")
	c.Assert(err1, IsNil)
	c.Assert(err2, IsNil)
	c.Assert(hash1, Not(Equals), "")
	c.Assert(hash2, Not(Equals), "")
	c.Assert(hash1, Not(Equals), hash2)
}
<|endoftext|>


<commit_before>/*
Copyright IBM Corp. 2016 All Rights Reserved.

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 common

import (
	cb "github.com/hyperledger/fabric/protos/common"
	pb "github.com/hyperledger/fabric/protos/peer"
	context "golang.org/x/net/context"
	grpc "google.golang.org/grpc"
)

// GetMockEndorserClient return a endorser client return specified ProposalResponse and err(nil or error)
func GetMockEndorserClient(repponse *pb.ProposalResponse, err error) pb.EndorserClient {
	return &mockEndorserClient{
		repponse: repponse,
		err:      err,
	}
}

type mockEndorserClient struct {
	repponse *pb.ProposalResponse
	err      error
}

func (m *mockEndorserClient) ProcessProposal(ctx context.Context, in *pb.SignedProposal, opts ...grpc.CallOption) (*pb.ProposalResponse, error) {
	return m.repponse, m.err
}

func GetMockBroadcastClient(err error) BroadcastClient {
	return &mockBroadcastClient{err: err}
}

// mockBroadcastClient return success immediately
type mockBroadcastClient struct {
	err error
}

func (m *mockBroadcastClient) Send(env *cb.Envelope) error {
	return m.err
}

func (m *mockBroadcastClient) Close() error {
	return nil
}
<commit_msg>Fix param name in peer/common/mockclient.go<commit_after>/*
Copyright IBM Corp. 2016 All Rights Reserved.

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 common

import (
	cb "github.com/hyperledger/fabric/protos/common"
	pb "github.com/hyperledger/fabric/protos/peer"
	context "golang.org/x/net/context"
	grpc "google.golang.org/grpc"
)

// GetMockEndorserClient return a endorser client return specified ProposalResponse and err(nil or error)
func GetMockEndorserClient(response *pb.ProposalResponse, err error) pb.EndorserClient {
	return &mockEndorserClient{
		response: response,
		err:      err,
	}
}

type mockEndorserClient struct {
	response *pb.ProposalResponse
	err      error
}

func (m *mockEndorserClient) ProcessProposal(ctx context.Context, in *pb.SignedProposal, opts ...grpc.CallOption) (*pb.ProposalResponse, error) {
	return m.response, m.err
}

func GetMockBroadcastClient(err error) BroadcastClient {
	return &mockBroadcastClient{err: err}
}

// mockBroadcastClient return success immediately
type mockBroadcastClient struct {
	err error
}

func (m *mockBroadcastClient) Send(env *cb.Envelope) error {
	return m.err
}

func (m *mockBroadcastClient) Close() error {
	return nil
}
<|endoftext|>


<commit_before>package gorillaws

import (
	"github.com/davyxu/cellnet"
	"github.com/davyxu/cellnet/peer"
	"github.com/davyxu/cellnet/util"
	"github.com/gorilla/websocket"
	"sync"
)

// Socket会话
type wsSession struct {
	peer.CoreContextSet
	peer.CoreSessionIdentify
	*peer.CoreProcBundle

	pInterface cellnet.Peer

	conn *websocket.Conn

	// 退出同步器
	exitSync sync.WaitGroup

	// 发送队列
	sendQueue *cellnet.Pipe

	cleanupGuard sync.Mutex

	endNotify func()
}

func (self *wsSession) Peer() cellnet.Peer {
	return self.pInterface
}

// 取原始连接
func (self *wsSession) Raw() interface{} {
	if self.conn == nil {
		return nil
	}

	return self.conn
}

func (self *wsSession) Close() {
	self.sendQueue.Add(nil)
}

// 发送封包
func (self *wsSession) Send(msg interface{}) {
	self.sendQueue.Add(msg)
}

// 接收循环
func (self *wsSession) recvLoop() {

	for self.conn != nil {

		msg, err := self.ReadMessage(self)

		if err != nil {
			if !util.IsEOFOrNetReadError(err) {
				log.Errorln("session closed:", err)
			}

			self.ProcEvent(&cellnet.RecvMsgEvent{Ses: self, Msg: &cellnet.SessionClosed{}})
			break
		}

		self.ProcEvent(&cellnet.RecvMsgEvent{Ses: self, Msg: msg})
	}

	self.cleanup()
}

// 发送循环
func (self *wsSession) sendLoop() {

	var writeList []interface{}

	for {
		writeList = writeList[0:0]
		exit := self.sendQueue.Pick(&writeList)

		// 遍历要发送的数据
		for _, msg := range writeList {

			// TODO SendMsgEvent并不是很有意义
			self.SendMessage(&cellnet.SendMsgEvent{Ses: self, Msg: msg})
		}

		if exit {
			break
		}
	}

	self.cleanup()
}

// 清理资源
func (self *wsSession) cleanup() {

	self.cleanupGuard.Lock()

	defer self.cleanupGuard.Unlock()

	// 关闭连接
	if self.conn != nil {
		self.conn.Close()
		self.conn = nil
	}

	// 通知完成
	self.exitSync.Done()
}

// 启动会话的各种资源
func (self *wsSession) Start() {

	// 将会话添加到管理器
	self.Peer().(peer.SessionManager).Add(self)

	// 需要接收和发送线程同时完成时才算真正的完成
	self.exitSync.Add(2)

	go func() {

		// 等待2个任务结束
		self.exitSync.Wait()

		// 将会话从管理器移除
		self.Peer().(peer.SessionManager).Remove(self)

		if self.endNotify != nil {
			self.endNotify()
		}

	}()

	// 启动并发接收goroutine
	go self.recvLoop()

	// 启动并发发送goroutine
	go self.sendLoop()
}

func newSession(conn *websocket.Conn, p cellnet.Peer, endNotify func()) *wsSession {
	self := &wsSession{
		conn:       conn,
		endNotify:  endNotify,
		sendQueue:  cellnet.NewPipe(),
		pInterface: p,
		CoreProcBundle: p.(interface {
			GetBundle() *peer.CoreProcBundle
		}).GetBundle(),
	}

	return self
}
<commit_msg>修复 websocket 客服端关闭服务端无法释放 #60<commit_after>package gorillaws

import (
	"github.com/davyxu/cellnet"
	"github.com/davyxu/cellnet/peer"
	"github.com/davyxu/cellnet/util"
	"github.com/gorilla/websocket"
	"sync"
)

// Socket会话
type wsSession struct {
	peer.CoreContextSet
	peer.CoreSessionIdentify
	*peer.CoreProcBundle

	pInterface cellnet.Peer

	conn *websocket.Conn

	// 退出同步器
	exitSync sync.WaitGroup

	// 发送队列
	sendQueue *cellnet.Pipe

	cleanupGuard sync.Mutex

	endNotify func()
}

func (self *wsSession) Peer() cellnet.Peer {
	return self.pInterface
}

// 取原始连接
func (self *wsSession) Raw() interface{} {
	if self.conn == nil {
		return nil
	}

	return self.conn
}

func (self *wsSession) Close() {
	self.sendQueue.Add(nil)
}

// 发送封包
func (self *wsSession) Send(msg interface{}) {
	self.sendQueue.Add(msg)
}

// 接收循环
func (self *wsSession) recvLoop() {

	for self.conn != nil {

		msg, err := self.ReadMessage(self)

		if err != nil {
			if !util.IsEOFOrNetReadError(err) {
				log.Errorln("session closed:", err)
			}

			self.ProcEvent(&cellnet.RecvMsgEvent{Ses: self, Msg: &cellnet.SessionClosed{}})
			break
		}

		self.ProcEvent(&cellnet.RecvMsgEvent{Ses: self, Msg: msg})
	}

	self.cleanup()
}

// 发送循环
func (self *wsSession) sendLoop() {

	var writeList []interface{}

	for {
		writeList = writeList[0:0]
		exit := self.sendQueue.Pick(&writeList)

		// 遍历要发送的数据
		for _, msg := range writeList {

			// TODO SendMsgEvent并不是很有意义
			self.SendMessage(&cellnet.SendMsgEvent{Ses: self, Msg: msg})
		}

		if exit {
			break
		}
	}

	self.cleanup()
}

// 清理资源
func (self *wsSession) cleanup() {

	self.cleanupGuard.Lock()

	defer self.cleanupGuard.Unlock()

	// 关闭连接
	if self.conn != nil {
		self.conn.Close()
		self.conn = nil
	}

	// pal301x: websocket 客服端关闭服务端无法释放 issue 60
	self.Close()

	// 通知完成
	self.exitSync.Done()
}

// 启动会话的各种资源
func (self *wsSession) Start() {

	// 将会话添加到管理器
	self.Peer().(peer.SessionManager).Add(self)

	// 需要接收和发送线程同时完成时才算真正的完成
	self.exitSync.Add(2)

	go func() {

		// 等待2个任务结束
		self.exitSync.Wait()

		// 将会话从管理器移除
		self.Peer().(peer.SessionManager).Remove(self)

		if self.endNotify != nil {
			self.endNotify()
		}

	}()

	// 启动并发接收goroutine
	go self.recvLoop()

	// 启动并发发送goroutine
	go self.sendLoop()
}

func newSession(conn *websocket.Conn, p cellnet.Peer, endNotify func()) *wsSession {
	self := &wsSession{
		conn:       conn,
		endNotify:  endNotify,
		sendQueue:  cellnet.NewPipe(),
		pInterface: p,
		CoreProcBundle: p.(interface {
			GetBundle() *peer.CoreProcBundle
		}).GetBundle(),
	}

	return self
}
<|endoftext|>


<commit_before>/*
Copyright 2018 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Package kind implements the root kind cobra command, and the cli Main()
package kind

import (
	log "github.com/sirupsen/logrus"
	"github.com/spf13/cobra"

	"k8s.io/test-infra/kind/cmd/kind/build"
	"k8s.io/test-infra/kind/cmd/kind/create"
	"k8s.io/test-infra/kind/cmd/kind/delete"
)

// NewCommand returns a new cobra.Command implementing the root command for kind
func NewCommand() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "kind",
		Short: "kind is a tool for managing local multi-node Kubernetes clusters",
		Long:  "kind creates and manages local multi-node Kubernetes clusters using Docker containers",
	}
	// add all top level subcommands
	cmd.AddCommand(build.NewCommand())
	cmd.AddCommand(create.NewCommand())
	cmd.AddCommand(delete.NewCommand())
	return cmd
}

// Run runs the `kind` root command
func Run() error {
	return NewCommand().Execute()
}

// Main wraps Run, adding a log.Fatal(err) on error, and setting the log formatter
func Main() {
	// this formatter is the default, but the timestamps output aren't
	// particularly useful, they're relative to the command start
	log.SetFormatter(&log.TextFormatter{
		FullTimestamp:   true,
		TimestampFormat: "15:04:05-0700",
	})
	if err := Run(); err != nil {
		log.Fatal(err)
	}
}
<commit_msg>tweak log timestamps<commit_after>/*
Copyright 2018 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Package kind implements the root kind cobra command, and the cli Main()
package kind

import (
	log "github.com/sirupsen/logrus"
	"github.com/spf13/cobra"

	"k8s.io/test-infra/kind/cmd/kind/build"
	"k8s.io/test-infra/kind/cmd/kind/create"
	"k8s.io/test-infra/kind/cmd/kind/delete"
)

// NewCommand returns a new cobra.Command implementing the root command for kind
func NewCommand() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "kind",
		Short: "kind is a tool for managing local multi-node Kubernetes clusters",
		Long:  "kind creates and manages local multi-node Kubernetes clusters using Docker containers",
	}
	// add all top level subcommands
	cmd.AddCommand(build.NewCommand())
	cmd.AddCommand(create.NewCommand())
	cmd.AddCommand(delete.NewCommand())
	return cmd
}

// Run runs the `kind` root command
func Run() error {
	return NewCommand().Execute()
}

// Main wraps Run, adding a log.Fatal(err) on error, and setting the log formatter
func Main() {
	// this formatter is the default, but the timestamps output aren't
	// particularly useful, they're relative to the command start
	log.SetFormatter(&log.TextFormatter{
		FullTimestamp:   true,
		TimestampFormat: "0102-15:04:05",
	})
	if err := Run(); err != nil {
		log.Fatal(err)
	}
}
<|endoftext|>


<commit_before>package aws

import (
	"fmt"
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/efs"
	"testing"

	"github.com/hashicorp/terraform-plugin-sdk/helper/acctest"
	"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
	"github.com/hashicorp/terraform-plugin-sdk/terraform"
)

func TestAccAWSEFSFileSystemPolicy_basic(t *testing.T) {
	var desc efs.DescribeFileSystemPolicyOutput
	resourceName := "aws_efs_file_system_policy.test"
	rName := acctest.RandomWithPrefix("tf-acc-test")

	resource.ParallelTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckEfsFileSystemDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccAWSEFSFileSystemPolicyConfig(rName),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckEfsFileSystemPolicy(resourceName, &desc),
					resource.TestCheckResourceAttrSet(resourceName, "policy"),
				),
			},
			{
				ResourceName:      resourceName,
				ImportState:       true,
				ImportStateVerify: true,
			},
		},
	})
}

func TestAccAWSEFSFileSystemPolicy_disappears(t *testing.T) {
	var desc efs.DescribeFileSystemPolicyOutput
	resourceName := "aws_efs_file_system_policy.test"
	rName := acctest.RandomWithPrefix("tf-acc-test")

	resource.ParallelTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckEfsFileSystemPolicyDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccAWSEFSFileSystemPolicyConfig(rName),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckEfsFileSystemPolicy(resourceName, &desc),
					testAccCheckResourceDisappears(testAccProvider, resourceAwsEfsFileSystemPolicy(), resourceName),
				),
				ExpectNonEmptyPlan: true,
			},
		},
	})
}

func testAccCheckEfsFileSystemPolicyDestroy(s *terraform.State) error {
	conn := testAccProvider.Meta().(*AWSClient).efsconn
	for _, rs := range s.RootModule().Resources {
		if rs.Type != "aws_efs_file_system_policy" {
			continue
		}

		resp, err := conn.DescribeFileSystemPolicy(&efs.DescribeFileSystemPolicyInput{
			FileSystemId: aws.String(rs.Primary.ID),
		})
		if err != nil {
			if isAWSErr(err, efs.ErrCodeFileSystemNotFound, "") ||
				isAWSErr(err, efs.ErrCodePolicyNotFound, "") {
				return nil
			}
			return fmt.Errorf("error describing EFS file system policy in tests: %s", err)
		}
		if resp != nil {
			return fmt.Errorf("EFS file system policy %q still exists", rs.Primary.ID)
		}
	}

	return nil
}

func testAccCheckEfsFileSystemPolicy(resourceID string, efsFsPolicy *efs.DescribeFileSystemPolicyOutput) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		rs, ok := s.RootModule().Resources[resourceID]
		if !ok {
			return fmt.Errorf("Not found: %s", resourceID)
		}

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

		conn := testAccProvider.Meta().(*AWSClient).efsconn
		fs, err := conn.DescribeFileSystemPolicy(&efs.DescribeFileSystemPolicyInput{
			FileSystemId: aws.String(rs.Primary.ID),
		})

		if err != nil {
			return err
		}

		*efsFsPolicy = *fs

		return nil
	}
}

func testAccAWSEFSFileSystemPolicyConfig(rName string) string {
	return fmt.Sprintf(`
resource "aws_efs_file_system" "test" {
	creation_token = %q
}

resource "aws_efs_file_system_policy" "test" {
  file_system_id = "${aws_efs_file_system.test.id}"

  policy = <<POLICY
{
    "Version": "2012-10-17",
    "Id": "ExamplePolicy01",
    "Statement": [
        {
            "Sid": "ExampleSatement01",
            "Effect": "Allow",
            "Principal": {
                "AWS": "*"
            },
            "Resource": "${aws_efs_file_system.test.arn}",
            "Action": [
                "elasticfilesystem:ClientMount",
                "elasticfilesystem:ClientWrite"
            ],
            "Condition": {
                "Bool": {
                    "aws:SecureTransport": "true"
                }
            }
        }
    ]
}
POLICY
}
`, rName)
}
<commit_msg>add update case<commit_after>package aws

import (
	"fmt"
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/efs"
	"testing"

	"github.com/hashicorp/terraform-plugin-sdk/helper/acctest"
	"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
	"github.com/hashicorp/terraform-plugin-sdk/terraform"
)

func TestAccAWSEFSFileSystemPolicy_basic(t *testing.T) {
	var desc efs.DescribeFileSystemPolicyOutput
	resourceName := "aws_efs_file_system_policy.test"
	rName := acctest.RandomWithPrefix("tf-acc-test")

	resource.ParallelTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckEfsFileSystemDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccAWSEFSFileSystemPolicyConfig(rName),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckEfsFileSystemPolicy(resourceName, &desc),
					resource.TestCheckResourceAttrSet(resourceName, "policy"),
				),
			},
			{
				ResourceName:      resourceName,
				ImportState:       true,
				ImportStateVerify: true,
			},
			{
				Config: testAccAWSEFSFileSystemPolicyConfigUpdated(rName),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckEfsFileSystemPolicy(resourceName, &desc),
					resource.TestCheckResourceAttrSet(resourceName, "policy"),
				),
			},
		},
	})
}

func TestAccAWSEFSFileSystemPolicy_disappears(t *testing.T) {
	var desc efs.DescribeFileSystemPolicyOutput
	resourceName := "aws_efs_file_system_policy.test"
	rName := acctest.RandomWithPrefix("tf-acc-test")

	resource.ParallelTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckEfsFileSystemPolicyDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccAWSEFSFileSystemPolicyConfig(rName),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckEfsFileSystemPolicy(resourceName, &desc),
					testAccCheckResourceDisappears(testAccProvider, resourceAwsEfsFileSystemPolicy(), resourceName),
				),
				ExpectNonEmptyPlan: true,
			},
		},
	})
}

func testAccCheckEfsFileSystemPolicyDestroy(s *terraform.State) error {
	conn := testAccProvider.Meta().(*AWSClient).efsconn
	for _, rs := range s.RootModule().Resources {
		if rs.Type != "aws_efs_file_system_policy" {
			continue
		}

		resp, err := conn.DescribeFileSystemPolicy(&efs.DescribeFileSystemPolicyInput{
			FileSystemId: aws.String(rs.Primary.ID),
		})
		if err != nil {
			if isAWSErr(err, efs.ErrCodeFileSystemNotFound, "") ||
				isAWSErr(err, efs.ErrCodePolicyNotFound, "") {
				return nil
			}
			return fmt.Errorf("error describing EFS file system policy in tests: %s", err)
		}
		if resp != nil {
			return fmt.Errorf("EFS file system policy %q still exists", rs.Primary.ID)
		}
	}

	return nil
}

func testAccCheckEfsFileSystemPolicy(resourceID string, efsFsPolicy *efs.DescribeFileSystemPolicyOutput) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		rs, ok := s.RootModule().Resources[resourceID]
		if !ok {
			return fmt.Errorf("Not found: %s", resourceID)
		}

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

		conn := testAccProvider.Meta().(*AWSClient).efsconn
		fs, err := conn.DescribeFileSystemPolicy(&efs.DescribeFileSystemPolicyInput{
			FileSystemId: aws.String(rs.Primary.ID),
		})

		if err != nil {
			return err
		}

		*efsFsPolicy = *fs

		return nil
	}
}

func testAccAWSEFSFileSystemPolicyConfig(rName string) string {
	return fmt.Sprintf(`
resource "aws_efs_file_system" "test" {
	creation_token = %q
}

resource "aws_efs_file_system_policy" "test" {
  file_system_id = "${aws_efs_file_system.test.id}"

  policy = <<POLICY
{
    "Version": "2012-10-17",
    "Id": "ExamplePolicy01",
    "Statement": [
        {
            "Sid": "ExampleSatement01",
            "Effect": "Allow",
            "Principal": {
                "AWS": "*"
            },
            "Resource": "${aws_efs_file_system.test.arn}",
            "Action": [
                "elasticfilesystem:ClientMount",
                "elasticfilesystem:ClientWrite"
            ],
            "Condition": {
                "Bool": {
                    "aws:SecureTransport": "true"
                }
            }
        }
    ]
}
POLICY
}
`, rName)
}

func testAccAWSEFSFileSystemPolicyConfigUpdated(rName string) string {
	return fmt.Sprintf(`
resource "aws_efs_file_system" "test" {
	creation_token = %q
}

resource "aws_efs_file_system_policy" "test" {
  file_system_id = "${aws_efs_file_system.test.id}"

  policy = <<POLICY
{
    "Version": "2012-10-17",
    "Id": "ExamplePolicy01",
    "Statement": [
        {
            "Sid": "ExampleSatement01",
            "Effect": "Allow",
            "Principal": {
                "AWS": "*"
            },
            "Resource": "${aws_efs_file_system.test.arn}",
            "Action": "elasticfilesystem:ClientMount",
            "Condition": {
                "Bool": {
                    "aws:SecureTransport": "true"
                }
            }
        }
    ]
}
POLICY
}
`, rName)
}
<|endoftext|>


<commit_before>/*
 * Copyright ©1998-2022 by Richard A. Wilkes. All rights reserved.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, version 2.0. If a copy of the MPL was not distributed with
 * this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This Source Code Form is "Incompatible With Secondary Licenses", as
 * defined by the Mozilla Public License, version 2.0.
 */

package ui

import (
	"bytes"
	"encoding/binary"
	"net"
	"time"

	"github.com/richardwilkes/json"
	"github.com/richardwilkes/toolbox/atexit"
	"github.com/richardwilkes/toolbox/cmdline"
	"github.com/richardwilkes/toolbox/errs"
	"github.com/richardwilkes/toolbox/log/jot"
	"github.com/richardwilkes/toolbox/xio"
)

func startHandoffService(pathsChan chan<- []string, paths []string) {
	const address = "127.0.0.1:13321"
	var pathsBuffer []byte
	now := time.Now()
	for time.Since(now) < 10*time.Second {
		// First, try to establish our port and become the primary GCS instance
		if listener, err := net.Listen("tcp4", address); err == nil {
			go acceptHandoff(listener, pathsChan)
			return
		}
		if pathsBuffer == nil {
			var err error
			if pathsBuffer, err = json.Marshal(paths); err != nil {
				jot.Fatal(1, errs.Wrap(err))
			}
		}
		// Port is in use, try connecting as a client and handing off our file list
		if conn, err := net.DialTimeout("tcp4", address, time.Second); err == nil && handoff(conn, pathsBuffer) {
			atexit.Exit(0)
		}
		// Client can't reach the server, loop around and start the processHandoff again
	}
}

func handoff(conn net.Conn, pathsBuffer []byte) bool {
	defer xio.CloseIgnoringErrors(conn)
	buffer := make([]byte, len(cmdline.AppIdentifier))
	if n, err := conn.Read(buffer); err != nil || n != len(buffer) || !bytes.Equal(buffer, []byte(cmdline.AppIdentifier)) {
		return false
	}
	buffer = make([]byte, 5)
	buffer[0] = 22
	binary.LittleEndian.PutUint32(buffer[1:], uint32(len(pathsBuffer)))
	if n, err := conn.Write(buffer); err != nil || n != len(buffer) {
		return false
	}
	if n, err := conn.Write(pathsBuffer); err != nil || n != len(pathsBuffer) {
		return false
	}
	return true
}

func acceptHandoff(listener net.Listener, pathsChan chan<- []string) {
	for {
		conn, err := listener.Accept()
		if err != nil {
			break
		}
		go processHandoff(conn, pathsChan)
	}
}

func processHandoff(conn net.Conn, pathsChan chan<- []string) {
	defer xio.CloseIgnoringErrors(conn)
	if _, err := conn.Write([]byte(cmdline.AppIdentifier)); err != nil {
		return
	}
	var single [1]byte
	n, err := conn.Read(single[:])
	if err != nil {
		return
	}
	if n != 1 {
		return
	}
	if single[0] != 22 {
		return
	}
	var sizeBuffer [4]byte
	if n, err = conn.Read(sizeBuffer[:]); err != nil {
		return
	}
	if n != 4 {
		return
	}
	size := int(binary.LittleEndian.Uint32(sizeBuffer[:]))
	buffer := make([]byte, size)
	if n, err = conn.Read(buffer[:]); err != nil {
		return
	}
	if n != size {
		return
	}
	var paths []string
	if err = json.Unmarshal(buffer, &paths); err != nil {
		return
	}
	pathsChan <- paths
}
<commit_msg>Change handoff port so that old versions won't try to capture it<commit_after>/*
 * Copyright ©1998-2022 by Richard A. Wilkes. All rights reserved.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, version 2.0. If a copy of the MPL was not distributed with
 * this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This Source Code Form is "Incompatible With Secondary Licenses", as
 * defined by the Mozilla Public License, version 2.0.
 */

package ui

import (
	"bytes"
	"encoding/binary"
	"net"
	"time"

	"github.com/richardwilkes/json"
	"github.com/richardwilkes/toolbox/atexit"
	"github.com/richardwilkes/toolbox/cmdline"
	"github.com/richardwilkes/toolbox/errs"
	"github.com/richardwilkes/toolbox/log/jot"
	"github.com/richardwilkes/toolbox/xio"
)

func startHandoffService(pathsChan chan<- []string, paths []string) {
	const address = "127.0.0.1:13322"
	var pathsBuffer []byte
	now := time.Now()
	for time.Since(now) < 10*time.Second {
		// First, try to establish our port and become the primary GCS instance
		if listener, err := net.Listen("tcp4", address); err == nil {
			go acceptHandoff(listener, pathsChan)
			return
		}
		if pathsBuffer == nil {
			var err error
			if pathsBuffer, err = json.Marshal(paths); err != nil {
				jot.Fatal(1, errs.Wrap(err))
			}
		}
		// Port is in use, try connecting as a client and handing off our file list
		if conn, err := net.DialTimeout("tcp4", address, time.Second); err == nil && handoff(conn, pathsBuffer) {
			atexit.Exit(0)
		}
		// Client can't reach the server, loop around and start the processHandoff again
	}
}

func handoff(conn net.Conn, pathsBuffer []byte) bool {
	defer xio.CloseIgnoringErrors(conn)
	buffer := make([]byte, len(cmdline.AppIdentifier))
	if n, err := conn.Read(buffer); err != nil || n != len(buffer) || !bytes.Equal(buffer, []byte(cmdline.AppIdentifier)) {
		return false
	}
	buffer = make([]byte, 5)
	buffer[0] = 22
	binary.LittleEndian.PutUint32(buffer[1:], uint32(len(pathsBuffer)))
	if n, err := conn.Write(buffer); err != nil || n != len(buffer) {
		return false
	}
	if n, err := conn.Write(pathsBuffer); err != nil || n != len(pathsBuffer) {
		return false
	}
	return true
}

func acceptHandoff(listener net.Listener, pathsChan chan<- []string) {
	for {
		conn, err := listener.Accept()
		if err != nil {
			break
		}
		go processHandoff(conn, pathsChan)
	}
}

func processHandoff(conn net.Conn, pathsChan chan<- []string) {
	defer xio.CloseIgnoringErrors(conn)
	if _, err := conn.Write([]byte(cmdline.AppIdentifier)); err != nil {
		return
	}
	var single [1]byte
	n, err := conn.Read(single[:])
	if err != nil {
		return
	}
	if n != 1 {
		return
	}
	if single[0] != 22 {
		return
	}
	var sizeBuffer [4]byte
	if n, err = conn.Read(sizeBuffer[:]); err != nil {
		return
	}
	if n != 4 {
		return
	}
	size := int(binary.LittleEndian.Uint32(sizeBuffer[:]))
	buffer := make([]byte, size)
	if n, err = conn.Read(buffer[:]); err != nil {
		return
	}
	if n != size {
		return
	}
	var paths []string
	if err = json.Unmarshal(buffer, &paths); err != nil {
		return
	}
	pathsChan <- paths
}
<|endoftext|>


<commit_before>package dns

import (
	"io"
	"testing"

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

func TestUnpackLabel(t *testing.T) {
	cases := []struct {
		Input     string
		Expected  string
		Offset    int
		IsPointer bool
		Err       error
	}{
		{Input: "\x00", Err: ErrLabelEmpty},
		{Input: "\x40", Err: ErrLabelTooLong},
		{Input: "\x01", Err: io.ErrShortBuffer},
		{Input: "\x3f", Err: io.ErrShortBuffer},

		{Input: "\x01.", Err: ErrLabelInvalid},
		{Input: "\x02..", Err: ErrLabelInvalid},
		{Input: "\x07.00000A", Err: ErrLabelInvalid},

		{Input: "\x02ok", Expected: "ok"},
		{Input: "\x03123", Expected: "123"},
		{Input: "\x0asome.email", Expected: "some.email"},

		// Pointer tests
		{Input: "\xc0\x02", Err: ErrLabelPointerIllegal, IsPointer: true},
		{Input: "\x01\xc0\x00", Offset: 1, Err: ErrLabelPointerIllegal, IsPointer: true},
		{Input: "\x00\x00\xc0\x00", Offset: 2, Err: ErrLabelEmpty, IsPointer: true},
		{Input: "\x06domain\xc0\x00", Expected: "domain", Offset: 7, IsPointer: true},
	}

	for _, c := range cases {
		t.Logf("Label unpacking input: %q\n", c.Input)

		var label string
		var n int
		var err error

		b := []byte(c.Input)
		if c.IsPointer {
			label, n, err = unpackLabelPointer(b, c.Offset)
		} else {
			label, n, err = unpackLabel(b, c.Offset)
		}

		assert.Equal(t, c.Err, err)
		if err == nil {
			if c.IsPointer {
				assert.Equal(t, 2, n)
			} else {
				assert.Equal(t, len(c.Input), n)
			}
		}
		assert.Equal(t, c.Expected, label)
	}
}
<commit_msg>(wip) add a test for invalid label and pointer<commit_after>package dns

import (
	"io"
	"testing"

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

func TestUnpackLabel(t *testing.T) {
	cases := []struct {
		Input     string
		Expected  string
		Offset    int
		IsPointer bool
		Err       error
	}{
		{Input: "\x00", Err: ErrLabelEmpty},
		{Input: "\x40", Err: ErrLabelTooLong},
		{Input: "\x01", Err: io.ErrShortBuffer},
		{Input: "\x3f", Err: io.ErrShortBuffer},

		{Input: "\x01.", Err: ErrLabelInvalid},
		{Input: "\x02..", Err: ErrLabelInvalid},
		{Input: "\x07.00000A", Err: ErrLabelInvalid},

		{Input: "\x02ok", Expected: "ok"},
		{Input: "\x03123", Expected: "123"},
		{Input: "\x0asome.email", Expected: "some.email"},

		// Pointer tests
		{Input: "\xc0\x02", Err: ErrLabelPointerIllegal, IsPointer: true},
		{Input: "\x01\xc0\x00", Offset: 1, Err: ErrLabelPointerIllegal, IsPointer: true},
		{Input: "\x01\xc0\xc0\x00", Offset: 2, Err: ErrLabelInvalid, IsPointer: true},
		{Input: "\x00\x00\xc0\x00", Offset: 2, Err: ErrLabelEmpty, IsPointer: true},
		{Input: "\x06domain\xc0\x00", Expected: "domain", Offset: 7, IsPointer: true},
	}

	for _, c := range cases {
		t.Logf("Label unpacking input: %q\n", c.Input)

		var label string
		var n int
		var err error

		b := []byte(c.Input)
		if c.IsPointer {
			label, n, err = unpackLabelPointer(b, c.Offset)
		} else {
			label, n, err = unpackLabel(b, c.Offset)
		}

		assert.Equal(t, c.Err, err)
		if err == nil {
			if c.IsPointer {
				assert.Equal(t, 2, n)
			} else {
				assert.Equal(t, len(c.Input), n)
			}
		}
		assert.Equal(t, c.Expected, label)
	}
}
<|endoftext|>