<commit_before>package main

import (
	"fmt"
	"log"
	"time"

	"github.com/dvrkps/dojo/etcdconfig/myconfig"
)

func main() {
	var (
		endpoints = []string{":2379"}
	)

	cfg, err := myconfig.New(
		myconfig.Config{
			Endpoints: endpoints,
			Env:       "test",
			Service:   "app",
		},
	)
	if err != nil {
		log.Fatal(err)
	}

	global(cfg)

	defer myconfig.Close(cfg)

}

func global(c *myconfig.Client) {
	var (
		b bool
		i int
		s string
	)

	for {
		time.Sleep(1e9)
		nb, _ := c.Bool("/global/istest")
		ni, _ := c.Int("/global/port")
		ns, _ := c.String("/global/words")
		if b != nb || i != ni || s != ns {
			b = nb
			i = ni
			s = ns
			fmt.Printf("global: istest: %v port: %v words: %q \n", b, i, s)
		}

	}
}
<commit_msg>etcdconfig: add service func<commit_after>package main

import (
	"fmt"
	"log"
	"time"

	"github.com/dvrkps/dojo/etcdconfig/myconfig"
)

func main() {
	var (
		endpoints = []string{":2379"}
	)

	cfg, err := myconfig.New(
		myconfig.Config{
			Endpoints: endpoints,
			Env:       "test",
			Service:   "app",
		},
	)
	if err != nil {
		log.Fatal(err)
	}

	go global(cfg)

	service(cfg)

	defer myconfig.Close(cfg)

}

func global(c *myconfig.Client) {
	var (
		b bool
		i int
		s string
	)

	for {
		time.Sleep(1e9)
		nb, _ := c.Bool("/global/istest")
		ni, _ := c.Int("/global/port")
		ns, _ := c.String("/global/words")
		if b != nb || i != ni || s != ns {
			b = nb
			i = ni
			s = ns
			fmt.Printf("global: istest: %v port: %v words: %q \n", b, i, s)
		}

	}
}

func service(c *myconfig.Client) {
	var (
		b bool
		i int
		s string
	)

	for {
		time.Sleep(1e9)
		nb, _ := c.Bool("/secret")
		ni, _ := c.Int("/devil")
		ns, _ := c.String("/server")
		if b != nb || i != ni || s != ns {
			b = nb
			i = ni
			s = ns
			fmt.Printf("service: secret: %v devil: %v server: %q \n", b, i, s)
		}

	}
}
<|endoftext|>


<commit_before>package ethui

import (
	"bytes"
	"fmt"
	"github.com/ethereum/eth-go"
	"github.com/ethereum/eth-go/ethchain"
	"github.com/ethereum/eth-go/ethdb"
	"github.com/ethereum/eth-go/ethpub"
	"github.com/ethereum/eth-go/ethutil"
	"github.com/go-qml/qml"
	"github.com/obscuren/mutan"
	"math/big"
	"strings"
)

type Gui struct {
	// The main application window
	win *qml.Window
	// QML Engine
	engine    *qml.Engine
	component *qml.Common
	// The ethereum interface
	eth *eth.Ethereum

	// The public Ethereum library
	lib   *EthLib
	uiLib *UiLib

	txDb *ethdb.LDBDatabase

	addr []byte

	pub *ethpub.PEthereum
}

// Create GUI, but doesn't start it
func New(ethereum *eth.Ethereum) *Gui {
	lib := &EthLib{stateManager: ethereum.StateManager(), blockChain: ethereum.BlockChain(), txPool: ethereum.TxPool()}
	db, err := ethdb.NewLDBDatabase("tx_database")
	if err != nil {
		panic(err)
	}

	// On first run we won't have any keys yet, so this would crash.
	// Therefor we check if we are ready to actually start this process
	var addr []byte
	if ethutil.GetKeyRing().Len() != 0 {
		addr = ethutil.GetKeyRing().Get(0).Address()
	}

	pub := ethpub.NewPEthereum(ethereum)

	return &Gui{eth: ethereum, lib: lib, txDb: db, addr: addr, pub: pub}
}

func (gui *Gui) Start(assetPath string) {
	const version = "0.5.0 RC7"

	defer gui.txDb.Close()

	// Register ethereum functions
	qml.RegisterTypes("Ethereum", 1, 0, []qml.TypeSpec{{
		Init: func(p *ethpub.PBlock, obj qml.Object) { p.Number = 0; p.Hash = "" },
	}, {
		Init: func(p *ethpub.PTx, obj qml.Object) { p.Value = ""; p.Hash = ""; p.Address = "" },
	}})

	ethutil.Config.SetClientString(fmt.Sprintf("/Ethereal v%s", version))
	ethutil.Config.Log.Infoln("[GUI] Starting GUI")
	// Create a new QML engine
	gui.engine = qml.NewEngine()
	context := gui.engine.Context()

	// Expose the eth library and the ui library to QML
	context.SetVar("eth", gui)
	gui.uiLib = NewUiLib(gui.engine, gui.eth, assetPath)
	context.SetVar("ui", gui.uiLib)

	// Load the main QML interface
	data, _ := ethutil.Config.Db.Get([]byte("KeyRing"))

	var win *qml.Window
	var err error
	if len(data) == 0 {
		win, err = gui.showKeyImport(context)
	} else {
		win, err = gui.showWallet(context)
	}
	if err != nil {
		ethutil.Config.Log.Infoln("FATAL: asset not found: you can set an alternative asset path on on the command line using option 'asset_path'")

		panic(err)
	}

	win.Show()
	win.Wait()

	gui.eth.Stop()
}

func (gui *Gui) showWallet(context *qml.Context) (*qml.Window, error) {
	component, err := gui.engine.LoadFile(gui.uiLib.AssetPath("qml/wallet.qml"))
	if err != nil {
		return nil, err
	}

	win := gui.createWindow(component)

	go gui.setInitialBlockChain()
	go gui.readPreviousTransactions()
	go gui.update()

	return win, nil
}

func (gui *Gui) showKeyImport(context *qml.Context) (*qml.Window, error) {
	context.SetVar("lib", gui.lib)
	component, err := gui.engine.LoadFile(gui.uiLib.AssetPath("qml/first_run.qml"))
	if err != nil {
		return nil, err
	}

	return gui.createWindow(component), nil
}

func (gui *Gui) createWindow(comp qml.Object) *qml.Window {
	win := comp.CreateWindow(nil)

	gui.win = win
	gui.uiLib.win = win

	db := &Debugger{gui.win, make(chan bool)}
	gui.lib.Db = db
	gui.uiLib.Db = db

	return gui.win
}

func (gui *Gui) setInitialBlockChain() {
	// Load previous 10 blocks
	chain := gui.eth.BlockChain().GetChain(gui.eth.BlockChain().CurrentBlock.Hash(), 10)
	for _, block := range chain {
		gui.processBlock(block)
	}

}

func (gui *Gui) readPreviousTransactions() {
	it := gui.txDb.Db().NewIterator(nil, nil)
	for it.Next() {
		tx := ethchain.NewTransactionFromBytes(it.Value())

		gui.win.Root().Call("addTx", ethpub.NewPTx(tx))
	}
	it.Release()
}

func (gui *Gui) processBlock(block *ethchain.Block) {
	gui.win.Root().Call("addBlock", ethpub.NewPBlock(block))
}

func (gui *Gui) setWalletValue(amount, unconfirmedFunds *big.Int) {
	var str string
	if unconfirmedFunds != nil {
		pos := "+"
		if unconfirmedFunds.Cmp(big.NewInt(0)) >= 0 {
			pos = "-"
		}
		val := ethutil.CurrencyToString(new(big.Int).Abs(ethutil.BigCopy(unconfirmedFunds)))
		str = fmt.Sprintf("%v (%s %v)", ethutil.CurrencyToString(amount), pos, val)
	} else {
		str = fmt.Sprintf("%v", ethutil.CurrencyToString(amount))
	}

	gui.win.Root().Call("setWalletValue", str)
}

// Simple go routine function that updates the list of peers in the GUI
func (gui *Gui) update() {
	reactor := gui.eth.Reactor()

	blockChan := make(chan ethutil.React, 1)
	txChan := make(chan ethutil.React, 1)

	reactor.Subscribe("newBlock", blockChan)
	reactor.Subscribe("newTx:pre", txChan)
	reactor.Subscribe("newTx:post", txChan)

	state := gui.eth.StateManager().TransState()

	unconfirmedFunds := new(big.Int)
	gui.win.Root().Call("setWalletValue", fmt.Sprintf("%v", ethutil.CurrencyToString(state.GetAccount(gui.addr).Amount)))

	for {
		select {
		case b := <-blockChan:
			block := b.Resource.(*ethchain.Block)
			if bytes.Compare(block.Coinbase, gui.addr) == 0 {
				gui.setWalletValue(gui.eth.StateManager().CurrentState().GetAccount(gui.addr).Amount, nil)
			}

		case txMsg := <-txChan:
			tx := txMsg.Resource.(*ethchain.Transaction)

			if txMsg.Event == "newTx:pre" {
				object := state.GetAccount(gui.addr)

				if bytes.Compare(tx.Sender(), gui.addr) == 0 && object.Nonce <= tx.Nonce {
					gui.win.Root().Call("addTx", ethpub.NewPTx(tx))
					gui.txDb.Put(tx.Hash(), tx.RlpEncode())

					/*
						object.Nonce += 1
						state.SetStateObject(object)
					*/

					unconfirmedFunds.Sub(unconfirmedFunds, tx.Value)
				} else if bytes.Compare(tx.Recipient, gui.addr) == 0 {
					gui.win.Root().Call("addTx", ethpub.NewPTx(tx))
					gui.txDb.Put(tx.Hash(), tx.RlpEncode())

					unconfirmedFunds.Add(unconfirmedFunds, tx.Value)
				}

				gui.setWalletValue(object.Amount, unconfirmedFunds)
			} else {
				object := state.GetAccount(gui.addr)
				if bytes.Compare(tx.Sender(), gui.addr) == 0 {
					object.SubAmount(tx.Value)
				} else if bytes.Compare(tx.Recipient, gui.addr) == 0 {
					object.AddAmount(tx.Value)
				}

				gui.setWalletValue(object.Amount, nil)

				state.UpdateStateObject(object)
			}
		}
	}
}

// Logging functions that log directly to the GUI interface
func (gui *Gui) Println(v ...interface{}) {
	str := strings.TrimRight(fmt.Sprintln(v...), "\n")
	lines := strings.Split(str, "\n")
	for _, line := range lines {
		gui.win.Root().Call("addLog", line)
	}
}

func (gui *Gui) Printf(format string, v ...interface{}) {
	str := strings.TrimRight(fmt.Sprintf(format, v...), "\n")
	lines := strings.Split(str, "\n")
	for _, line := range lines {
		gui.win.Root().Call("addLog", line)
	}
}

func (gui *Gui) Transact(recipient, value, gas, gasPrice, data string) (*ethpub.PReceipt, error) {
	keyPair := ethutil.GetKeyRing().Get(0)

	return gui.pub.Transact(ethutil.Hex(keyPair.PrivateKey), recipient, value, gas, gasPrice, data)
}

func (gui *Gui) Create(recipient, value, gas, gasPrice, data string) (*ethpub.PReceipt, error) {
	keyPair := ethutil.GetKeyRing().Get(0)

	mainInput, initInput := mutan.PreParse(data)

	return gui.pub.Create(ethutil.Hex(keyPair.PrivateKey), value, gas, gasPrice, initInput, mainInput)
}
<commit_msg>Fixed unconfirmed balance string<commit_after>package ethui

import (
	"bytes"
	"fmt"
	"github.com/ethereum/eth-go"
	"github.com/ethereum/eth-go/ethchain"
	"github.com/ethereum/eth-go/ethdb"
	"github.com/ethereum/eth-go/ethpub"
	"github.com/ethereum/eth-go/ethutil"
	"github.com/go-qml/qml"
	"github.com/obscuren/mutan"
	"math/big"
	"strings"
)

type Gui struct {
	// The main application window
	win *qml.Window
	// QML Engine
	engine    *qml.Engine
	component *qml.Common
	// The ethereum interface
	eth *eth.Ethereum

	// The public Ethereum library
	lib   *EthLib
	uiLib *UiLib

	txDb *ethdb.LDBDatabase

	addr []byte

	pub *ethpub.PEthereum
}

// Create GUI, but doesn't start it
func New(ethereum *eth.Ethereum) *Gui {
	lib := &EthLib{stateManager: ethereum.StateManager(), blockChain: ethereum.BlockChain(), txPool: ethereum.TxPool()}
	db, err := ethdb.NewLDBDatabase("tx_database")
	if err != nil {
		panic(err)
	}

	// On first run we won't have any keys yet, so this would crash.
	// Therefor we check if we are ready to actually start this process
	var addr []byte
	if ethutil.GetKeyRing().Len() != 0 {
		addr = ethutil.GetKeyRing().Get(0).Address()
	}

	pub := ethpub.NewPEthereum(ethereum)

	return &Gui{eth: ethereum, lib: lib, txDb: db, addr: addr, pub: pub}
}

func (gui *Gui) Start(assetPath string) {
	const version = "0.5.0 RC7"

	defer gui.txDb.Close()

	// Register ethereum functions
	qml.RegisterTypes("Ethereum", 1, 0, []qml.TypeSpec{{
		Init: func(p *ethpub.PBlock, obj qml.Object) { p.Number = 0; p.Hash = "" },
	}, {
		Init: func(p *ethpub.PTx, obj qml.Object) { p.Value = ""; p.Hash = ""; p.Address = "" },
	}})

	ethutil.Config.SetClientString(fmt.Sprintf("/Ethereal v%s", version))
	ethutil.Config.Log.Infoln("[GUI] Starting GUI")
	// Create a new QML engine
	gui.engine = qml.NewEngine()
	context := gui.engine.Context()

	// Expose the eth library and the ui library to QML
	context.SetVar("eth", gui)
	gui.uiLib = NewUiLib(gui.engine, gui.eth, assetPath)
	context.SetVar("ui", gui.uiLib)

	// Load the main QML interface
	data, _ := ethutil.Config.Db.Get([]byte("KeyRing"))

	var win *qml.Window
	var err error
	if len(data) == 0 {
		win, err = gui.showKeyImport(context)
	} else {
		win, err = gui.showWallet(context)
	}
	if err != nil {
		ethutil.Config.Log.Infoln("FATAL: asset not found: you can set an alternative asset path on on the command line using option 'asset_path'")

		panic(err)
	}

	win.Show()
	win.Wait()

	gui.eth.Stop()
}

func (gui *Gui) showWallet(context *qml.Context) (*qml.Window, error) {
	component, err := gui.engine.LoadFile(gui.uiLib.AssetPath("qml/wallet.qml"))
	if err != nil {
		return nil, err
	}

	win := gui.createWindow(component)

	go gui.setInitialBlockChain()
	go gui.readPreviousTransactions()
	go gui.update()

	return win, nil
}

func (gui *Gui) showKeyImport(context *qml.Context) (*qml.Window, error) {
	context.SetVar("lib", gui.lib)
	component, err := gui.engine.LoadFile(gui.uiLib.AssetPath("qml/first_run.qml"))
	if err != nil {
		return nil, err
	}

	return gui.createWindow(component), nil
}

func (gui *Gui) createWindow(comp qml.Object) *qml.Window {
	win := comp.CreateWindow(nil)

	gui.win = win
	gui.uiLib.win = win

	db := &Debugger{gui.win, make(chan bool)}
	gui.lib.Db = db
	gui.uiLib.Db = db

	return gui.win
}

func (gui *Gui) setInitialBlockChain() {
	// Load previous 10 blocks
	chain := gui.eth.BlockChain().GetChain(gui.eth.BlockChain().CurrentBlock.Hash(), 10)
	for _, block := range chain {
		gui.processBlock(block)
	}

}

func (gui *Gui) readPreviousTransactions() {
	it := gui.txDb.Db().NewIterator(nil, nil)
	for it.Next() {
		tx := ethchain.NewTransactionFromBytes(it.Value())

		gui.win.Root().Call("addTx", ethpub.NewPTx(tx))
	}
	it.Release()
}

func (gui *Gui) processBlock(block *ethchain.Block) {
	gui.win.Root().Call("addBlock", ethpub.NewPBlock(block))
}

func (gui *Gui) setWalletValue(amount, unconfirmedFunds *big.Int) {
	var str string
	if unconfirmedFunds != nil {
		pos := "+"
		if unconfirmedFunds.Cmp(big.NewInt(0)) < 0 {
			pos = "-"
		}
		val := ethutil.CurrencyToString(new(big.Int).Abs(ethutil.BigCopy(unconfirmedFunds)))
		str = fmt.Sprintf("%v (%s %v)", ethutil.CurrencyToString(amount), pos, val)
	} else {
		str = fmt.Sprintf("%v", ethutil.CurrencyToString(amount))
	}

	gui.win.Root().Call("setWalletValue", str)
}

// Simple go routine function that updates the list of peers in the GUI
func (gui *Gui) update() {
	reactor := gui.eth.Reactor()

	blockChan := make(chan ethutil.React, 1)
	txChan := make(chan ethutil.React, 1)

	reactor.Subscribe("newBlock", blockChan)
	reactor.Subscribe("newTx:pre", txChan)
	reactor.Subscribe("newTx:post", txChan)

	state := gui.eth.StateManager().TransState()

	unconfirmedFunds := new(big.Int)
	gui.win.Root().Call("setWalletValue", fmt.Sprintf("%v", ethutil.CurrencyToString(state.GetAccount(gui.addr).Amount)))

	for {
		select {
		case b := <-blockChan:
			block := b.Resource.(*ethchain.Block)
			if bytes.Compare(block.Coinbase, gui.addr) == 0 {
				gui.setWalletValue(gui.eth.StateManager().CurrentState().GetAccount(gui.addr).Amount, nil)
			}

		case txMsg := <-txChan:
			tx := txMsg.Resource.(*ethchain.Transaction)

			if txMsg.Event == "newTx:pre" {
				object := state.GetAccount(gui.addr)

				if bytes.Compare(tx.Sender(), gui.addr) == 0 {
					gui.win.Root().Call("addTx", ethpub.NewPTx(tx))
					gui.txDb.Put(tx.Hash(), tx.RlpEncode())

					unconfirmedFunds.Sub(unconfirmedFunds, tx.Value)
				} else if bytes.Compare(tx.Recipient, gui.addr) == 0 {
					gui.win.Root().Call("addTx", ethpub.NewPTx(tx))
					gui.txDb.Put(tx.Hash(), tx.RlpEncode())

					unconfirmedFunds.Add(unconfirmedFunds, tx.Value)
				}

				gui.setWalletValue(object.Amount, unconfirmedFunds)
			} else {
				object := state.GetAccount(gui.addr)
				if bytes.Compare(tx.Sender(), gui.addr) == 0 {
					object.SubAmount(tx.Value)
				} else if bytes.Compare(tx.Recipient, gui.addr) == 0 {
					object.AddAmount(tx.Value)
				}

				gui.setWalletValue(object.Amount, nil)

				state.UpdateStateObject(object)
			}
		}
	}
}

// Logging functions that log directly to the GUI interface
func (gui *Gui) Println(v ...interface{}) {
	str := strings.TrimRight(fmt.Sprintln(v...), "\n")
	lines := strings.Split(str, "\n")
	for _, line := range lines {
		gui.win.Root().Call("addLog", line)
	}
}

func (gui *Gui) Printf(format string, v ...interface{}) {
	str := strings.TrimRight(fmt.Sprintf(format, v...), "\n")
	lines := strings.Split(str, "\n")
	for _, line := range lines {
		gui.win.Root().Call("addLog", line)
	}
}

func (gui *Gui) Transact(recipient, value, gas, gasPrice, data string) (*ethpub.PReceipt, error) {
	keyPair := ethutil.GetKeyRing().Get(0)

	return gui.pub.Transact(ethutil.Hex(keyPair.PrivateKey), recipient, value, gas, gasPrice, data)
}

func (gui *Gui) Create(recipient, value, gas, gasPrice, data string) (*ethpub.PReceipt, error) {
	keyPair := ethutil.GetKeyRing().Get(0)

	mainInput, initInput := mutan.PreParse(data)

	return gui.pub.Create(ethutil.Hex(keyPair.PrivateKey), value, gas, gasPrice, initInput, mainInput)
}
<|endoftext|>


<commit_before>// +build !windows

package integration

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"net/http/httputil"
	"os"
	"os/exec"
	"path/filepath"
	"testing"

	"github.com/creack/pty"
	"github.com/sclevine/spec"
	"github.com/stretchr/testify/require"
)

var _ = suite("auth/init", func(t *testing.T, when spec.G, it spec.S) {
	var (
		expect *require.Assertions
		server *httptest.Server
	)

	it.Before(func() {
		expect = require.New(t)

		server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
			w.Header().Add("content-type", "application/json")

			switch req.URL.Path {
			case "/v2/account":
				auth := req.Header.Get("Authorization")

				if auth == "Bearer first-token" || auth == "Bearer second-token" || auth == "Bearer some-magic-token" {
					w.Write([]byte(`{ "account":{}}`))
					return
				}

				w.WriteHeader(http.StatusUnauthorized)
			case "/v2/droplets/1":
				token := req.Header.Get("Authorization")
				if token != "Bearer second-token" {
					w.WriteHeader(http.StatusUnauthorized)
					return
				}

				w.WriteHeader(http.StatusNoContent)
			default:
				dump, err := httputil.DumpRequest(req, true)
				if err != nil {
					t.Fatal("failed to dump request")
				}

				t.Fatalf("received unknown request: %s", dump)
			}
		}))
	})

	when("a custom config is provided", func() {
		it("validates and saves the provided auth token", func() {
			tmpDir, err := ioutil.TempDir("", "")
			expect.NoError(err)

			testConfig := filepath.Join(tmpDir, "test-config.yml")

			cmd := exec.Command(builtBinaryPath,
				"-u", server.URL,
				"--config", testConfig,
				"auth",
				"init",
			)

			ptmx, err := pty.Start(cmd)
			expect.NoError(err)

			go func() {
				ptmx.Write([]byte("some-magic-token\n"))
			}()

			buf := bytes.NewBuffer([]byte{})

			count, _ := io.Copy(buf, ptmx) // yes, ignore error intentionally
			expect.NotZero(count)
			ptmx.Close()

			expect.Contains(buf.String(), "Validating token... OK")

			fileBytes, err := ioutil.ReadFile(testConfig)
			expect.NoError(err)

			expect.Contains(string(fileBytes), "access-token: some-magic-token")
		})
	})

	when("no custom config is provided", func() {
		it("saves the auth token to the default config path", func() {
			cmd := exec.Command(builtBinaryPath,
				"-u", server.URL,
				"auth",
				"init",
			)

			ptmx, err := pty.Start(cmd)
			expect.NoError(err)

			go func() {
				ptmx.Write([]byte("some-magic-token\n"))
			}()

			buf := bytes.NewBuffer([]byte{})

			count, _ := io.Copy(buf, ptmx) // yes, ignore error intentionally
			expect.NotZero(count)
			ptmx.Close()

			expect.Contains(buf.String(), "Validating token... OK")

			location, err := getDefaultConfigLocation()
			expect.NoError(err)

			fileBytes, err := ioutil.ReadFile(location)
			expect.NoError(err)

			expect.Contains(string(fileBytes), "access-token: some-magic-token")

			err = os.Remove(location)
			expect.NoError(err)
		})
	})

	when("a token cannot be validated", func() {
		it("exits non-zero with an error", func() {
			tmpDir, err := ioutil.TempDir("", "")
			expect.NoError(err)

			testConfig := filepath.Join(tmpDir, "test-config.yml")

			cmd := exec.Command(builtBinaryPath,
				"-u", server.URL,
				"--config", testConfig,
				"auth",
				"init",
			)

			ptmx, err := pty.Start(cmd)
			expect.NoError(err)

			go func() {
				ptmx.Write([]byte("some-bad-token\n"))
			}()

			buf := bytes.NewBuffer([]byte{})

			count, _ := io.Copy(buf, ptmx) // yes, ignore error intentionally
			expect.NotZero(count)
			ptmx.Close()

			expect.Contains(buf.String(), "Validating token... invalid token")
			expect.Contains(buf.String(), fmt.Sprintf("unable to use supplied token to access API: GET %s/v2/account: 401", server.URL))
		})
	})

	when("a new auth context is added", func() {
		it("allows you to switch to that context", func() {
			const nextContext = "next"

			var testConfigBytes = []byte(`access-token: first-token
auth-contexts:
  next: second-token
context: default
`)

			tmpDir, err := ioutil.TempDir("", "")
			expect.NoError(err)
			testConfig := filepath.Join(tmpDir, "test-config.yml")
			expect.NoError(ioutil.WriteFile(testConfig, testConfigBytes, 0644))

			cmd := exec.Command(builtBinaryPath,
				"-u", server.URL,
				"auth",
				"switch",
				"--config", testConfig,
				"--context",
				nextContext,
			)
			_, err = cmd.CombinedOutput()
			expect.NoError(err)

			fileBytes, err := ioutil.ReadFile(testConfig)
			expect.NoError(err)
			expect.Contains(string(fileBytes), "context: next")

			cmd = exec.Command(builtBinaryPath,
				"-u", server.URL,
				"--config", testConfig,
				"compute",
				"droplet",
				"delete",
				"1",
				"-f",
			)

			output, err := cmd.CombinedOutput()
			expect.NoError(err, string(output))

			err = os.Remove(testConfig)
			expect.NoError(err)
		})
	})
})
<commit_msg>Fix copy-dependant integration test.<commit_after>// +build !windows

package integration

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"net/http/httputil"
	"os"
	"os/exec"
	"path/filepath"
	"testing"

	"github.com/creack/pty"
	"github.com/sclevine/spec"
	"github.com/stretchr/testify/require"
)

var _ = suite("auth/init", func(t *testing.T, when spec.G, it spec.S) {
	var (
		expect *require.Assertions
		server *httptest.Server
	)

	it.Before(func() {
		expect = require.New(t)

		server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
			w.Header().Add("content-type", "application/json")

			switch req.URL.Path {
			case "/v2/account":
				auth := req.Header.Get("Authorization")

				if auth == "Bearer first-token" || auth == "Bearer second-token" || auth == "Bearer some-magic-token" {
					w.Write([]byte(`{ "account":{}}`))
					return
				}

				w.WriteHeader(http.StatusUnauthorized)
			case "/v2/droplets/1":
				token := req.Header.Get("Authorization")
				if token != "Bearer second-token" {
					w.WriteHeader(http.StatusUnauthorized)
					return
				}

				w.WriteHeader(http.StatusNoContent)
			default:
				dump, err := httputil.DumpRequest(req, true)
				if err != nil {
					t.Fatal("failed to dump request")
				}

				t.Fatalf("received unknown request: %s", dump)
			}
		}))
	})

	when("a custom config is provided", func() {
		it("validates and saves the provided auth token", func() {
			tmpDir, err := ioutil.TempDir("", "")
			expect.NoError(err)

			testConfig := filepath.Join(tmpDir, "test-config.yml")

			cmd := exec.Command(builtBinaryPath,
				"-u", server.URL,
				"--config", testConfig,
				"auth",
				"init",
			)

			ptmx, err := pty.Start(cmd)
			expect.NoError(err)

			go func() {
				ptmx.Write([]byte("some-magic-token\n"))
			}()

			buf := bytes.NewBuffer([]byte{})

			count, _ := io.Copy(buf, ptmx) // yes, ignore error intentionally
			expect.NotZero(count)
			ptmx.Close()

			expect.Contains(buf.String(), "Validating token... OK")

			fileBytes, err := ioutil.ReadFile(testConfig)
			expect.NoError(err)

			expect.Contains(string(fileBytes), "access-token: some-magic-token")
		})
	})

	when("no custom config is provided", func() {
		it("saves the auth token to the default config path", func() {
			cmd := exec.Command(builtBinaryPath,
				"-u", server.URL,
				"auth",
				"init",
			)

			ptmx, err := pty.Start(cmd)
			expect.NoError(err)

			go func() {
				ptmx.Write([]byte("some-magic-token\n"))
			}()

			buf := bytes.NewBuffer([]byte{})

			count, _ := io.Copy(buf, ptmx) // yes, ignore error intentionally
			expect.NotZero(count)
			ptmx.Close()

			expect.Contains(buf.String(), "Validating token... OK")

			location, err := getDefaultConfigLocation()
			expect.NoError(err)

			fileBytes, err := ioutil.ReadFile(location)
			expect.NoError(err)

			expect.Contains(string(fileBytes), "access-token: some-magic-token")

			err = os.Remove(location)
			expect.NoError(err)
		})
	})

	when("a token cannot be validated", func() {
		it("exits non-zero with an error", func() {
			tmpDir, err := ioutil.TempDir("", "")
			expect.NoError(err)

			testConfig := filepath.Join(tmpDir, "test-config.yml")

			cmd := exec.Command(builtBinaryPath,
				"-u", server.URL,
				"--config", testConfig,
				"auth",
				"init",
			)

			ptmx, err := pty.Start(cmd)
			expect.NoError(err)

			go func() {
				ptmx.Write([]byte("some-bad-token\n"))
			}()

			buf := bytes.NewBuffer([]byte{})

			count, _ := io.Copy(buf, ptmx) // yes, ignore error intentionally
			expect.NotZero(count)
			ptmx.Close()

			expect.Contains(buf.String(), "Validating token... invalid token")
			expect.Contains(buf.String(), fmt.Sprintf("Unable to use supplied token to access API: GET %s/v2/account: 401", server.URL))
		})
	})

	when("a new auth context is added", func() {
		it("allows you to switch to that context", func() {
			const nextContext = "next"

			var testConfigBytes = []byte(`access-token: first-token
auth-contexts:
  next: second-token
context: default
`)

			tmpDir, err := ioutil.TempDir("", "")
			expect.NoError(err)
			testConfig := filepath.Join(tmpDir, "test-config.yml")
			expect.NoError(ioutil.WriteFile(testConfig, testConfigBytes, 0644))

			cmd := exec.Command(builtBinaryPath,
				"-u", server.URL,
				"auth",
				"switch",
				"--config", testConfig,
				"--context",
				nextContext,
			)
			_, err = cmd.CombinedOutput()
			expect.NoError(err)

			fileBytes, err := ioutil.ReadFile(testConfig)
			expect.NoError(err)
			expect.Contains(string(fileBytes), "context: next")

			cmd = exec.Command(builtBinaryPath,
				"-u", server.URL,
				"--config", testConfig,
				"compute",
				"droplet",
				"delete",
				"1",
				"-f",
			)

			output, err := cmd.CombinedOutput()
			expect.NoError(err, string(output))

			err = os.Remove(testConfig)
			expect.NoError(err)
		})
	})
})
<|endoftext|>


<commit_before>package main

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

var (
	groups   = regexp.MustCompile(`(?:[^/\\]|\\.)*`)
	branches = regexp.MustCompile(`(?:[^,\\]|\\.)*`)
)

func parseExpr(expr string) ([][]string, error) {
	expr = strings.Replace(expr, `\,`, `\\,`, -1)
	expr = strings.Replace(expr, `\/`, `\\/`, -1)
	expr, err := strconv.Unquote(`"` + expr + `"`)
	if err != nil {
		return nil, err
	}

	gls := groups.FindAllString(expr, -1)
	tree := make([][]string, len(sls))
	for gi := 0; gi < len(gls); gi++ {
		bls := branches.FindAllString(gls[gi], -1)
		for bi := 0; bi < len(bls); bi++ {
			bls[bi] = strings.Replace(bls[bi], `\,`, `,`, -1)
			bls[bi] = strings.Replace(bls[bi], `\/`, `/`, -1)
			bls[bi] = regexp.QuoteMeta(bls[bi])
		}
		tree[gi] = bls
	}
	return tree, nil
}

func newMatcher(expr string) (m *regexp.Regexp, err error) {
	tree, err := parseExpr(expr)
	if err != nil {
		return nil, err
	}

	sls := make([]string, len(tree))
	for gi, bls := range tree {
		sls[gi] = "(" + strings.Join(bls, "|") + ")"
	}
	return regexp.Compile(strings.Join(sls, ""))
}

func newReplacement(exprFrom, exprTo string) ([]map[string]string, error) {
	from, err := parseExpr(exprFrom)
	if err != nil {
		return nil, err
	}
	to, err := parseExpr(exprTo)
	if err != nil {
		return nil, err
	}

	if len(from) != len(to) {
		return nil, fmt.Errorf("mismatch the number of group")
	}

	r := make([]map[string]string, len(from))
	for gi := 0; gi < len(from); gi++ {
		if len(from[gi]) != len(to[gi]) {
			return nil, fmt.Errorf("mismatch the number of group[%q]", gi)
		}

		r[gi] = make(map[string]string)
		for bi := 0; bi < len(from[gi]); bi++ {
			src, dst := from[gi][bi], to[gi][bi]
			if _, exist := r[gi][src]; exist {
				return nil, fmt.Errorf("group[%q] has duplicate items", gi)
			}
			r[gi][src] = dst
		}
	}
	return r, nil
}

type Replacer struct {
	matcher     *regexp.Regexp
	replacement []map[string]string
}

func NewReplacer(from, to string) (r *Replacer, err error) {
	r = &Replacer{}

	r.matcher, err = newMatcher(from)
	if err != nil {
		return nil, err
	}
	r.replacement, err = newReplacement(from, to)
	if err != nil {
		return nil, err
	}

	return r, nil
}

func (r *Replacer) ReplaceAll(s string) string {
	return r.matcher.ReplaceAllStringFunc(s, func(t string) string {
		m := r.matcher.FindStringSubmatch(t)[1:]

		a := make([]string, len(m))
		for i, from := range m {
			a[i] = r.replacement[i][from]
		}
		return strings.Join(a, "")
	})
}
<commit_msg>Fix forgotten change variable name<commit_after>package main

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

var (
	groups   = regexp.MustCompile(`(?:[^/\\]|\\.)*`)
	branches = regexp.MustCompile(`(?:[^,\\]|\\.)*`)
)

func parseExpr(expr string) ([][]string, error) {
	expr = strings.Replace(expr, `\,`, `\\,`, -1)
	expr = strings.Replace(expr, `\/`, `\\/`, -1)
	expr, err := strconv.Unquote(`"` + expr + `"`)
	if err != nil {
		return nil, err
	}

	gls := groups.FindAllString(expr, -1)
	tree := make([][]string, len(gls))
	for gi := 0; gi < len(gls); gi++ {
		bls := branches.FindAllString(gls[gi], -1)
		for bi := 0; bi < len(bls); bi++ {
			bls[bi] = strings.Replace(bls[bi], `\,`, `,`, -1)
			bls[bi] = strings.Replace(bls[bi], `\/`, `/`, -1)
			bls[bi] = regexp.QuoteMeta(bls[bi])
		}
		tree[gi] = bls
	}
	return tree, nil
}

func newMatcher(expr string) (m *regexp.Regexp, err error) {
	tree, err := parseExpr(expr)
	if err != nil {
		return nil, err
	}

	sls := make([]string, len(tree))
	for gi, bls := range tree {
		sls[gi] = "(" + strings.Join(bls, "|") + ")"
	}
	return regexp.Compile(strings.Join(sls, ""))
}

func newReplacement(exprFrom, exprTo string) ([]map[string]string, error) {
	from, err := parseExpr(exprFrom)
	if err != nil {
		return nil, err
	}
	to, err := parseExpr(exprTo)
	if err != nil {
		return nil, err
	}

	if len(from) != len(to) {
		return nil, fmt.Errorf("mismatch the number of group")
	}

	r := make([]map[string]string, len(from))
	for gi := 0; gi < len(from); gi++ {
		if len(from[gi]) != len(to[gi]) {
			return nil, fmt.Errorf("mismatch the number of group[%q]", gi)
		}

		r[gi] = make(map[string]string)
		for bi := 0; bi < len(from[gi]); bi++ {
			src, dst := from[gi][bi], to[gi][bi]
			if _, exist := r[gi][src]; exist {
				return nil, fmt.Errorf("group[%q] has duplicate items", gi)
			}
			r[gi][src] = dst
		}
	}
	return r, nil
}

type Replacer struct {
	matcher     *regexp.Regexp
	replacement []map[string]string
}

func NewReplacer(from, to string) (r *Replacer, err error) {
	r = &Replacer{}

	r.matcher, err = newMatcher(from)
	if err != nil {
		return nil, err
	}
	r.replacement, err = newReplacement(from, to)
	if err != nil {
		return nil, err
	}

	return r, nil
}

func (r *Replacer) ReplaceAll(s string) string {
	return r.matcher.ReplaceAllStringFunc(s, func(t string) string {
		m := r.matcher.FindStringSubmatch(t)[1:]

		a := make([]string, len(m))
		for i, from := range m {
			a[i] = r.replacement[i][from]
		}
		return strings.Join(a, "")
	})
}
<|endoftext|>


<commit_before>// +build ccm

package gocql

import (
	"github.com/gocql/gocql/ccm_test"
	"log"
	"testing"
	"time"
)

func TestEventDiscovery(t *testing.T) {
	if err := ccm.AllUp(); err != nil {
		t.Fatal(err)
	}

	session := createSession(t)
	defer session.Close()

	status, err := ccm.Status()
	if err != nil {
		t.Fatal(err)
	}
	t.Logf("status=%+v\n", status)

	session.pool.mu.RLock()
	poolHosts := session.pool.hostConnPools // TODO: replace with session.ring
	t.Logf("poolhosts=%+v\n", poolHosts)
	// check we discovered all the nodes in the ring
	for _, host := range status {
		if _, ok := poolHosts[host.Addr]; !ok {
			t.Errorf("did not discover %q", host.Addr)
		}
	}
	session.pool.mu.RUnlock()
	if t.Failed() {
		t.FailNow()
	}
}

func TestEventNodeDownControl(t *testing.T) {
	const targetNode = "node1"
	if err := ccm.AllUp(); err != nil {
		t.Fatal(err)
	}

	session := createSession(t)
	defer session.Close()

	if err := ccm.NodeDown(targetNode); err != nil {
		t.Fatal(err)
	}
	log.Println("down")

	status, err := ccm.Status()
	if err != nil {
		t.Fatal(err)
	}
	t.Logf("status=%+v\n", status)

	time.Sleep(5 * time.Second)

	session.pool.mu.RLock()

	poolHosts := session.pool.hostConnPools
	node := status[targetNode]
	t.Logf("poolhosts=%+v\n", poolHosts)

	if _, ok := poolHosts[node.Addr]; ok {
		session.pool.mu.RUnlock()
		t.Fatal("node not removed after remove event")
	}
	session.pool.mu.RUnlock()
}

func TestEventNodeDown(t *testing.T) {
	const targetNode = "node3"
	if err := ccm.AllUp(); err != nil {
		t.Fatal(err)
	}

	session := createSession(t)
	defer session.Close()

	if err := ccm.NodeDown(targetNode); err != nil {
		t.Fatal(err)
	}
	log.Println("down")

	status, err := ccm.Status()
	if err != nil {
		t.Fatal(err)
	}
	t.Logf("status=%+v\n", status)

	time.Sleep(5 * time.Second)

	session.pool.mu.RLock()
	defer session.pool.mu.RUnlock()

	poolHosts := session.pool.hostConnPools
	node := status[targetNode]
	t.Logf("poolhosts=%+v\n", poolHosts)

	if _, ok := poolHosts[node.Addr]; ok {
		t.Fatal("node not removed after remove event")
	}
}

func TestEventNodeUp(t *testing.T) {
	if err := ccm.AllUp(); err != nil {
		t.Fatal(err)
	}

	status, err := ccm.Status()
	if err != nil {
		t.Fatal(err)
	}
	t.Logf("status=%+v\n", status)

	session := createSession(t)
	defer session.Close()

	const targetNode = "node2"

	if err := ccm.NodeDown(targetNode); err != nil {
		t.Fatal(err)
	}

	time.Sleep(5 * time.Second)

	session.pool.mu.RLock()

	poolHosts := session.pool.hostConnPools
	t.Logf("poolhosts=%+v\n", poolHosts)
	node := status[targetNode]

	if _, ok := poolHosts[node.Addr]; ok {
		session.pool.mu.RUnlock()
		t.Fatal("node not removed after remove event")
	}
	session.pool.mu.RUnlock()

	if err := ccm.NodeUp(targetNode); err != nil {
		t.Fatal(err)
	}

	time.Sleep(5 * time.Second)

	session.pool.mu.RLock()
	t.Logf("poolhosts=%+v\n", poolHosts)
	if _, ok := poolHosts[node.Addr]; !ok {
		session.pool.mu.RUnlock()
		t.Fatal("node not added after node added event")
	}
	session.pool.mu.RUnlock()
}
<commit_msg>improve ccm event test logging<commit_after>// +build ccm

package gocql

import (
	"github.com/gocql/gocql/ccm_test"
	"testing"
	"time"
)

func TestEventDiscovery(t *testing.T) {
	if err := ccm.AllUp(); err != nil {
		t.Fatal(err)
	}

	session := createSession(t)
	defer session.Close()

	status, err := ccm.Status()
	if err != nil {
		t.Fatal(err)
	}
	t.Logf("status=%+v\n", status)

	session.pool.mu.RLock()
	poolHosts := session.pool.hostConnPools // TODO: replace with session.ring
	t.Logf("poolhosts=%+v\n", poolHosts)
	// check we discovered all the nodes in the ring
	for _, host := range status {
		if _, ok := poolHosts[host.Addr]; !ok {
			t.Errorf("did not discover %q", host.Addr)
		}
	}
	session.pool.mu.RUnlock()
	if t.Failed() {
		t.FailNow()
	}
}

func TestEventNodeDownControl(t *testing.T) {
	const targetNode = "node1"
	t.Log("marking " + targetNode + " as down")
	if err := ccm.AllUp(); err != nil {
		t.Fatal(err)
	}

	session := createSession(t)
	defer session.Close()

	if err := ccm.NodeDown(targetNode); err != nil {
		t.Fatal(err)
	}

	status, err := ccm.Status()
	if err != nil {
		t.Fatal(err)
	}
	t.Logf("status=%+v\n", status)
	t.Logf("marking node %q down: %v\n", targetNode, status[targetNode])

	time.Sleep(5 * time.Second)

	session.pool.mu.RLock()

	poolHosts := session.pool.hostConnPools
	node := status[targetNode]
	t.Logf("poolhosts=%+v\n", poolHosts)

	if _, ok := poolHosts[node.Addr]; ok {
		session.pool.mu.RUnlock()
		t.Fatal("node not removed after remove event")
	}
	session.pool.mu.RUnlock()
}

func TestEventNodeDown(t *testing.T) {
	const targetNode = "node3"
	if err := ccm.AllUp(); err != nil {
		t.Fatal(err)
	}

	session := createSession(t)
	defer session.Close()

	if err := ccm.NodeDown(targetNode); err != nil {
		t.Fatal(err)
	}

	status, err := ccm.Status()
	if err != nil {
		t.Fatal(err)
	}
	t.Logf("status=%+v\n", status)
	t.Logf("marking node %q down: %v\n", targetNode, status[targetNode])

	time.Sleep(5 * time.Second)

	session.pool.mu.RLock()
	defer session.pool.mu.RUnlock()

	poolHosts := session.pool.hostConnPools
	node := status[targetNode]
	t.Logf("poolhosts=%+v\n", poolHosts)

	if _, ok := poolHosts[node.Addr]; ok {
		t.Fatal("node not removed after remove event")
	}
}

func TestEventNodeUp(t *testing.T) {
	if err := ccm.AllUp(); err != nil {
		t.Fatal(err)
	}

	status, err := ccm.Status()
	if err != nil {
		t.Fatal(err)
	}
	t.Logf("status=%+v\n", status)

	session := createSession(t)
	defer session.Close()

	const targetNode = "node2"

	if err := ccm.NodeDown(targetNode); err != nil {
		t.Fatal(err)
	}

	time.Sleep(5 * time.Second)

	session.pool.mu.RLock()

	poolHosts := session.pool.hostConnPools
	t.Logf("poolhosts=%+v\n", poolHosts)
	node := status[targetNode]

	if _, ok := poolHosts[node.Addr]; ok {
		session.pool.mu.RUnlock()
		t.Fatal("node not removed after remove event")
	}
	session.pool.mu.RUnlock()

	if err := ccm.NodeUp(targetNode); err != nil {
		t.Fatal(err)
	}

	time.Sleep(5 * time.Second)

	session.pool.mu.RLock()
	t.Logf("poolhosts=%+v\n", poolHosts)
	if _, ok := poolHosts[node.Addr]; !ok {
		session.pool.mu.RUnlock()
		t.Fatal("node not added after node added event")
	}
	session.pool.mu.RUnlock()
}
<|endoftext|>


<commit_before>// Copyright 2018 The Ebiten 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 audio_test

import (
	"errors"
	"os"
	"runtime"
	"testing"
	"time"

	"github.com/hajimehoshi/ebiten"
	. "github.com/hajimehoshi/ebiten/audio"
	"github.com/hajimehoshi/ebiten/internal/testflock"
)

func TestMain(m *testing.M) {
	testflock.Lock()
	defer testflock.Unlock()

	code := 0
	// Run an Ebiten process so that audio is available.
	regularTermination := errors.New("regular termination")
	f := func(screen *ebiten.Image) error {
		code = m.Run()
		return regularTermination
	}
	if err := ebiten.Run(f, 320, 240, 1, "Test"); err != nil && err != regularTermination {
		panic(err)
	}
	os.Exit(code)
}

var context *Context

func init() {
	var err error
	context, err = NewContext(44100)
	if err != nil {
		panic(err)
	}
}

// Issue #746
func TestGC(t *testing.T) {
	p, _ := NewPlayer(context, BytesReadSeekCloser(make([]byte, 4)))
	got := PlayersNumForTesting()
	if want := 0; got != want {
		t.Errorf("PlayersNum(): got: %d, want: %d", got, want)
	}

	p.Play()
	got = PlayersNumForTesting()
	if want := 1; got != want {
		t.Errorf("PlayersNum() after Play: got: %d, want: %d", got, want)
	}

	runtime.KeepAlive(p)
	p = nil
	runtime.GC()

	ch := make(chan struct{})
	go func() {
		defer close(ch)
		for i := 0; i < 10; i++ {
			got = PlayersNumForTesting()
			if want := 0; got == want {
				return
			}
			// 100[ms] should be enough all the bytes are consumed.
			// TODO: This is a darty hack. Would it be possible to use virtual time?
			time.Sleep(100 * time.Millisecond)
		}
		t.Errorf("time out")
	}()

	<-ch
}
<commit_msg>audio: No need goroutine for tests<commit_after>// Copyright 2018 The Ebiten 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 audio_test

import (
	"errors"
	"os"
	"runtime"
	"testing"
	"time"

	"github.com/hajimehoshi/ebiten"
	. "github.com/hajimehoshi/ebiten/audio"
	"github.com/hajimehoshi/ebiten/internal/testflock"
)

func TestMain(m *testing.M) {
	testflock.Lock()
	defer testflock.Unlock()

	code := 0
	// Run an Ebiten process so that audio is available.
	regularTermination := errors.New("regular termination")
	f := func(screen *ebiten.Image) error {
		code = m.Run()
		return regularTermination
	}
	if err := ebiten.Run(f, 320, 240, 1, "Test"); err != nil && err != regularTermination {
		panic(err)
	}
	os.Exit(code)
}

var context *Context

func init() {
	var err error
	context, err = NewContext(44100)
	if err != nil {
		panic(err)
	}
}

// Issue #746
func TestGC(t *testing.T) {
	p, _ := NewPlayer(context, BytesReadSeekCloser(make([]byte, 4)))
	got := PlayersNumForTesting()
	if want := 0; got != want {
		t.Errorf("PlayersNum(): got: %d, want: %d", got, want)
	}

	p.Play()
	got = PlayersNumForTesting()
	if want := 1; got != want {
		t.Errorf("PlayersNum() after Play: got: %d, want: %d", got, want)
	}

	runtime.KeepAlive(p)
	p = nil
	runtime.GC()

	for i := 0; i < 10; i++ {
		got = PlayersNumForTesting()
		if want := 0; got == want {
			return
		}
		// 100[ms] should be enough all the bytes are consumed.
		// TODO: This is a darty hack. Would it be possible to use virtual time?
		time.Sleep(100 * time.Millisecond)
	}
	t.Errorf("time out")
}
<|endoftext|>


<commit_before>package auth

import (
	"testing"
)

func TestRegistry(t *testing.T) {
	// Get the hasher from the registry
	pbkdf2_sha256, err := GetHasher("pbkdf2_sha256")
	if err != nil {
		// TODO best way to print an error?
		t.Errorf("Failed to get hasher with err %s", err)
	}
	cleartext := "badpassword"
	hashed := MakePassword(pbkdf2_sha256, cleartext)
	// TODO some error output would be appreciated
	verify := CheckPassword(pbkdf2_sha256, cleartext, hashed)
	if !verify {
		t.Errorf("Password did not verify!")
	}
}

// TODO Create a hash and plug it in
// TODO test util functions
<commit_msg>hashing errors during testing should be fatal<commit_after>package auth

import (
	"testing"
)

func TestRegistry(t *testing.T) {
	// Get the hasher from the registry
	pbkdf2_sha256, err := GetHasher("pbkdf2_sha256")
	if err != nil {
		// TODO best way to print an error?
		t.Fatalf("Failed to get hasher with err %s", err)
	}
	cleartext := "badpassword"
	hashed := MakePassword(pbkdf2_sha256, cleartext)
	// TODO some error output would be appreciated
	verify := CheckPassword(pbkdf2_sha256, cleartext, hashed)
	if !verify {
		t.Errorf("Password did not verify!")
	}
}

// TODO Create a hash and plug it in
// TODO test util functions
<|endoftext|>


<commit_before>package sup

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

	"gopkg.in/yaml.v2"
)

// Supfile represents the Stack Up configuration YAML file.
type Supfile struct {
	Networks map[string]Network  `yaml:"networks"`
	Commands map[string]Command  `yaml:"commands"`
	Targets  map[string][]string `yaml:"targets"`
	Env      map[string]string   `yaml:"env"`
	Version  string              `yaml:"version"`
}

// Network is group of hosts with extra custom env vars.
type Network struct {
	Env       map[string]string `yaml:"env"`
	Inventory string            `yaml:"inventory"`
	Hosts     []string          `yaml:"hosts"`
	Bastion   string            `yaml:"bastion"` // Jump host for the environment
}

// Command represents command(s) to be run remotely.
type Command struct {
	Name   string   `yaml:"-"`      // Command name.
	Desc   string   `yaml:"desc"`   // Command description.
	Local  string   `yaml:"local"`  // Command(s) to be run locally.
	Run    string   `yaml:"run"`    // Command(s) to be run remotelly.
	Script string   `yaml:"script"` // Load command(s) from script and run it remotelly.
	Upload []Upload `yaml:"upload"` // See Upload struct.
	Stdin  bool     `yaml:"stdin"`  // Attach localhost STDOUT to remote commands' STDIN?
	Once   bool     `yaml:"once"`   // The command should be run "once" (on one host only).
	Serial int      `yaml:"serial"` // Max number of clients processing a task in parallel.

	// API backward compatibility. Will be deprecated in v1.0.
	RunOnce bool `yaml:"run_once"` // The command should be run once only.
}

// Upload represents file copy operation from localhost Src path to Dst
// path of every host in a given Network.
type Upload struct {
	Src string `yaml:"src"`
	Dst string `yaml:"dst"`
	Exc string `yaml:"exclude"`
}

// NewSupfile parses configuration file and returns Supfile or error.
func NewSupfile(file string) (*Supfile, error) {
	var conf Supfile
	data, err := ioutil.ReadFile(file)
	if err != nil {
		return nil, err
	}
	err = yaml.Unmarshal(data, &conf)
	if err != nil {
		return nil, err
	}

	// API backward compatibility. Will be deprecated in v1.0.
	switch conf.Version {
	case "":
		conf.Version = "0.1"
		fallthrough
	case "0.1":
		for _, cmd := range conf.Commands {
			if cmd.RunOnce {
				return nil, errors.New("command.run_once is not supported in Supfile v" + conf.Version)
			}
		}
		fallthrough
	case "0.2":
		for _, cmd := range conf.Commands {
			if cmd.Once {
				return nil, errors.New("command.once is not supported in Supfile v" + conf.Version)
			}
			if cmd.Local != "" {
				return nil, errors.New("command.local is not supported in Supfile v" + conf.Version)
			}
			if cmd.Serial != 0 {
				return nil, errors.New("command.serial is not supported in Supfile v" + conf.Version)
			}
		}
		for _, network := range conf.Networks {
			if network.Inventory != "" {
				return nil, errors.New("network.inventory is not supported in Supfile v" + conf.Version)
			}
		}
	case "0.3":
		for _, cmd := range conf.Commands {
			if cmd.RunOnce {
				fmt.Fprintf(os.Stderr, "Warning: command.run_once was deprecated by command.once in Supfile v"+conf.Version+"\n")
				cmd.Once = cmd.RunOnce
				break
			}
		}
	default:
		return nil, errors.New("unsupported version, please update sup by `go get -u github.com/pressly/sup`")
	}

	for i, network := range conf.Networks {
		hosts, err := network.ParseInventory()
		if err != nil {
			return nil, err
		}
		network.Hosts = append(network.Hosts, hosts...)
		conf.Networks[i] = network
	}

	return &conf, nil
}

// ParseInventory runs the inventory command, if provided, and appends
// the command's output lines to the manually defined list of hosts.
func (n Network) ParseInventory() ([]string, error) {
	if n.Inventory == "" {
		return nil, nil
	}

	cmd := exec.Command("/bin/sh", "-c", n.Inventory)
	cmd.Stderr = os.Stderr
	output, err := cmd.Output()
	if err != nil {
		return nil, err
	}

	var hosts []string
	buf := bytes.NewBuffer(output)
	for {
		host, err := buf.ReadString('\n')
		if err != nil {
			if err == io.EOF {
				break
			}
			return nil, err
		}

		host = strings.TrimSpace(host)
		// skip empty lines and comments
		if host == "" || host[:1] == "#" {
			continue
		}

		hosts = append(hosts, host)
	}
	return hosts, nil
}
<commit_msg>Fix run_once backward compatibility on v0.3<commit_after>package sup

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

	"gopkg.in/yaml.v2"
)

// Supfile represents the Stack Up configuration YAML file.
type Supfile struct {
	Networks map[string]Network  `yaml:"networks"`
	Commands map[string]Command  `yaml:"commands"`
	Targets  map[string][]string `yaml:"targets"`
	Env      map[string]string   `yaml:"env"`
	Version  string              `yaml:"version"`
}

// Network is group of hosts with extra custom env vars.
type Network struct {
	Env       map[string]string `yaml:"env"`
	Inventory string            `yaml:"inventory"`
	Hosts     []string          `yaml:"hosts"`
	Bastion   string            `yaml:"bastion"` // Jump host for the environment
}

// Command represents command(s) to be run remotely.
type Command struct {
	Name   string   `yaml:"-"`      // Command name.
	Desc   string   `yaml:"desc"`   // Command description.
	Local  string   `yaml:"local"`  // Command(s) to be run locally.
	Run    string   `yaml:"run"`    // Command(s) to be run remotelly.
	Script string   `yaml:"script"` // Load command(s) from script and run it remotelly.
	Upload []Upload `yaml:"upload"` // See Upload struct.
	Stdin  bool     `yaml:"stdin"`  // Attach localhost STDOUT to remote commands' STDIN?
	Once   bool     `yaml:"once"`   // The command should be run "once" (on one host only).
	Serial int      `yaml:"serial"` // Max number of clients processing a task in parallel.

	// API backward compatibility. Will be deprecated in v1.0.
	RunOnce bool `yaml:"run_once"` // The command should be run once only.
}

// Upload represents file copy operation from localhost Src path to Dst
// path of every host in a given Network.
type Upload struct {
	Src string `yaml:"src"`
	Dst string `yaml:"dst"`
	Exc string `yaml:"exclude"`
}

// NewSupfile parses configuration file and returns Supfile or error.
func NewSupfile(file string) (*Supfile, error) {
	var conf Supfile
	data, err := ioutil.ReadFile(file)
	if err != nil {
		return nil, err
	}
	err = yaml.Unmarshal(data, &conf)
	if err != nil {
		return nil, err
	}

	// API backward compatibility. Will be deprecated in v1.0.
	switch conf.Version {
	case "":
		conf.Version = "0.1"
		fallthrough
	case "0.1":
		for _, cmd := range conf.Commands {
			if cmd.RunOnce {
				return nil, errors.New("command.run_once is not supported in Supfile v" + conf.Version)
			}
		}
		fallthrough
	case "0.2":
		for _, cmd := range conf.Commands {
			if cmd.Once {
				return nil, errors.New("command.once is not supported in Supfile v" + conf.Version)
			}
			if cmd.Local != "" {
				return nil, errors.New("command.local is not supported in Supfile v" + conf.Version)
			}
			if cmd.Serial != 0 {
				return nil, errors.New("command.serial is not supported in Supfile v" + conf.Version)
			}
		}
		for _, network := range conf.Networks {
			if network.Inventory != "" {
				return nil, errors.New("network.inventory is not supported in Supfile v" + conf.Version)
			}
		}
		fallthrough
	case "0.3":
		var warning string
		for key, cmd := range conf.Commands {
			if cmd.RunOnce {
				warning = "Warning: command.run_once was deprecated by command.once in Supfile v" + conf.Version + "\n"
				cmd.Once = true
				conf.Commands[key] = cmd
			}
		}
		if warning != "" {
			fmt.Fprintf(os.Stderr, warning)
		}
	default:
		return nil, errors.New("unsupported version, please update sup by `go get -u github.com/pressly/sup`")
	}

	for i, network := range conf.Networks {
		hosts, err := network.ParseInventory()
		if err != nil {
			return nil, err
		}
		network.Hosts = append(network.Hosts, hosts...)
		conf.Networks[i] = network
	}

	return &conf, nil
}

// ParseInventory runs the inventory command, if provided, and appends
// the command's output lines to the manually defined list of hosts.
func (n Network) ParseInventory() ([]string, error) {
	if n.Inventory == "" {
		return nil, nil
	}

	cmd := exec.Command("/bin/sh", "-c", n.Inventory)
	cmd.Stderr = os.Stderr
	output, err := cmd.Output()
	if err != nil {
		return nil, err
	}

	var hosts []string
	buf := bytes.NewBuffer(output)
	for {
		host, err := buf.ReadString('\n')
		if err != nil {
			if err == io.EOF {
				break
			}
			return nil, err
		}

		host = strings.TrimSpace(host)
		// skip empty lines and comments
		if host == "" || host[:1] == "#" {
			continue
		}

		hosts = append(hosts, host)
	}
	return hosts, nil
}
<|endoftext|>


<commit_before>package snakepit

import (
	"net/http"
	"os"

	"github.com/pressly/chi"
	"golang.org/x/net/context"
)

type Swagger struct {
	path string
}

func NewSwagger() func(next chi.Handler) chi.Handler {
	path := "./swagger.json"
	if _, err := os.Stat(path); os.IsNotExist(err) {
		path = os.Getenv("HOME") + "/swagger.json"
	}

	swagger := &Swagger{path: path}
	return swagger.middleware
}

func (rec *Swagger) middleware(next chi.Handler) chi.Handler {
	return chi.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		if r.URL.Path == "/swagger" {
			w.Header().Add("Access-Control-Allow-Origin", "*")
			w.Header().Add("Access-Control-Allow-Methods", "GET")

			http.ServeFile(w, r, rec.path)
			return
		}

		next.ServeHTTPC(ctx, w, r)
	})
}
<commit_msg>Swagger middleware now serves dynamically.<commit_after>package snakepit

import (
	"encoding/json"
	"io/ioutil"
	"net/http"
	"os"

	"github.com/pressly/chi"
	"golang.org/x/net/context"
)

type swaggerConf struct {
	Swagger     json.RawMessage `json:"swagger,omitempty"`
	BasePath    string          `json:"basePath,omitempty"`
	Schemes     []string        `json:"schemes,omitempty"`
	Consumes    json.RawMessage `json:"consumes,omitempty"`
	Produces    json.RawMessage `json:"produces,omitempty"`
	Info        json.RawMessage `json:"info,omitempty"`
	Paths       json.RawMessage `json:"paths,omitempty"`
	Definitions json.RawMessage `json:"definitions,omitempty"`
	Responses   json.RawMessage `json:"responses,omitempty"`
}

type Swagger struct {
	conf []byte
}

func NewSwagger(basePath, scheme string) func(next chi.Handler) chi.Handler {
	path := "./swagger.json"
	if _, err := os.Stat(path); os.IsNotExist(err) {
		path = os.Getenv("HOME") + "/swagger.json"
	}

	buf, err := ioutil.ReadFile(path)
	if err != nil {
		panic(err)
	}

	conf := &swaggerConf{}

	if err := json.Unmarshal(buf, conf); err != nil {
		panic(err)
	}

	conf.BasePath = basePath
	conf.Schemes = []string{scheme}

	raw, err := json.Marshal(conf)
	if err != nil {
		panic(err)
	}

	swagger := &Swagger{conf: raw}
	return swagger.middleware
}

func (rec *Swagger) middleware(next chi.Handler) chi.Handler {
	return chi.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		if r.URL.Path == "/swagger" {
			w.WriteHeader(200)

			w.Header().Add("Access-Control-Allow-Origin", "*")
			w.Header().Add("Access-Control-Allow-Methods", "GET")
			w.Header().Set("Content-Type", "application/json")

			w.Write(rec.conf)

			return
		}

		next.ServeHTTPC(ctx, w, r)
	})
}
<|endoftext|>


<commit_before>package hcs

import (
	"fmt"
	"sync"
	"syscall"

	"github.com/Microsoft/hcsshim/internal/interop"
	"github.com/Microsoft/hcsshim/internal/logfields"
	"github.com/sirupsen/logrus"
)

var (
	nextCallback    uintptr
	callbackMap     = map[uintptr]*notifcationWatcherContext{}
	callbackMapLock = sync.RWMutex{}

	notificationWatcherCallback = syscall.NewCallback(notificationWatcher)

	// Notifications for HCS_SYSTEM handles
	hcsNotificationSystemExited                      hcsNotification = 0x00000001
	hcsNotificationSystemCreateCompleted             hcsNotification = 0x00000002
	hcsNotificationSystemStartCompleted              hcsNotification = 0x00000003
	hcsNotificationSystemPauseCompleted              hcsNotification = 0x00000004
	hcsNotificationSystemResumeCompleted             hcsNotification = 0x00000005
	hcsNotificationSystemCrashReport                 hcsNotification = 0x00000006
	hcsNotificationSystemSiloJobCreated              hcsNotification = 0x00000007
	hcsNotificationSystemSaveCompleted               hcsNotification = 0x00000008
	hcsNotificationSystemRdpEnhancedModeStateChanged hcsNotification = 0x00000009
	hcsNotificationSystemShutdownFailed              hcsNotification = 0x0000000A
	hcsNotificationSystemGetPropertiesCompleted      hcsNotification = 0x0000000B
	hcsNotificationSystemModifyCompleted             hcsNotification = 0x0000000C
	hcsNotificationSystemCrashInitiated              hcsNotification = 0x0000000D
	hcsNotificationSystemGuestConnectionClosed       hcsNotification = 0x0000000E

	// Notifications for HCS_PROCESS handles
	hcsNotificationProcessExited hcsNotification = 0x00010000

	// Common notifications
	hcsNotificationInvalid           hcsNotification = 0x00000000
	hcsNotificationServiceDisconnect hcsNotification = 0x01000000
)

type hcsNotification uint32

func (hn hcsNotification) String() string {
	switch hn {
	case hcsNotificationSystemExited:
		return "SystemExited"
	case hcsNotificationSystemCreateCompleted:
		return "SystemCreateCompleted"
	case hcsNotificationSystemStartCompleted:
		return "SystemStartCompleted"
	case hcsNotificationSystemPauseCompleted:
		return "SystemPauseCompleted"
	case hcsNotificationSystemResumeCompleted:
		return "SystemResumeCompleted"
	case hcsNotificationSystemCrashReport:
		return "SystemCrashReport"
	case hcsNotificationSystemSiloJobCreated:
		return "SystemSiloJobCreated"
	case hcsNotificationSystemSaveCompleted:
		return "SystemSaveCompleted"
	case hcsNotificationSystemRdpEnhancedModeStateChanged:
		return "SystemRdpEnhancedModeStateChanged"
	case hcsNotificationSystemShutdownFailed:
		return "SystemShutdownFailed"
	case hcsNotificationSystemGetPropertiesCompleted:
		return "SystemGetPropertiesCompleted"
	case hcsNotificationSystemModifyCompleted:
		return "SystemModifyCompleted"
	case hcsNotificationSystemCrashInitiated:
		return "SystemCrashInitiated"
	case hcsNotificationSystemGuestConnectionClosed:
		return "SystemGuestConnectionClosed"
	case hcsNotificationProcessExited:
		return "ProcessExited"
	case hcsNotificationInvalid:
		return "Invalid"
	case hcsNotificationServiceDisconnect:
		return "ServiceDisconnect"
	default:
		return fmt.Sprintf("Unknown: %d", hn)
	}
}

type notificationChannel chan error

type notifcationWatcherContext struct {
	channels notificationChannels
	handle   hcsCallback

	systemID  string
	processID int
}

type notificationChannels map[hcsNotification]notificationChannel

func newSystemChannels() notificationChannels {
	channels := make(notificationChannels)

	channels[hcsNotificationSystemExited] = make(notificationChannel, 1)
	channels[hcsNotificationSystemCreateCompleted] = make(notificationChannel, 1)
	channels[hcsNotificationSystemStartCompleted] = make(notificationChannel, 1)
	channels[hcsNotificationSystemPauseCompleted] = make(notificationChannel, 1)
	channels[hcsNotificationSystemResumeCompleted] = make(notificationChannel, 1)

	return channels
}

func newProcessChannels() notificationChannels {
	channels := make(notificationChannels)

	channels[hcsNotificationProcessExited] = make(notificationChannel, 1)

	return channels
}

func closeChannels(channels notificationChannels) {
	for _, c := range channels {
		close(c)
	}
}

func notificationWatcher(notificationType hcsNotification, callbackNumber uintptr, notificationStatus uintptr, notificationData *uint16) uintptr {
	var result error
	if int32(notificationStatus) < 0 {
		result = interop.Win32FromHresult(notificationStatus)
	}

	callbackMapLock.RLock()
	context := callbackMap[callbackNumber]
	callbackMapLock.RUnlock()

	if context == nil {
		return 0
	}

	log := logrus.WithFields(logrus.Fields{
		"notification-type": notificationType.String(),
		"system-id":         context.systemID,
	})
	if context.processID != 0 {
		log.Data[logfields.ProcessID] = context.processID
	}
	log.Debug("")

	// The HCS notification system can grow overtime. We explicitly opt-in to
	// the notifications we would like to handle, all others we simply return.
	// This means that as it grows we don't have issues associated with new
	// notification types the code didn't know about.
	switch notificationType {
	case hcsNotificationSystemExited, hcsNotificationSystemCreateCompleted, hcsNotificationSystemStartCompleted, hcsNotificationSystemPauseCompleted, hcsNotificationSystemResumeCompleted:
	case hcsNotificationProcessExited:
	default:
		return 0
	}

	if channel, ok := context.channels[notificationType]; ok {
		channel <- result
	}

	return 0
}
<commit_msg>hcs: Fail operations when the HCS service crashes<commit_after>package hcs

import (
	"fmt"
	"sync"
	"syscall"

	"github.com/Microsoft/hcsshim/internal/interop"
	"github.com/Microsoft/hcsshim/internal/logfields"
	"github.com/sirupsen/logrus"
)

var (
	nextCallback    uintptr
	callbackMap     = map[uintptr]*notifcationWatcherContext{}
	callbackMapLock = sync.RWMutex{}

	notificationWatcherCallback = syscall.NewCallback(notificationWatcher)

	// Notifications for HCS_SYSTEM handles
	hcsNotificationSystemExited                      hcsNotification = 0x00000001
	hcsNotificationSystemCreateCompleted             hcsNotification = 0x00000002
	hcsNotificationSystemStartCompleted              hcsNotification = 0x00000003
	hcsNotificationSystemPauseCompleted              hcsNotification = 0x00000004
	hcsNotificationSystemResumeCompleted             hcsNotification = 0x00000005
	hcsNotificationSystemCrashReport                 hcsNotification = 0x00000006
	hcsNotificationSystemSiloJobCreated              hcsNotification = 0x00000007
	hcsNotificationSystemSaveCompleted               hcsNotification = 0x00000008
	hcsNotificationSystemRdpEnhancedModeStateChanged hcsNotification = 0x00000009
	hcsNotificationSystemShutdownFailed              hcsNotification = 0x0000000A
	hcsNotificationSystemGetPropertiesCompleted      hcsNotification = 0x0000000B
	hcsNotificationSystemModifyCompleted             hcsNotification = 0x0000000C
	hcsNotificationSystemCrashInitiated              hcsNotification = 0x0000000D
	hcsNotificationSystemGuestConnectionClosed       hcsNotification = 0x0000000E

	// Notifications for HCS_PROCESS handles
	hcsNotificationProcessExited hcsNotification = 0x00010000

	// Common notifications
	hcsNotificationInvalid           hcsNotification = 0x00000000
	hcsNotificationServiceDisconnect hcsNotification = 0x01000000
)

type hcsNotification uint32

func (hn hcsNotification) String() string {
	switch hn {
	case hcsNotificationSystemExited:
		return "SystemExited"
	case hcsNotificationSystemCreateCompleted:
		return "SystemCreateCompleted"
	case hcsNotificationSystemStartCompleted:
		return "SystemStartCompleted"
	case hcsNotificationSystemPauseCompleted:
		return "SystemPauseCompleted"
	case hcsNotificationSystemResumeCompleted:
		return "SystemResumeCompleted"
	case hcsNotificationSystemCrashReport:
		return "SystemCrashReport"
	case hcsNotificationSystemSiloJobCreated:
		return "SystemSiloJobCreated"
	case hcsNotificationSystemSaveCompleted:
		return "SystemSaveCompleted"
	case hcsNotificationSystemRdpEnhancedModeStateChanged:
		return "SystemRdpEnhancedModeStateChanged"
	case hcsNotificationSystemShutdownFailed:
		return "SystemShutdownFailed"
	case hcsNotificationSystemGetPropertiesCompleted:
		return "SystemGetPropertiesCompleted"
	case hcsNotificationSystemModifyCompleted:
		return "SystemModifyCompleted"
	case hcsNotificationSystemCrashInitiated:
		return "SystemCrashInitiated"
	case hcsNotificationSystemGuestConnectionClosed:
		return "SystemGuestConnectionClosed"
	case hcsNotificationProcessExited:
		return "ProcessExited"
	case hcsNotificationInvalid:
		return "Invalid"
	case hcsNotificationServiceDisconnect:
		return "ServiceDisconnect"
	default:
		return fmt.Sprintf("Unknown: %d", hn)
	}
}

type notificationChannel chan error

type notifcationWatcherContext struct {
	channels notificationChannels
	handle   hcsCallback

	systemID  string
	processID int
}

type notificationChannels map[hcsNotification]notificationChannel

func newSystemChannels() notificationChannels {
	channels := make(notificationChannels)
	for _, notif := range []hcsNotification{
		hcsNotificationServiceDisconnect,
		hcsNotificationSystemExited,
		hcsNotificationSystemCreateCompleted,
		hcsNotificationSystemStartCompleted,
		hcsNotificationSystemPauseCompleted,
		hcsNotificationSystemResumeCompleted,
	} {
		channels[notif] = make(notificationChannel, 1)
	}
	return channels
}

func newProcessChannels() notificationChannels {
	channels := make(notificationChannels)
	for _, notif := range []hcsNotification{
		hcsNotificationServiceDisconnect,
		hcsNotificationProcessExited,
	} {
		channels[notif] = make(notificationChannel, 1)
	}
	return channels
}

func closeChannels(channels notificationChannels) {
	for _, c := range channels {
		close(c)
	}
}

func notificationWatcher(notificationType hcsNotification, callbackNumber uintptr, notificationStatus uintptr, notificationData *uint16) uintptr {
	var result error
	if int32(notificationStatus) < 0 {
		result = interop.Win32FromHresult(notificationStatus)
	}

	callbackMapLock.RLock()
	context := callbackMap[callbackNumber]
	callbackMapLock.RUnlock()

	if context == nil {
		return 0
	}

	log := logrus.WithFields(logrus.Fields{
		"notification-type": notificationType.String(),
		"system-id":         context.systemID,
	})
	if context.processID != 0 {
		log.Data[logfields.ProcessID] = context.processID
	}
	log.Debug("HCS notification")

	if channel, ok := context.channels[notificationType]; ok {
		channel <- result
	}

	return 0
}
<|endoftext|>


<commit_before>// Copyright 2015 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// 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 registry

import (
	"crypto/rand"
	"encoding/base64"
	"fmt"
	"io"
	"strings"
	"time"

	"github.com/jacobsa/comeback/internal/blob"
	"github.com/jacobsa/comeback/internal/crypto"
	"github.com/jacobsa/gcloud/gcs"
	"github.com/jacobsa/gcloud/gcs/gcsutil"
	"golang.org/x/net/context"
)

// Create a registry that stores data in the supplied GCS bucket, deriving a
// crypto key from the supplied password and ensuring that the bucket may not
// in the future be used with any other key and has not in the past, either.
// Return a crypter configured to use the key.
func NewGCSRegistry(
	ctx context.Context,
	bucket gcs.Bucket,
	cryptoPassword string,
	deriver crypto.KeyDeriver) (r Registry, crypter crypto.Crypter, err error) {
	return newGCSRegistry(
		ctx,
		bucket,
		cryptoPassword,
		deriver,
		crypto.NewCrypter,
		rand.Reader)
}

const (
	gcsJobKeyPrefix      = "jobs/"
	gcsMetadataKey_Name  = "job_name"
	gcsMetadataKey_Score = "hex_score"

	// Constants related to the "marker" object, used to ensure that the user has
	// the right password. See notes on gcsRegistry.
	markerObjectName                = "marker"
	markerObjectMetadata_Salt       = "base64_salt"
	markerObjectMetadata_Ciphertext = "base64_ciphertext"
)

// A registry that stores job records in a GCS bucket. Object names are of the
// form
//
//     <gcsJobKeyPrefix><time>
//
// where <time> is a time.Time with UTC location formatted according to
// time.RFC3339. Additional information is stored as object metadata fields
// keyed by the constants above. Metadata fields are used in preference to
// object content so that they are accessible on a ListObjects request.
//
// The bucket additionally contains a "marker" object (named by the constant
// markerObjectName) with metadata keys specifying a salt and a ciphertext for
// some random plaintext, generated ant written the first time the bucket is
// used. This marker allows us to verify that the user-provided crypto password
// is correct by deriving a key using the password and the salt and making sure
// that the ciphertext can be decrypted using that key.
type gcsRegistry struct {
	bucket gcs.Bucket
}

func (r *gcsRegistry) RecordBackup(
	ctx context.Context,
	j CompletedJob) (err error) {
	// Write an object to the bucket. On the small change that the time collides
	// (or we've done something dumb like use the zero time), use a generation
	// precondition to ensure we don't overwrite anything.
	var precond int64
	formattedTime := j.StartTime.UTC().Format(time.RFC3339)
	req := &gcs.CreateObjectRequest{
		Name:                   gcsJobKeyPrefix + formattedTime,
		Contents:               strings.NewReader(""),
		GenerationPrecondition: &precond,

		Metadata: map[string]string{
			gcsMetadataKey_Name:  j.Name,
			gcsMetadataKey_Score: j.Score.Hex(),
		},
	}

	_, err = r.bucket.CreateObject(ctx, req)
	if err != nil {
		err = fmt.Errorf("CreateObject: %v", err)
		return
	}

	return
}

func parseObjectAsJob(o *gcs.Object) (j CompletedJob, err error) {
	// Extract the formatted time.
	if !strings.HasPrefix(o.Name, gcsJobKeyPrefix) {
		err = fmt.Errorf("Unexpected object name: \"%s\"", o.Name)
		return
	}

	formattedTime := strings.TrimPrefix(o.Name, gcsJobKeyPrefix)

	// Parse it.
	j.StartTime, err = time.Parse(time.RFC3339, formattedTime)
	if err != nil {
		err = fmt.Errorf("Parsing time \"%s\": %v", formattedTime, err)
		return
	}

	// Extract the job name.
	{
		var ok bool
		if j.Name, ok = o.Metadata[gcsMetadataKey_Name]; !ok {
			err = fmt.Errorf(
				"Object with name \"%s\" is missing metadata key %s",
				o.Name,
				gcsMetadataKey_Name)

			return
		}
	}

	// Extract the score.
	{
		hexScore, ok := o.Metadata[gcsMetadataKey_Score]
		if !ok {
			err = fmt.Errorf(
				"Object with name \"%s\" is missing metadata key %s",
				o.Name,
				gcsMetadataKey_Score)

			return
		}

		j.Score, err = blob.ParseHexScore(hexScore)
		if err != nil {
			err = fmt.Errorf("Parsing hex score \"%s\": %v", hexScore, err)
			return
		}
	}

	return
}

func (r *gcsRegistry) ListBackups(
	ctx context.Context) (jobs []CompletedJob, err error) {
	// List all of the objects with the appropriate name prefix.
	req := &gcs.ListObjectsRequest{
		Prefix: gcsJobKeyPrefix,
	}

	objects, _, err := gcsutil.ListAll(ctx, r.bucket, req)
	if err != nil {
		err = fmt.Errorf("gcsutil.ListAll: %v", err)
		return
	}

	// Process each object.
	for _, o := range objects {
		var j CompletedJob
		j, err = parseObjectAsJob(o)
		if err != nil {
			err = fmt.Errorf("parseObjectAsJob: %v", err)
			return
		}

		jobs = append(jobs, j)
	}

	return
}

// Like NewGCSRegistry, but with more injected.
func newGCSRegistry(
	ctx context.Context,
	bucket gcs.Bucket,
	cryptoPassword string,
	deriver crypto.KeyDeriver,
	createCrypter func(key []byte) (crypto.Crypter, error),
	cryptoRandSrc io.Reader) (r Registry, crypter crypto.Crypter, err error) {
	// Find the previously-written encrypted marker object, if any.
	statReq := &gcs.StatObjectRequest{Name: markerObjectName}
	o, err := bucket.StatObject(ctx, statReq)

	if _, ok := err.(*gcs.NotFoundError); ok {
		err = nil
		o = nil
	}

	if err != nil {
		err = fmt.Errorf("StatObject: %v", err)
		return
	}

	// If the object was found, we must verify it is compatible.
	if o != nil {
		crypter, err = verifyCompatibleAndSetUpCrypter(
			o,
			cryptoPassword,
			deriver,
			createCrypter,
		)

		if err != nil {
			return
		}

		// All is good.
		r = &gcsRegistry{
			bucket: bucket,
		}

		return
	}

	// Otherwise, we want to claim this bucket. Encrypt some random data, base64
	// encode it, then write it out. Make sure to use a precondition to defeat
	// the race condition where another machine is doing the same simultaneously.

	// Generate a random salt.
	salt := make([]byte, 8)
	if _, err = io.ReadAtLeast(cryptoRandSrc, salt, len(salt)); err != nil {
		err = fmt.Errorf("Reading random bytes for salt: %v", err)
		return
	}

	// Derive a crypto key and create the crypter.
	cryptoKey := deriver.DeriveKey(cryptoPassword, salt)
	crypter, err = createCrypter(cryptoKey)
	if err != nil {
		err = fmt.Errorf("createCrypter: %v", err)
		return
	}

	// Create some plaintext.
	plaintext := make([]byte, 8)
	_, err = io.ReadAtLeast(cryptoRandSrc, plaintext, len(plaintext))
	if err != nil {
		err = fmt.Errorf("Reading random bytes for plaintext: %v", err)
		return
	}

	// Encrypt the plaintext.
	ciphertext, err := crypter.Encrypt(nil, plaintext)
	if err != nil {
		err = fmt.Errorf("Encrypt: %v", err)
		return
	}

	// Base-64 encode.
	encodedCiphertext := base64.StdEncoding.EncodeToString(ciphertext)
	encodedSalt := base64.StdEncoding.EncodeToString(salt)

	// Write out the marker object.
	var precond int64
	createReq := &gcs.CreateObjectRequest{
		Name: markerObjectName,
		Metadata: map[string]string{
			markerObjectMetadata_Salt:       encodedSalt,
			markerObjectMetadata_Ciphertext: encodedCiphertext,
		},
		Contents:               strings.NewReader(""),
		GenerationPrecondition: &precond,
	}

	_, err = bucket.CreateObject(ctx, createReq)
	if err != nil {
		err = fmt.Errorf("CreateObject: %v", err)
		return
	}

	// All is good.
	r = &gcsRegistry{
		bucket: bucket,
	}

	return
}

func verifyCompatibleAndSetUpCrypter(
	markerObject *gcs.Object,
	cryptoPassword string,
	deriver crypto.KeyDeriver,
	createCrypter func(key []byte) (crypto.Crypter, error)) (
	crypter crypto.Crypter,
	err error) {
	o := markerObject

	// Find the metadata keys.
	var passwordSaltBase64 string
	var ciphertextBase64 string
	var ok bool

	if passwordSaltBase64, ok = o.Metadata[markerObjectMetadata_Salt]; !ok {
		err = fmt.Errorf("Missing salt metadata key.")
		return
	}

	if ciphertextBase64, ok = o.Metadata[markerObjectMetadata_Ciphertext]; !ok {
		err = fmt.Errorf("Missing ciphertext metadata key.")
		return
	}

	// Base64-decode.
	passwordSalt, err := base64.StdEncoding.DecodeString(passwordSaltBase64)
	if err != nil {
		err = fmt.Errorf("Decoding password salt: %v", err)
		return
	}

	ciphertext, err := base64.StdEncoding.DecodeString(ciphertextBase64)
	if err != nil {
		err = fmt.Errorf("Decoding ciphertext: %v", err)
		return
	}

	// Derive a key and create a crypter.
	cryptoKey := deriver.DeriveKey(cryptoPassword, passwordSalt)
	if crypter, err = createCrypter(cryptoKey); err != nil {
		err = fmt.Errorf("createCrypter: %v", err)
		return
	}

	// Attempt to decrypt the ciphertext.
	if _, err = crypter.Decrypt(ciphertext); err != nil {
		// Special case: Did the crypter signal that the key was wrong?
		if _, ok := err.(*crypto.NotAuthenticError); ok {
			err = fmt.Errorf("The supplied password is incorrect.")
			return
		}

		// Generic error.
		err = fmt.Errorf("Decrypt: %v", err)
		return
	}

	return
}
<commit_msg>Tolerate gcsfuse directory markers.<commit_after>// Copyright 2015 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// 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 registry

import (
	"crypto/rand"
	"encoding/base64"
	"fmt"
	"io"
	"strings"
	"time"

	"github.com/jacobsa/comeback/internal/blob"
	"github.com/jacobsa/comeback/internal/crypto"
	"github.com/jacobsa/gcloud/gcs"
	"github.com/jacobsa/gcloud/gcs/gcsutil"
	"golang.org/x/net/context"
)

// Create a registry that stores data in the supplied GCS bucket, deriving a
// crypto key from the supplied password and ensuring that the bucket may not
// in the future be used with any other key and has not in the past, either.
// Return a crypter configured to use the key.
func NewGCSRegistry(
	ctx context.Context,
	bucket gcs.Bucket,
	cryptoPassword string,
	deriver crypto.KeyDeriver) (r Registry, crypter crypto.Crypter, err error) {
	return newGCSRegistry(
		ctx,
		bucket,
		cryptoPassword,
		deriver,
		crypto.NewCrypter,
		rand.Reader)
}

const (
	gcsJobKeyPrefix      = "jobs/"
	gcsMetadataKey_Name  = "job_name"
	gcsMetadataKey_Score = "hex_score"

	// Constants related to the "marker" object, used to ensure that the user has
	// the right password. See notes on gcsRegistry.
	markerObjectName                = "marker"
	markerObjectMetadata_Salt       = "base64_salt"
	markerObjectMetadata_Ciphertext = "base64_ciphertext"
)

// A registry that stores job records in a GCS bucket. Object names are of the
// form
//
//     <gcsJobKeyPrefix><time>
//
// where <time> is a time.Time with UTC location formatted according to
// time.RFC3339. Additional information is stored as object metadata fields
// keyed by the constants above. Metadata fields are used in preference to
// object content so that they are accessible on a ListObjects request.
//
// The bucket additionally contains a "marker" object (named by the constant
// markerObjectName) with metadata keys specifying a salt and a ciphertext for
// some random plaintext, generated ant written the first time the bucket is
// used. This marker allows us to verify that the user-provided crypto password
// is correct by deriving a key using the password and the salt and making sure
// that the ciphertext can be decrypted using that key.
type gcsRegistry struct {
	bucket gcs.Bucket
}

func (r *gcsRegistry) RecordBackup(
	ctx context.Context,
	j CompletedJob) (err error) {
	// Write an object to the bucket. On the small change that the time collides
	// (or we've done something dumb like use the zero time), use a generation
	// precondition to ensure we don't overwrite anything.
	var precond int64
	formattedTime := j.StartTime.UTC().Format(time.RFC3339)
	req := &gcs.CreateObjectRequest{
		Name:                   gcsJobKeyPrefix + formattedTime,
		Contents:               strings.NewReader(""),
		GenerationPrecondition: &precond,

		Metadata: map[string]string{
			gcsMetadataKey_Name:  j.Name,
			gcsMetadataKey_Score: j.Score.Hex(),
		},
	}

	_, err = r.bucket.CreateObject(ctx, req)
	if err != nil {
		err = fmt.Errorf("CreateObject: %v", err)
		return
	}

	return
}

func parseObjectAsJob(o *gcs.Object) (j CompletedJob, err error) {
	// Extract the formatted time.
	if !strings.HasPrefix(o.Name, gcsJobKeyPrefix) {
		err = fmt.Errorf("Unexpected object name: \"%s\"", o.Name)
		return
	}

	formattedTime := strings.TrimPrefix(o.Name, gcsJobKeyPrefix)

	// Parse it.
	j.StartTime, err = time.Parse(time.RFC3339, formattedTime)
	if err != nil {
		err = fmt.Errorf("Parsing time \"%s\": %v", formattedTime, err)
		return
	}

	// Extract the job name.
	{
		var ok bool
		if j.Name, ok = o.Metadata[gcsMetadataKey_Name]; !ok {
			err = fmt.Errorf(
				"Object with name \"%s\" is missing metadata key %s",
				o.Name,
				gcsMetadataKey_Name)

			return
		}
	}

	// Extract the score.
	{
		hexScore, ok := o.Metadata[gcsMetadataKey_Score]
		if !ok {
			err = fmt.Errorf(
				"Object with name \"%s\" is missing metadata key %s",
				o.Name,
				gcsMetadataKey_Score)

			return
		}

		j.Score, err = blob.ParseHexScore(hexScore)
		if err != nil {
			err = fmt.Errorf("Parsing hex score \"%s\": %v", hexScore, err)
			return
		}
	}

	return
}

func (r *gcsRegistry) ListBackups(
	ctx context.Context) (jobs []CompletedJob, err error) {
	// List all of the objects with the appropriate name prefix.
	req := &gcs.ListObjectsRequest{
		Prefix: gcsJobKeyPrefix,
	}

	objects, _, err := gcsutil.ListAll(ctx, r.bucket, req)
	if err != nil {
		err = fmt.Errorf("gcsutil.ListAll: %v", err)
		return
	}

	// Process each object.
	for _, o := range objects {
		// Skip the object whose name is exactly the prefix, if any. This lets us
		// tolerate a "directory marker" with gcsfuse.
		if o.Name == gcsJobKeyPrefix {
			continue
		}

		// Parse.
		var j CompletedJob
		j, err = parseObjectAsJob(o)
		if err != nil {
			err = fmt.Errorf("parseObjectAsJob: %v", err)
			return
		}

		jobs = append(jobs, j)
	}

	return
}

// Like NewGCSRegistry, but with more injected.
func newGCSRegistry(
	ctx context.Context,
	bucket gcs.Bucket,
	cryptoPassword string,
	deriver crypto.KeyDeriver,
	createCrypter func(key []byte) (crypto.Crypter, error),
	cryptoRandSrc io.Reader) (r Registry, crypter crypto.Crypter, err error) {
	// Find the previously-written encrypted marker object, if any.
	statReq := &gcs.StatObjectRequest{Name: markerObjectName}
	o, err := bucket.StatObject(ctx, statReq)

	if _, ok := err.(*gcs.NotFoundError); ok {
		err = nil
		o = nil
	}

	if err != nil {
		err = fmt.Errorf("StatObject: %v", err)
		return
	}

	// If the object was found, we must verify it is compatible.
	if o != nil {
		crypter, err = verifyCompatibleAndSetUpCrypter(
			o,
			cryptoPassword,
			deriver,
			createCrypter,
		)

		if err != nil {
			return
		}

		// All is good.
		r = &gcsRegistry{
			bucket: bucket,
		}

		return
	}

	// Otherwise, we want to claim this bucket. Encrypt some random data, base64
	// encode it, then write it out. Make sure to use a precondition to defeat
	// the race condition where another machine is doing the same simultaneously.

	// Generate a random salt.
	salt := make([]byte, 8)
	if _, err = io.ReadAtLeast(cryptoRandSrc, salt, len(salt)); err != nil {
		err = fmt.Errorf("Reading random bytes for salt: %v", err)
		return
	}

	// Derive a crypto key and create the crypter.
	cryptoKey := deriver.DeriveKey(cryptoPassword, salt)
	crypter, err = createCrypter(cryptoKey)
	if err != nil {
		err = fmt.Errorf("createCrypter: %v", err)
		return
	}

	// Create some plaintext.
	plaintext := make([]byte, 8)
	_, err = io.ReadAtLeast(cryptoRandSrc, plaintext, len(plaintext))
	if err != nil {
		err = fmt.Errorf("Reading random bytes for plaintext: %v", err)
		return
	}

	// Encrypt the plaintext.
	ciphertext, err := crypter.Encrypt(nil, plaintext)
	if err != nil {
		err = fmt.Errorf("Encrypt: %v", err)
		return
	}

	// Base-64 encode.
	encodedCiphertext := base64.StdEncoding.EncodeToString(ciphertext)
	encodedSalt := base64.StdEncoding.EncodeToString(salt)

	// Write out the marker object.
	var precond int64
	createReq := &gcs.CreateObjectRequest{
		Name: markerObjectName,
		Metadata: map[string]string{
			markerObjectMetadata_Salt:       encodedSalt,
			markerObjectMetadata_Ciphertext: encodedCiphertext,
		},
		Contents:               strings.NewReader(""),
		GenerationPrecondition: &precond,
	}

	_, err = bucket.CreateObject(ctx, createReq)
	if err != nil {
		err = fmt.Errorf("CreateObject: %v", err)
		return
	}

	// All is good.
	r = &gcsRegistry{
		bucket: bucket,
	}

	return
}

func verifyCompatibleAndSetUpCrypter(
	markerObject *gcs.Object,
	cryptoPassword string,
	deriver crypto.KeyDeriver,
	createCrypter func(key []byte) (crypto.Crypter, error)) (
	crypter crypto.Crypter,
	err error) {
	o := markerObject

	// Find the metadata keys.
	var passwordSaltBase64 string
	var ciphertextBase64 string
	var ok bool

	if passwordSaltBase64, ok = o.Metadata[markerObjectMetadata_Salt]; !ok {
		err = fmt.Errorf("Missing salt metadata key.")
		return
	}

	if ciphertextBase64, ok = o.Metadata[markerObjectMetadata_Ciphertext]; !ok {
		err = fmt.Errorf("Missing ciphertext metadata key.")
		return
	}

	// Base64-decode.
	passwordSalt, err := base64.StdEncoding.DecodeString(passwordSaltBase64)
	if err != nil {
		err = fmt.Errorf("Decoding password salt: %v", err)
		return
	}

	ciphertext, err := base64.StdEncoding.DecodeString(ciphertextBase64)
	if err != nil {
		err = fmt.Errorf("Decoding ciphertext: %v", err)
		return
	}

	// Derive a key and create a crypter.
	cryptoKey := deriver.DeriveKey(cryptoPassword, passwordSalt)
	if crypter, err = createCrypter(cryptoKey); err != nil {
		err = fmt.Errorf("createCrypter: %v", err)
		return
	}

	// Attempt to decrypt the ciphertext.
	if _, err = crypter.Decrypt(ciphertext); err != nil {
		// Special case: Did the crypter signal that the key was wrong?
		if _, ok := err.(*crypto.NotAuthenticError); ok {
			err = fmt.Errorf("The supplied password is incorrect.")
			return
		}

		// Generic error.
		err = fmt.Errorf("Decrypt: %v", err)
		return
	}

	return
}
<|endoftext|>


<commit_before>package boomer

import "testing"

func TestRound(t *testing.T) {

	if int(round(float64(147.5002), .5, -1)) != 150 {
		t.Error("147.5002 should be rounded to 150")
	}

	if int(round(float64(3432.5002), .5, -2)) != 3400 {
		t.Error("3432.5002 should be rounded to 3400")
	}

	roundOne := round(float64(58760.5002), .5, -3)
	roundTwo := round(float64(58960.6003), .5, -3)
	if roundOne != roundTwo {
		t.Error("round(58760.5002) should be equal to round(58960.6003)")
	}

	roundOne = round(float64(58360.5002), .5, -3)
	roundTwo = round(float64(58460.6003), .5, -3)
	if roundOne != roundTwo {
		t.Error("round(58360.5002) should be equal to round(58460.6003)")
	}

	roundOne = round(float64(58360), .5, -3)
	roundTwo = round(float64(58460), .5, -3)
	if roundOne != roundTwo {
		t.Error("round(58360) should be equal to round(58460)")
	}

}
<commit_msg>add test for utils<commit_after>package boomer

import (
	"os"
	"regexp"
	"testing"
)

func TestRound(t *testing.T) {

	if int(round(float64(147.5002), .5, -1)) != 150 {
		t.Error("147.5002 should be rounded to 150")
	}

	if int(round(float64(3432.5002), .5, -2)) != 3400 {
		t.Error("3432.5002 should be rounded to 3400")
	}

	roundOne := round(float64(58760.5002), .5, -3)
	roundTwo := round(float64(58960.6003), .5, -3)
	if roundOne != roundTwo {
		t.Error("round(58760.5002) should be equal to round(58960.6003)")
	}

	roundOne = round(float64(58360.5002), .5, -3)
	roundTwo = round(float64(58460.6003), .5, -3)
	if roundOne != roundTwo {
		t.Error("round(58360.5002) should be equal to round(58460.6003)")
	}

	roundOne = round(float64(58360), .5, -3)
	roundTwo = round(float64(58460), .5, -3)
	if roundOne != roundTwo {
		t.Error("round(58360) should be equal to round(58460)")
	}

}

func TestMD5(t *testing.T) {
	hashValue := MD5("Hello", "World!")
	if hashValue != "06e0e6637d27b2622ab52022db713ce2" {
		t.Error("Expected: 06e0e6637d27b2622ab52022db713ce2, Got: ", hashValue)
	}
}

func TestGetNodeID(t *testing.T) {
	nodeID := getNodeID()
	hostname, _ := os.Hostname()
	regex := hostname + "_[a-f0-9]{32}$"
	validNodeID := regexp.MustCompile(regex)
	if !validNodeID.MatchString(nodeID) {
		t.Error("Invalid format of nodeID")
	}
}
<|endoftext|>


<commit_before>package main

import (
	"log"
	"time"

	"buildblast/lib/game"
)

type clientResponse struct {
	client *Client
	isNew  bool
}

type disconnectingClient struct {
	id     string
	reason string
}

type Game struct {
	clients map[string]*Client

	clientRequests       chan string
	clientResponses      chan clientResponse
	disconnectingClients chan disconnectingClient

	world *game.World
}

func NewGame() *Game {
	g := new(Game)

	g.clients = make(map[string]*Client, 0)

	g.clientRequests = make(chan string)
	g.clientResponses = make(chan clientResponse)
	g.disconnectingClients = make(chan disconnectingClient)

	g.world = game.NewWorld(float64(time.Now().Unix()))

	return g
}

// Thread safe, blocking
// Returns a client with the given ID. If there is no client with the given
// id, creates a new client with the given ID, and adds it to the game.
func (g *Game) clientWithID(id string) (client *Client, isNew bool) {
	g.clientRequests <- id
	resp := <-g.clientResponses
	return resp.client, resp.isNew
}

func (g *Game) handleClientRequests() {
	select {
	case id := <-g.clientRequests:
		client := g.clients[id]
		isNew := false
		if client == nil {
			client = NewClient(id)
			g.clients[id] = client
			client.Connected(g, g.world)
			g.Announce(id + " has joined the game!")
			isNew = true
		}
		g.clientResponses <- clientResponse{
			client: client,
			isNew:  isNew,
		}
	default:
		return
	}
}

// Thread safe
func (g *Game) Disconnect(id, reason string) {
	g.disconnectingClients <- disconnectingClient{
		id:     id,
		reason: reason,
	}
}

func (g *Game) handleDisconnectingClients() {
	select {
	case disconnecting := <-g.disconnectingClients:
		g.disconnect(disconnecting.id, disconnecting.reason)
	}
}

// Not thread safe
func (g *Game) disconnect(id, reason string) {
	client := g.clients[id]
	if client == nil {
		log.Println("[WARN] Attempt to disconnect client who is not connected.")
		return
	}
	delete(g.clients, id)

	client.Disconnected(g, g.world)

	g.Announce(id + " has left the game: " + reason)
}

func (g *Game) Announce(message string) {
	g.Chat("SERVER", message)
}

func (g *Game) Chat(user string, message string) {
	log.Println("[CHAT]", user+":", message)
	g.Broadcast(&MsgChat{
		DisplayName: user,
		Message:     message,
	})
}

func (g *Game) Broadcast(m Message) {
	for _, c := range g.clients {
		c.Send(m)
	}
}

func (g *Game) BroadcastLossy(m Message) {
	for _, c := range g.clients {
		c.SendLossy(m)
	}
}

func (g *Game) Run() {
	updateTicker := time.Tick(time.Second / 60)
	for {
		<-updateTicker
		g.Tick()
	}
}

func (g *Game) Tick() {
	g.handleClientRequests()

	g.world.Tick()
	for _, c := range g.clients {
		c.Tick(g, g.world)
	}
}

func (g *Game) EntityCreated(id game.EntityID, entity game.Entity) {}

func (g *Game) EntityDamaged(id game.EntityID, entity game.Entity) {
	pos, posTime := entity.Pos()

	g.Broadcast(&MsgEntityState{
		Timestamp: posTime,
		ID:        id,
		Pos:       pos,
		Vy:        entity.Vy(),
		Look:      entity.Look(),
		Health:    entity.Health(),
	})
}

func (g *Game) EntityDied(id game.EntityID, entity game.Entity, killer string) {
	g.Announce(killer + " killed " + string(id))

	pos, posTime := entity.Pos()

	g.Broadcast(&MsgEntityState{
		Timestamp: posTime,
		ID:        id,
		Pos:       pos,
		Vy:        entity.Vy(),
		Look:      entity.Look(),
		Health:    entity.Health(),
	})
}

func (g *Game) EntityRemoved(id game.EntityID) {}
<commit_msg>Less redundancy = good.<commit_after>package main

import (
	"log"
	"time"

	"buildblast/lib/game"
)

type clientResponse struct {
	client *Client
	isNew  bool
}

type disconnectingClient struct {
	id     string
	reason string
}

type Game struct {
	clients map[string]*Client

	clientRequests       chan string
	clientResponses      chan clientResponse
	disconnectingClients chan disconnectingClient

	world *game.World
}

func NewGame() *Game {
	g := new(Game)

	g.clients = make(map[string]*Client, 0)

	g.clientRequests = make(chan string)
	g.clientResponses = make(chan clientResponse)
	g.disconnectingClients = make(chan disconnectingClient)

	g.world = game.NewWorld(float64(time.Now().Unix()))

	return g
}

// Thread safe, blocking
// Returns a client with the given ID. If there is no client with the given
// id, creates a new client with the given ID, and adds it to the game.
func (g *Game) clientWithID(id string) (client *Client, isNew bool) {
	g.clientRequests <- id
	resp := <-g.clientResponses
	return resp.client, resp.isNew
}

func (g *Game) handleClientRequests() {
	select {
	case id := <-g.clientRequests:
		client := g.clients[id]
		isNew := false
		if client == nil {
			client = NewClient(id)
			g.clients[id] = client
			client.Connected(g, g.world)
			g.Announce(id + " has joined the game!")
			isNew = true
		}
		g.clientResponses <- clientResponse{
			client: client,
			isNew:  isNew,
		}
	default:
		return
	}
}

// Thread safe
func (g *Game) Disconnect(id, reason string) {
	g.disconnectingClients <- disconnectingClient{
		id:     id,
		reason: reason,
	}
}

func (g *Game) handleDisconnectingClients() {
	select {
	case disconnecting := <-g.disconnectingClients:
		g.disconnect(disconnecting.id, disconnecting.reason)
	}
}

// Not thread safe
func (g *Game) disconnect(id, reason string) {
	client := g.clients[id]
	if client == nil {
		log.Println("[WARN] Attempt to disconnect client who is not connected.")
		return
	}
	delete(g.clients, id)

	client.Disconnected(g, g.world)

	g.Announce(id + " has left the game: " + reason)
}

func (g *Game) Announce(message string) {
	g.Chat("SERVER", message)
}

func (g *Game) Chat(user string, message string) {
	log.Println("[CHAT]", user+":", message)
	g.Broadcast(&MsgChat{
		DisplayName: user,
		Message:     message,
	})
}

func (g *Game) Broadcast(m Message) {
	for _, c := range g.clients {
		c.Send(m)
	}
}

func (g *Game) BroadcastLossy(m Message) {
	for _, c := range g.clients {
		c.SendLossy(m)
	}
}

func (g *Game) Run() {
	updateTicker := time.Tick(time.Second / 60)
	for {
		<-updateTicker
		g.Tick()
	}
}

func (g *Game) Tick() {
	g.handleClientRequests()

	g.world.Tick()
	for _, c := range g.clients {
		c.Tick(g, g.world)
	}
}

func (g *Game) EntityCreated(id game.EntityID, entity game.Entity) {}

func (g *Game) EntityDamaged(id game.EntityID, entity game.Entity) {
	pos, posTime := entity.Pos()
	g.Broadcast(&MsgEntityState{
		Timestamp: posTime,
		ID:        id,
		Pos:       pos,
		Vy:        entity.Vy(),
		Look:      entity.Look(),
		Health:    entity.Health(),
	})
}

func (g *Game) EntityDied(id game.EntityID, entity game.Entity, killer string) {
	g.Announce(killer + " killed " + string(id))
	g.EntityDamaged(id, entity)
}

func (g *Game) EntityRemoved(id game.EntityID) {}
<|endoftext|>