<commit_before>// Copyright 2016 Joel Scoble and The JoeFriday 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 utilization handles processing of CPU utilization information.
// This information is calculated using the differences of two CPU stats
// snapshots and represented as a percentage.
package utilization

import (
	"io"
	"sync"
	"time"

	"github.com/SermoDigital/helpers"
	joe "github.com/mohae/joefriday"
	"github.com/mohae/joefriday/cpu/stats"
)

// Profiler is used to process the /proc/stats file and calculate Utilization
// information.
type Profiler struct {
	*stats.Profiler
	prior stats.Stats
}

// Returns an initialized Profiler; ready to use.
func New() (prof *Profiler, err error) {
	p, err := stats.New()
	if err != nil {
		return nil, err
	}
	s, err := p.Get()
	if err != nil {
		return nil, err
	}
	return &Profiler{Profiler: p, prior: *s}, nil
}

// Get returns the cpu utilization.  Utilization calculations requires two
// pieces of data.  This func gets a snapshot of /proc/stat, sleeps for a
// second, takes another snapshot and calcualtes the utilization from the
// two snapshots.  If ongoing utilitzation information is desired, the
// Ticker should be used; it's better suited for ongoing utilization
// information.
//
// TODO: should this be changed so that this calculates utilization since
// last time the stats were obtained.  If there aren't pre-existing stats
// it would get current utilization (which may be a separate method (or
// should be?)).  Also: rethink locking.
func (prof *Profiler) Get() (u *Utilization, err error) {
	err = prof.Reset()
	if err != nil {
		return nil, err
	}
	stat, err := prof.Profiler.Get()
	if err != nil {
		return nil, err
	}
	u = prof.calculateUtilization(stat)
	prof.prior = *stat
	return u, nil
}

var std *Profiler
var stdMu sync.Mutex

// Get returns the current cpu utilization using the package's global Profiler.
func Get() (*Utilization, error) {
	stdMu.Lock()
	defer stdMu.Unlock()
	if std == nil {
		var err error
		std, err = New()
		if err != nil {
			return nil, err
		}
	}
	return std.Get()
}

// Ticker processes CPU utilization information on a ticker.  The generated
// utilization data is sent to the out channel.  Any errors encountered are
// sent to the errs.  Processing ends when a done signal is received.
//
// It is the callers responsibility to close the done and errs channels.
//
// TODO: better handle errors, e.g. restore cur from prior so that there
// isn't the possibility of temporarily having bad data, just a missed
// collection interval.
func (prof *Profiler) Ticker(interval time.Duration, out chan *Utilization, done chan struct{}, errs chan error) {
	ticker := time.NewTicker(interval)
	defer ticker.Stop()
	defer close(out)
	// predeclare some vars
	var (
		i, j, pos, fieldNum int
		n                   uint64
		v                   byte
		stop                bool
		err                 error
		cur                 stats.Stats
		stat                stats.Stat
	)
	// ticker
tick:
	for {
		select {
		case <-done:
			return
		case <-ticker.C:
			cur.Timestamp = time.Now().UTC().UnixNano()
			err = prof.Reset()
			if err != nil {
				errs <- joe.Error{Type: "cpu", Op: "utilization ticker: seek /proc/stat", Err: err}
				continue tick
			}
			cur.CPU = cur.CPU[:0]
			// read each line until eof
			for {
				prof.Line, err = prof.Buf.ReadSlice('\n')
				if err != nil {
					if err == io.EOF {
						break
					}
					errs <- joe.Error{Type: "cpu stat", Op: "reading /proc/stat output", Err: err}
					break
				}
				// Get everything up to the first space, this is the key.  Not all keys are processed.
				for i, v = range prof.Line {
					if v == 0x20 {
						prof.Val = prof.Line[:i]
						pos = i + 1
						break
					}
				}
				// skip the intr line
				if prof.Val[0] == 'i' {
					continue
				}
				if prof.Val[0] == 'c' {
					if prof.Val[1] == 'p' { // process CPU
						stat.ID = string(prof.Val[:])
						j = 0
						// skip over any remaining spaces
						for i, v = range prof.Line[pos:] {
							if v != 0x20 {
								break
							}
							j++
						}
						fieldNum = 0
						pos, j = j+pos, j+pos
						// space is the field separator
						for i, v = range prof.Line[pos:] {
							if v == '\n' {
								stop = true
							}
							if v == 0x20 || stop {
								fieldNum++
								n, err = helpers.ParseUint(prof.Line[j : pos+i])
								if err != nil {
									errs <- joe.Error{Type: "cpu stat", Op: "convert cpu data", Err: err}
									continue
								}
								j = pos + i + 1
								if fieldNum < 6 {
									if fieldNum < 4 {
										if fieldNum == 1 {
											stat.User = int64(n)
											continue
										}
										if fieldNum == 2 {
											stat.Nice = int64(n)
											continue
										}
										stat.System = int64(n) // 3
										continue
									}
									if fieldNum == 4 {
										stat.Idle = int64(n)
										continue
									}
									stat.IOWait = int64(n) // 5
									continue
								}
								if fieldNum < 8 {
									if fieldNum == 6 {
										stat.IRQ = int64(n)
										continue
									}
									stat.SoftIRQ = int64(n) // 7
									continue
								}
								if fieldNum == 8 {
									stat.Steal = int64(n)
									continue
								}
								if fieldNum == 9 {
									stat.Quest = int64(n)
									continue
								}
								stat.QuestNice = int64(n) // 10
							}
						}
						cur.CPU = append(cur.CPU, stat)
						stop = false
						continue
					}
					// Otherwise it's ctxt info; rest of the line is the data.
					n, err = helpers.ParseUint(prof.Line[pos : len(prof.Line)-1])
					if err != nil {
						errs <- joe.Error{Type: "cpu stat", Op: "convert ctxt data", Err: err}
						continue
					}
					cur.Ctxt = int64(n)
					continue
				}
				if prof.Val[0] == 'b' {
					// rest of the line is the data
					n, err = helpers.ParseUint(prof.Line[pos : len(prof.Line)-1])
					if err != nil {
						errs <- joe.Error{Type: "cpu stat", Op: "convert btime data", Err: err}
						continue
					}
					cur.BTime = int64(n)
					continue
				}
				if prof.Val[0] == 'p' && prof.Val[4] == 'e' { // processes info
					// rest of the line is the data
					n, err = helpers.ParseUint(prof.Line[pos : len(prof.Line)-1])
					if err != nil {
						errs <- joe.Error{Type: "cpu stat", Op: "convert processes data", Err: err}
						continue
					}
					cur.Processes = int64(n)
					continue
				}
			}
			out <- prof.calculateUtilization(&cur)
			prof.prior.Ctxt = cur.Ctxt
			prof.prior.BTime = cur.BTime
			prof.prior.Processes = cur.Processes
			if len(prof.prior.CPU) != len(cur.CPU) {
				prof.prior.CPU = make([]stats.Stat, len(cur.CPU))
			}
			copy(prof.prior.CPU, cur.CPU)
		}
	}
}

// Ticker gathers information on a ticker using the specified interval.
// This uses a local Profiler as using the global doesn't make sense for
// an ongoing ticker.
func Ticker(interval time.Duration, out chan *Utilization, done chan struct{}, errs chan error) {
	prof, err := New()
	if err != nil {
		errs <- err
		close(out)
		return
	}
	prof.Ticker(interval, out, done, errs)
}

// utilizaton =
//   ()(Δuser + Δnice + Δsystem)/(Δuser+Δnice+Δsystem+Δidle)) * CLK_TCK
func (prof *Profiler) calculateUtilization(s2 *stats.Stats) *Utilization {
	u := &Utilization{
		Timestamp:  s2.Timestamp,
		BTimeDelta: int32(s2.Timestamp/1000000000 - s2.BTime),
		CtxtDelta:  s2.Ctxt - prof.prior.Ctxt,
		Processes:  int32(s2.Processes),
		CPU:        make([]Util, len(s2.CPU)),
	}
	var dUser, dNice, dSys, dIdle, tot float32
	// Rest of the calculations are per core
	for i := 0; i < len(s2.CPU); i++ {
		v := Util{ID: s2.CPU[i].ID}
		dUser = float32(s2.CPU[i].User - prof.prior.CPU[i].User)
		dNice = float32(s2.CPU[i].Nice - prof.prior.CPU[i].Nice)
		dSys = float32(s2.CPU[i].System - prof.prior.CPU[i].System)
		dIdle = float32(s2.CPU[i].Idle - prof.prior.CPU[i].Idle)
		tot = dUser + dNice + dSys + dIdle
		v.Usage = (dUser + dNice + dSys) / tot * float32(s2.ClkTck)
		v.User = dUser / tot * float32(s2.ClkTck)
		v.Nice = dNice / tot * float32(s2.ClkTck)
		v.System = dSys / tot * float32(s2.ClkTck)
		v.Idle = dIdle / tot * float32(s2.ClkTck)
		v.IOWait = float32(s2.CPU[i].IOWait-prof.prior.CPU[i].IOWait) / tot * float32(s2.ClkTck)
		u.CPU[i] = v
	}
	return u
}

// Utilization holds information about cpu utilization.
type Utilization struct {
	Timestamp int64 `json:"timestamp"`
	// time since last reboot, in seconds
	BTimeDelta int32 `json:"btime_delta"`
	// context switches since last snapshot
	CtxtDelta int64 `json:"ctxt_delta"`
	// current number of Processes
	Processes int32 `json:"processes"`
	// cpu specific utilization information
	CPU []Util `json:"cpu"`
}

// Util holds utilization information, as percentages, for a CPU.
type Util struct {
	ID     string  `json:"id"`
	Usage  float32 `json:"total"`
	User   float32 `json:"user"`
	Nice   float32 `json:"nice"`
	System float32 `json:"system"`
	Idle   float32 `json:"idle"`
	IOWait float32 `json:"io_wait"`
}
<commit_msg>elide unnecessary reset() call<commit_after>// Copyright 2016 Joel Scoble and The JoeFriday 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 utilization handles processing of CPU utilization information.
// This information is calculated using the differences of two CPU stats
// snapshots and represented as a percentage.
package utilization

import (
	"io"
	"sync"
	"time"

	"github.com/SermoDigital/helpers"
	joe "github.com/mohae/joefriday"
	"github.com/mohae/joefriday/cpu/stats"
)

// Profiler is used to process the /proc/stats file and calculate Utilization
// information.
type Profiler struct {
	*stats.Profiler
	prior stats.Stats
}

// Returns an initialized Profiler; ready to use.
func New() (prof *Profiler, err error) {
	p, err := stats.New()
	if err != nil {
		return nil, err
	}
	s, err := p.Get()
	if err != nil {
		return nil, err
	}
	return &Profiler{Profiler: p, prior: *s}, nil
}

// Get returns the cpu utilization.  Utilization calculations requires two
// pieces of data.  This func gets a snapshot of /proc/stat, sleeps for a
// second, takes another snapshot and calcualtes the utilization from the
// two snapshots.  If ongoing utilitzation information is desired, the
// Ticker should be used; it's better suited for ongoing utilization
// information.
//
// TODO: should this be changed so that this calculates utilization since
// last time the stats were obtained.  If there aren't pre-existing stats
// it would get current utilization (which may be a separate method (or
// should be?)).  Also: rethink locking.
func (prof *Profiler) Get() (u *Utilization, err error) {
	stat, err := prof.Profiler.Get()
	if err != nil {
		return nil, err
	}
	u = prof.calculateUtilization(stat)
	prof.prior = *stat
	return u, nil
}

var std *Profiler
var stdMu sync.Mutex

// Get returns the current cpu utilization using the package's global Profiler.
func Get() (*Utilization, error) {
	stdMu.Lock()
	defer stdMu.Unlock()
	if std == nil {
		var err error
		std, err = New()
		if err != nil {
			return nil, err
		}
	}
	return std.Get()
}

// Ticker processes CPU utilization information on a ticker.  The generated
// utilization data is sent to the out channel.  Any errors encountered are
// sent to the errs.  Processing ends when a done signal is received.
//
// It is the callers responsibility to close the done and errs channels.
//
// TODO: better handle errors, e.g. restore cur from prior so that there
// isn't the possibility of temporarily having bad data, just a missed
// collection interval.
func (prof *Profiler) Ticker(interval time.Duration, out chan *Utilization, done chan struct{}, errs chan error) {
	ticker := time.NewTicker(interval)
	defer ticker.Stop()
	defer close(out)
	// predeclare some vars
	var (
		i, j, pos, fieldNum int
		n                   uint64
		v                   byte
		stop                bool
		err                 error
		cur                 stats.Stats
		stat                stats.Stat
	)
	// ticker
tick:
	for {
		select {
		case <-done:
			return
		case <-ticker.C:
			cur.Timestamp = time.Now().UTC().UnixNano()
			err = prof.Reset()
			if err != nil {
				errs <- joe.Error{Type: "cpu", Op: "utilization ticker: seek /proc/stat", Err: err}
				continue tick
			}
			cur.CPU = cur.CPU[:0]
			// read each line until eof
			for {
				prof.Line, err = prof.Buf.ReadSlice('\n')
				if err != nil {
					if err == io.EOF {
						break
					}
					errs <- joe.Error{Type: "cpu stat", Op: "reading /proc/stat output", Err: err}
					break
				}
				// Get everything up to the first space, this is the key.  Not all keys are processed.
				for i, v = range prof.Line {
					if v == 0x20 {
						prof.Val = prof.Line[:i]
						pos = i + 1
						break
					}
				}
				// skip the intr line
				if prof.Val[0] == 'i' {
					continue
				}
				if prof.Val[0] == 'c' {
					if prof.Val[1] == 'p' { // process CPU
						stat.ID = string(prof.Val[:])
						j = 0
						// skip over any remaining spaces
						for i, v = range prof.Line[pos:] {
							if v != 0x20 {
								break
							}
							j++
						}
						fieldNum = 0
						pos, j = j+pos, j+pos
						// space is the field separator
						for i, v = range prof.Line[pos:] {
							if v == '\n' {
								stop = true
							}
							if v == 0x20 || stop {
								fieldNum++
								n, err = helpers.ParseUint(prof.Line[j : pos+i])
								if err != nil {
									errs <- joe.Error{Type: "cpu stat", Op: "convert cpu data", Err: err}
									continue
								}
								j = pos + i + 1
								if fieldNum < 6 {
									if fieldNum < 4 {
										if fieldNum == 1 {
											stat.User = int64(n)
											continue
										}
										if fieldNum == 2 {
											stat.Nice = int64(n)
											continue
										}
										stat.System = int64(n) // 3
										continue
									}
									if fieldNum == 4 {
										stat.Idle = int64(n)
										continue
									}
									stat.IOWait = int64(n) // 5
									continue
								}
								if fieldNum < 8 {
									if fieldNum == 6 {
										stat.IRQ = int64(n)
										continue
									}
									stat.SoftIRQ = int64(n) // 7
									continue
								}
								if fieldNum == 8 {
									stat.Steal = int64(n)
									continue
								}
								if fieldNum == 9 {
									stat.Quest = int64(n)
									continue
								}
								stat.QuestNice = int64(n) // 10
							}
						}
						cur.CPU = append(cur.CPU, stat)
						stop = false
						continue
					}
					// Otherwise it's ctxt info; rest of the line is the data.
					n, err = helpers.ParseUint(prof.Line[pos : len(prof.Line)-1])
					if err != nil {
						errs <- joe.Error{Type: "cpu stat", Op: "convert ctxt data", Err: err}
						continue
					}
					cur.Ctxt = int64(n)
					continue
				}
				if prof.Val[0] == 'b' {
					// rest of the line is the data
					n, err = helpers.ParseUint(prof.Line[pos : len(prof.Line)-1])
					if err != nil {
						errs <- joe.Error{Type: "cpu stat", Op: "convert btime data", Err: err}
						continue
					}
					cur.BTime = int64(n)
					continue
				}
				if prof.Val[0] == 'p' && prof.Val[4] == 'e' { // processes info
					// rest of the line is the data
					n, err = helpers.ParseUint(prof.Line[pos : len(prof.Line)-1])
					if err != nil {
						errs <- joe.Error{Type: "cpu stat", Op: "convert processes data", Err: err}
						continue
					}
					cur.Processes = int64(n)
					continue
				}
			}
			out <- prof.calculateUtilization(&cur)
			prof.prior.Ctxt = cur.Ctxt
			prof.prior.BTime = cur.BTime
			prof.prior.Processes = cur.Processes
			if len(prof.prior.CPU) != len(cur.CPU) {
				prof.prior.CPU = make([]stats.Stat, len(cur.CPU))
			}
			copy(prof.prior.CPU, cur.CPU)
		}
	}
}

// Ticker gathers information on a ticker using the specified interval.
// This uses a local Profiler as using the global doesn't make sense for
// an ongoing ticker.
func Ticker(interval time.Duration, out chan *Utilization, done chan struct{}, errs chan error) {
	prof, err := New()
	if err != nil {
		errs <- err
		close(out)
		return
	}
	prof.Ticker(interval, out, done, errs)
}

// utilizaton =
//   ()(Δuser + Δnice + Δsystem)/(Δuser+Δnice+Δsystem+Δidle)) * CLK_TCK
func (prof *Profiler) calculateUtilization(s2 *stats.Stats) *Utilization {
	u := &Utilization{
		Timestamp:  s2.Timestamp,
		BTimeDelta: int32(s2.Timestamp/1000000000 - s2.BTime),
		CtxtDelta:  s2.Ctxt - prof.prior.Ctxt,
		Processes:  int32(s2.Processes),
		CPU:        make([]Util, len(s2.CPU)),
	}
	var dUser, dNice, dSys, dIdle, tot float32
	// Rest of the calculations are per core
	for i := 0; i < len(s2.CPU); i++ {
		v := Util{ID: s2.CPU[i].ID}
		dUser = float32(s2.CPU[i].User - prof.prior.CPU[i].User)
		dNice = float32(s2.CPU[i].Nice - prof.prior.CPU[i].Nice)
		dSys = float32(s2.CPU[i].System - prof.prior.CPU[i].System)
		dIdle = float32(s2.CPU[i].Idle - prof.prior.CPU[i].Idle)
		tot = dUser + dNice + dSys + dIdle
		v.Usage = (dUser + dNice + dSys) / tot * float32(s2.ClkTck)
		v.User = dUser / tot * float32(s2.ClkTck)
		v.Nice = dNice / tot * float32(s2.ClkTck)
		v.System = dSys / tot * float32(s2.ClkTck)
		v.Idle = dIdle / tot * float32(s2.ClkTck)
		v.IOWait = float32(s2.CPU[i].IOWait-prof.prior.CPU[i].IOWait) / tot * float32(s2.ClkTck)
		u.CPU[i] = v
	}
	return u
}

// Utilization holds information about cpu utilization.
type Utilization struct {
	Timestamp int64 `json:"timestamp"`
	// time since last reboot, in seconds
	BTimeDelta int32 `json:"btime_delta"`
	// context switches since last snapshot
	CtxtDelta int64 `json:"ctxt_delta"`
	// current number of Processes
	Processes int32 `json:"processes"`
	// cpu specific utilization information
	CPU []Util `json:"cpu"`
}

// Util holds utilization information, as percentages, for a CPU.
type Util struct {
	ID     string  `json:"id"`
	Usage  float32 `json:"total"`
	User   float32 `json:"user"`
	Nice   float32 `json:"nice"`
	System float32 `json:"system"`
	Idle   float32 `json:"idle"`
	IOWait float32 `json:"io_wait"`
}
<|endoftext|>


<commit_before>package voting

import (
	"golang.org/x/net/context"

	"chain/core/appdb"
	"chain/core/txbuilder"
	"chain/cos/bc"
	"chain/cos/txscript"
	"chain/errors"
)

// RightIssuance builds a txbuilder Receiver issuance for an asset that
// is being issued into a voting right contract.
func RightIssuance(ctx context.Context, adminScript, holderScript []byte) txbuilder.Receiver {
	return rightScriptData{
		AdminScript:    adminScript,
		HolderScript:   holderScript,
		Delegatable:    true,
		Deadline:       InfiniteDeadline,
		OwnershipChain: bc.Hash{},
	}
}

// RightAuthentication builds txbuilder Reserver and Receiver implementations
// for passing a voting right token through a transaction unchanged. The
// output voting right is identical to the input voting right. Its
// presence in the transaction proves voting right ownership during
// voting.
func RightAuthentication(ctx context.Context, src *Right) (txbuilder.Reserver, txbuilder.Receiver, error) {
	originalHolderAddr, err := appdb.GetAddress(ctx, src.HolderScript)
	if err != nil {
		holderScriptStr, _ := txscript.DisasmString(src.HolderScript)
		return nil, nil, errors.Wrapf(err, "could not get address for holder script [%s]", holderScriptStr)
	}

	reserver := rightsReserver{
		outpoint:   src.Outpoint,
		clause:     clauseAuthenticate,
		output:     src.rightScriptData, // unchanged
		prevScript: src.PKScript(),
		holderAddr: originalHolderAddr,
	}
	return reserver, reserver.output, nil
}

// RightTransfer builds txbuilder Reserver and Receiver implementations for
// a voting right transfer.
func RightTransfer(ctx context.Context, src *Right, newHolderScript []byte) (txbuilder.Reserver, txbuilder.Receiver, error) {
	currentHolderAddr, err := appdb.GetAddress(ctx, src.HolderScript)
	if err != nil {
		holderScriptStr, _ := txscript.DisasmString(src.HolderScript)
		return nil, nil, errors.Wrapf(err, "could not get address for holder script [%s]", holderScriptStr)
	}

	reserver := rightsReserver{
		outpoint: src.Outpoint,
		clause:   clauseTransfer,
		output: rightScriptData{
			AdminScript:    src.AdminScript, // unchanged
			HolderScript:   newHolderScript,
			Delegatable:    src.Delegatable,    // unchanged
			Deadline:       src.Deadline,       // unchanged
			OwnershipChain: src.OwnershipChain, // unchanged
		},
		prevScript: src.PKScript(),
		holderAddr: currentHolderAddr,
	}
	return reserver, reserver.output, nil
}

// RightDelegation builds txbuilder Reserver and Receiver implementations for
// delegating a voting right to another party.
func RightDelegation(ctx context.Context, src *Right, newHolderScript []byte, newDeadline int64, delegatable bool) (txbuilder.Reserver, txbuilder.Receiver, error) {
	currentHolderAddr, err := appdb.GetAddress(ctx, src.HolderScript)
	if err != nil {
		holderScriptStr, _ := txscript.DisasmString(src.HolderScript)
		return nil, nil, errors.Wrapf(err, "could not get address for holder script [%s]", holderScriptStr)
	}

	reserver := rightsReserver{
		outpoint: src.Outpoint,
		clause:   clauseDelegate,
		output: rightScriptData{
			AdminScript:  src.AdminScript,
			HolderScript: newHolderScript,
			Delegatable:  delegatable,
			Deadline:     newDeadline,
			OwnershipChain: calculateOwnershipChain(
				src.OwnershipChain,
				src.HolderScript,
				src.Deadline,
			),
		},
		prevScript: src.PKScript(),
		holderAddr: currentHolderAddr,
	}
	return reserver, reserver.output, nil
}

// RightRecall builds txbuilder Reserver and Receiver implementations for
// a voting right recall.
func RightRecall(ctx context.Context, src, recallPoint *Right, intermediaryRights []*Right) (txbuilder.Reserver, txbuilder.Receiver, error) {
	originalHolderAddr, err := appdb.GetAddress(ctx, recallPoint.HolderScript)
	if err != nil {
		originalHolderAddr = nil
	}

	intermediaries := make([]RightHolder, 0, len(intermediaryRights))
	for _, r := range intermediaryRights {
		intermediaries = append(intermediaries, RightHolder{
			Script:   r.HolderScript,
			Deadline: r.Deadline,
		})
	}

	reserver := rightsReserver{
		outpoint:       src.Outpoint,
		clause:         clauseRecall,
		output:         recallPoint.rightScriptData,
		intermediaries: intermediaries,
		prevScript:     src.PKScript(),
		holderAddr:     originalHolderAddr,
	}
	return reserver, reserver.output, nil
}

// RightOverride builds txbuilder Reserver and Receiver implementations for
// a voting right override.
func RightOverride(ctx context.Context, src, forkPoint *Right, intermediaryRights []*Right, delegates []RightHolder) (txbuilder.Reserver, txbuilder.Receiver, error) {
	adminAddr, err := appdb.GetAddress(ctx, src.AdminScript)
	if err != nil {
		adminAddr = nil
	}

	proofHashes := make([]RightHolder, 0, len(intermediaryRights)+1)
	proofHashes = append(proofHashes, RightHolder{Script: forkPoint.HolderScript, Deadline: forkPoint.Deadline})
	for _, r := range intermediaryRights {
		proofHashes = append(proofHashes, RightHolder{
			Script:   r.HolderScript,
			Deadline: r.Deadline,
		})
	}

	// Build up the new ownership hash.
	output := forkPoint.rightScriptData
	for _, d := range delegates {
		output.OwnershipChain = calculateOwnershipChain(output.OwnershipChain, output.HolderScript, output.Deadline)
		output.HolderScript = d.Script
		output.Deadline = d.Deadline
	}

	// The contract expects the holder at the fork point too.
	newHolders := append([]RightHolder{
		{Script: forkPoint.HolderScript, Deadline: forkPoint.Deadline},
	}, delegates...)

	reserver := rightsReserver{
		outpoint:    src.Outpoint,
		clause:      clauseOverride,
		output:      output,
		proofHashes: proofHashes,
		newHolders:  newHolders,
		prevScript:  src.PKScript(),
		adminAddr:   adminAddr,
	}
	return reserver, output, nil
}

// TokenIssuance builds a txbuilder Receiver implementation
// for a voting token issuance.
func TokenIssuance(ctx context.Context, rightAssetID bc.AssetID, admin []byte) txbuilder.Receiver {
	scriptData := tokenScriptData{
		Right:       rightAssetID,
		AdminScript: admin,
		State:       stateDistributed,
		Vote:        0,
	}
	return scriptData
}

// TokenRedistribution builds txbuilder Reserver and Destination implementations
// for a voting token redistribution.
func TokenRedistribution(ctx context.Context, token *Token, rightScript []byte, distributions map[bc.AssetID]uint64) (txbuilder.Reserver, []*txbuilder.Destination, error) {
	tok := tokenScriptData{
		Right:       token.Right,
		AdminScript: token.AdminScript,
		State:       stateDistributed,
		Vote:        0,
	}

	reserver := tokenReserver{
		outpoint:      token.Outpoint,
		clause:        clauseRedistribute,
		output:        tok,
		prevScript:    token.tokenScriptData.PKScript(),
		rightScript:   rightScript,
		distributions: distributions,
	}

	change := uint64(token.Amount)
	destinations := make([]*txbuilder.Destination, 0, len(distributions)+1)
	for assetID, amount := range distributions {
		output := tok
		output.Right = assetID
		destinations = append(destinations, &txbuilder.Destination{
			AssetAmount: bc.AssetAmount{AssetID: token.AssetID, Amount: amount},
			Receiver:    output,
		})
		change = change - amount
	}
	if change > 0 {
		destinations = append(destinations, &txbuilder.Destination{
			AssetAmount: bc.AssetAmount{AssetID: token.AssetID, Amount: change},
			Receiver:    token.tokenScriptData,
		})
	}
	return reserver, destinations, nil
}

// TokenRegistration builds txbuilder Reserver and Destination
// implementations for a voting token registration transition.
func TokenRegistration(ctx context.Context, token *Token, rightScript []byte, registrations []Registration) (txbuilder.Reserver, []*txbuilder.Destination, error) {
	prevScript := token.tokenScriptData.PKScript()
	registered := token.tokenScriptData
	registered.State = stateRegistered

	reserver := tokenReserver{
		outpoint:      token.Outpoint,
		clause:        clauseRegister,
		output:        registered,
		registrations: registrations,
		prevScript:    prevScript,
		rightScript:   rightScript,
	}

	change := uint64(token.Amount)
	destinations := make([]*txbuilder.Destination, 0, len(registrations)+1)
	for _, r := range registrations {
		output := registered
		output.RegistrationID = r.ID
		destinations = append(destinations, &txbuilder.Destination{
			AssetAmount: bc.AssetAmount{AssetID: token.AssetID, Amount: r.Amount},
			Receiver:    output,
		})
		change = change - r.Amount
	}
	if change > 0 {
		destinations = append(destinations, &txbuilder.Destination{
			AssetAmount: bc.AssetAmount{AssetID: token.AssetID, Amount: change},
			Receiver:    token.tokenScriptData,
		})
	}

	return reserver, destinations, nil
}

// TokenVote builds txbuilder Reserver and Receiver implementations
// for a voting token vote transition.
func TokenVote(ctx context.Context, token *Token, rightScript []byte, vote int64) (txbuilder.Reserver, txbuilder.Receiver, error) {
	data := token.tokenScriptData
	data.State = stateVoted
	data.Vote = vote

	reserver := tokenReserver{
		outpoint:    token.Outpoint,
		clause:      clauseVote,
		output:      data,
		prevScript:  token.tokenScriptData.PKScript(),
		rightScript: rightScript,
	}
	return reserver, data, nil
}

// TokenFinish builds txbuilder Reserve and Receiver implementations
// for a voting token finish/close transition.
func TokenFinish(ctx context.Context, token *Token) (txbuilder.Reserver, txbuilder.Receiver, error) {
	data := token.tokenScriptData
	data.State = data.State | stateFinished

	adminAddr, err := appdb.GetAddress(ctx, token.AdminScript)
	if err != nil {
		adminAddr = nil
	}

	reserver := tokenReserver{
		outpoint:   token.Outpoint,
		clause:     clauseFinish,
		output:     data,
		prevScript: token.tokenScriptData.PKScript(),
		adminAddr:  adminAddr,
	}
	return reserver, data, nil
}

func TokenInvalidate(ctx context.Context, token *Token) (txbuilder.Reserver, txbuilder.Receiver, error) {
	data := token.tokenScriptData
	data.State = data.State | stateInvalid

	adminAddr, err := appdb.GetAddress(ctx, token.AdminScript)
	if err != nil {
		adminAddr = nil
	}

	reserver := tokenReserver{
		outpoint:   token.Outpoint,
		clause:     clauseInvalidate,
		output:     data,
		prevScript: token.tokenScriptData.PKScript(),
		adminAddr:  adminAddr,
	}
	return reserver, data, nil
}

// TokenReset builds txbuilder.Reserve and Receiver implementations
// to reset a voting token.
func TokenReset(ctx context.Context, token *Token, preserveRegistration bool) (txbuilder.Reserver, txbuilder.Receiver, error) {
	data := tokenScriptData{
		Right:          token.Right,
		AdminScript:    token.AdminScript,
		State:          stateDistributed,
		Vote:           0, // unset vote
		RegistrationID: token.RegistrationID,
	}
	if preserveRegistration && (token.State.Registered() || token.State.Voted()) {
		data.State = stateRegistered
	}

	adminAddr, err := appdb.GetAddress(ctx, token.AdminScript)
	if err != nil {
		adminAddr = nil
	}

	reserver := tokenReserver{
		outpoint:   token.Outpoint,
		clause:     clauseReset,
		output:     data,
		prevScript: token.tokenScriptData.PKScript(),
		adminAddr:  adminAddr,
	}
	return reserver, data, nil
}

// TokenRetire builds a txbuilder Reserver implementation for retiring a
// voting token.
func TokenRetire(ctx context.Context, token *Token) (txbuilder.Reserver, error) {
	adminAddr, err := appdb.GetAddress(ctx, token.AdminScript)
	if err != nil {
		adminAddr = nil
	}

	reserver := tokenReserver{
		outpoint:   token.Outpoint,
		clause:     clauseRetire,
		prevScript: token.tokenScriptData.PKScript(),
		adminAddr:  adminAddr,
	}
	return reserver, nil
}
<commit_msg>core/smartcontracts/voting: reset fix<commit_after>package voting

import (
	"golang.org/x/net/context"

	"chain/core/appdb"
	"chain/core/txbuilder"
	"chain/cos/bc"
	"chain/cos/txscript"
	"chain/errors"
)

// RightIssuance builds a txbuilder Receiver issuance for an asset that
// is being issued into a voting right contract.
func RightIssuance(ctx context.Context, adminScript, holderScript []byte) txbuilder.Receiver {
	return rightScriptData{
		AdminScript:    adminScript,
		HolderScript:   holderScript,
		Delegatable:    true,
		Deadline:       InfiniteDeadline,
		OwnershipChain: bc.Hash{},
	}
}

// RightAuthentication builds txbuilder Reserver and Receiver implementations
// for passing a voting right token through a transaction unchanged. The
// output voting right is identical to the input voting right. Its
// presence in the transaction proves voting right ownership during
// voting.
func RightAuthentication(ctx context.Context, src *Right) (txbuilder.Reserver, txbuilder.Receiver, error) {
	originalHolderAddr, err := appdb.GetAddress(ctx, src.HolderScript)
	if err != nil {
		holderScriptStr, _ := txscript.DisasmString(src.HolderScript)
		return nil, nil, errors.Wrapf(err, "could not get address for holder script [%s]", holderScriptStr)
	}

	reserver := rightsReserver{
		outpoint:   src.Outpoint,
		clause:     clauseAuthenticate,
		output:     src.rightScriptData, // unchanged
		prevScript: src.PKScript(),
		holderAddr: originalHolderAddr,
	}
	return reserver, reserver.output, nil
}

// RightTransfer builds txbuilder Reserver and Receiver implementations for
// a voting right transfer.
func RightTransfer(ctx context.Context, src *Right, newHolderScript []byte) (txbuilder.Reserver, txbuilder.Receiver, error) {
	currentHolderAddr, err := appdb.GetAddress(ctx, src.HolderScript)
	if err != nil {
		holderScriptStr, _ := txscript.DisasmString(src.HolderScript)
		return nil, nil, errors.Wrapf(err, "could not get address for holder script [%s]", holderScriptStr)
	}

	reserver := rightsReserver{
		outpoint: src.Outpoint,
		clause:   clauseTransfer,
		output: rightScriptData{
			AdminScript:    src.AdminScript, // unchanged
			HolderScript:   newHolderScript,
			Delegatable:    src.Delegatable,    // unchanged
			Deadline:       src.Deadline,       // unchanged
			OwnershipChain: src.OwnershipChain, // unchanged
		},
		prevScript: src.PKScript(),
		holderAddr: currentHolderAddr,
	}
	return reserver, reserver.output, nil
}

// RightDelegation builds txbuilder Reserver and Receiver implementations for
// delegating a voting right to another party.
func RightDelegation(ctx context.Context, src *Right, newHolderScript []byte, newDeadline int64, delegatable bool) (txbuilder.Reserver, txbuilder.Receiver, error) {
	currentHolderAddr, err := appdb.GetAddress(ctx, src.HolderScript)
	if err != nil {
		holderScriptStr, _ := txscript.DisasmString(src.HolderScript)
		return nil, nil, errors.Wrapf(err, "could not get address for holder script [%s]", holderScriptStr)
	}

	reserver := rightsReserver{
		outpoint: src.Outpoint,
		clause:   clauseDelegate,
		output: rightScriptData{
			AdminScript:  src.AdminScript,
			HolderScript: newHolderScript,
			Delegatable:  delegatable,
			Deadline:     newDeadline,
			OwnershipChain: calculateOwnershipChain(
				src.OwnershipChain,
				src.HolderScript,
				src.Deadline,
			),
		},
		prevScript: src.PKScript(),
		holderAddr: currentHolderAddr,
	}
	return reserver, reserver.output, nil
}

// RightRecall builds txbuilder Reserver and Receiver implementations for
// a voting right recall.
func RightRecall(ctx context.Context, src, recallPoint *Right, intermediaryRights []*Right) (txbuilder.Reserver, txbuilder.Receiver, error) {
	originalHolderAddr, err := appdb.GetAddress(ctx, recallPoint.HolderScript)
	if err != nil {
		originalHolderAddr = nil
	}

	intermediaries := make([]RightHolder, 0, len(intermediaryRights))
	for _, r := range intermediaryRights {
		intermediaries = append(intermediaries, RightHolder{
			Script:   r.HolderScript,
			Deadline: r.Deadline,
		})
	}

	reserver := rightsReserver{
		outpoint:       src.Outpoint,
		clause:         clauseRecall,
		output:         recallPoint.rightScriptData,
		intermediaries: intermediaries,
		prevScript:     src.PKScript(),
		holderAddr:     originalHolderAddr,
	}
	return reserver, reserver.output, nil
}

// RightOverride builds txbuilder Reserver and Receiver implementations for
// a voting right override.
func RightOverride(ctx context.Context, src, forkPoint *Right, intermediaryRights []*Right, delegates []RightHolder) (txbuilder.Reserver, txbuilder.Receiver, error) {
	adminAddr, err := appdb.GetAddress(ctx, src.AdminScript)
	if err != nil {
		adminAddr = nil
	}

	proofHashes := make([]RightHolder, 0, len(intermediaryRights)+1)
	proofHashes = append(proofHashes, RightHolder{Script: forkPoint.HolderScript, Deadline: forkPoint.Deadline})
	for _, r := range intermediaryRights {
		proofHashes = append(proofHashes, RightHolder{
			Script:   r.HolderScript,
			Deadline: r.Deadline,
		})
	}

	// Build up the new ownership hash.
	output := forkPoint.rightScriptData
	for _, d := range delegates {
		output.OwnershipChain = calculateOwnershipChain(output.OwnershipChain, output.HolderScript, output.Deadline)
		output.HolderScript = d.Script
		output.Deadline = d.Deadline
	}

	// The contract expects the holder at the fork point too.
	newHolders := append([]RightHolder{
		{Script: forkPoint.HolderScript, Deadline: forkPoint.Deadline},
	}, delegates...)

	reserver := rightsReserver{
		outpoint:    src.Outpoint,
		clause:      clauseOverride,
		output:      output,
		proofHashes: proofHashes,
		newHolders:  newHolders,
		prevScript:  src.PKScript(),
		adminAddr:   adminAddr,
	}
	return reserver, output, nil
}

// TokenIssuance builds a txbuilder Receiver implementation
// for a voting token issuance.
func TokenIssuance(ctx context.Context, rightAssetID bc.AssetID, admin []byte) txbuilder.Receiver {
	scriptData := tokenScriptData{
		Right:       rightAssetID,
		AdminScript: admin,
		State:       stateDistributed,
		Vote:        0,
	}
	return scriptData
}

// TokenRedistribution builds txbuilder Reserver and Destination implementations
// for a voting token redistribution.
func TokenRedistribution(ctx context.Context, token *Token, rightScript []byte, distributions map[bc.AssetID]uint64) (txbuilder.Reserver, []*txbuilder.Destination, error) {
	tok := tokenScriptData{
		Right:       token.Right,
		AdminScript: token.AdminScript,
		State:       stateDistributed,
		Vote:        0,
	}

	reserver := tokenReserver{
		outpoint:      token.Outpoint,
		clause:        clauseRedistribute,
		output:        tok,
		prevScript:    token.tokenScriptData.PKScript(),
		rightScript:   rightScript,
		distributions: distributions,
	}

	change := uint64(token.Amount)
	destinations := make([]*txbuilder.Destination, 0, len(distributions)+1)
	for assetID, amount := range distributions {
		output := tok
		output.Right = assetID
		destinations = append(destinations, &txbuilder.Destination{
			AssetAmount: bc.AssetAmount{AssetID: token.AssetID, Amount: amount},
			Receiver:    output,
		})
		change = change - amount
	}
	if change > 0 {
		destinations = append(destinations, &txbuilder.Destination{
			AssetAmount: bc.AssetAmount{AssetID: token.AssetID, Amount: change},
			Receiver:    token.tokenScriptData,
		})
	}
	return reserver, destinations, nil
}

// TokenRegistration builds txbuilder Reserver and Destination
// implementations for a voting token registration transition.
func TokenRegistration(ctx context.Context, token *Token, rightScript []byte, registrations []Registration) (txbuilder.Reserver, []*txbuilder.Destination, error) {
	prevScript := token.tokenScriptData.PKScript()
	registered := token.tokenScriptData
	registered.State = stateRegistered

	reserver := tokenReserver{
		outpoint:      token.Outpoint,
		clause:        clauseRegister,
		output:        registered,
		registrations: registrations,
		prevScript:    prevScript,
		rightScript:   rightScript,
	}

	change := uint64(token.Amount)
	destinations := make([]*txbuilder.Destination, 0, len(registrations)+1)
	for _, r := range registrations {
		output := registered
		output.RegistrationID = r.ID
		destinations = append(destinations, &txbuilder.Destination{
			AssetAmount: bc.AssetAmount{AssetID: token.AssetID, Amount: r.Amount},
			Receiver:    output,
		})
		change = change - r.Amount
	}
	if change > 0 {
		destinations = append(destinations, &txbuilder.Destination{
			AssetAmount: bc.AssetAmount{AssetID: token.AssetID, Amount: change},
			Receiver:    token.tokenScriptData,
		})
	}

	return reserver, destinations, nil
}

// TokenVote builds txbuilder Reserver and Receiver implementations
// for a voting token vote transition.
func TokenVote(ctx context.Context, token *Token, rightScript []byte, vote int64) (txbuilder.Reserver, txbuilder.Receiver, error) {
	data := token.tokenScriptData
	data.State = stateVoted
	data.Vote = vote

	reserver := tokenReserver{
		outpoint:    token.Outpoint,
		clause:      clauseVote,
		output:      data,
		prevScript:  token.tokenScriptData.PKScript(),
		rightScript: rightScript,
	}
	return reserver, data, nil
}

// TokenFinish builds txbuilder Reserve and Receiver implementations
// for a voting token finish/close transition.
func TokenFinish(ctx context.Context, token *Token) (txbuilder.Reserver, txbuilder.Receiver, error) {
	data := token.tokenScriptData
	data.State = data.State | stateFinished

	adminAddr, err := appdb.GetAddress(ctx, token.AdminScript)
	if err != nil {
		adminAddr = nil
	}

	reserver := tokenReserver{
		outpoint:   token.Outpoint,
		clause:     clauseFinish,
		output:     data,
		prevScript: token.tokenScriptData.PKScript(),
		adminAddr:  adminAddr,
	}
	return reserver, data, nil
}

func TokenInvalidate(ctx context.Context, token *Token) (txbuilder.Reserver, txbuilder.Receiver, error) {
	data := token.tokenScriptData
	data.State = data.State | stateInvalid

	adminAddr, err := appdb.GetAddress(ctx, token.AdminScript)
	if err != nil {
		adminAddr = nil
	}

	reserver := tokenReserver{
		outpoint:   token.Outpoint,
		clause:     clauseInvalidate,
		output:     data,
		prevScript: token.tokenScriptData.PKScript(),
		adminAddr:  adminAddr,
	}
	return reserver, data, nil
}

// TokenReset builds txbuilder.Reserve and Receiver implementations
// to reset a voting token.
func TokenReset(ctx context.Context, token *Token, preserveRegistration bool) (txbuilder.Reserver, txbuilder.Receiver, error) {
	data := tokenScriptData{
		Right:       token.Right,
		AdminScript: token.AdminScript,
		State:       stateDistributed,
		Vote:        0, // unset vote
	}
	if preserveRegistration && (token.State.Registered() || token.State.Voted()) {
		data.RegistrationID = token.RegistrationID
		data.State = stateRegistered
	}

	adminAddr, err := appdb.GetAddress(ctx, token.AdminScript)
	if err != nil {
		adminAddr = nil
	}

	reserver := tokenReserver{
		outpoint:   token.Outpoint,
		clause:     clauseReset,
		output:     data,
		prevScript: token.tokenScriptData.PKScript(),
		adminAddr:  adminAddr,
	}
	return reserver, data, nil
}

// TokenRetire builds a txbuilder Reserver implementation for retiring a
// voting token.
func TokenRetire(ctx context.Context, token *Token) (txbuilder.Reserver, error) {
	adminAddr, err := appdb.GetAddress(ctx, token.AdminScript)
	if err != nil {
		adminAddr = nil
	}

	reserver := tokenReserver{
		outpoint:   token.Outpoint,
		clause:     clauseRetire,
		prevScript: token.tokenScriptData.PKScript(),
		adminAddr:  adminAddr,
	}
	return reserver, nil
}
<|endoftext|>


<commit_before>package vagrantutil

import (
	"errors"
	"os"
	"strings"
)

// List of errors ignored by Destroy / Status methods:
const (
	errNotCreated    = "A Vagrant environment or target machine is required to run this"
	errRubyNotExists = "No such file or directory - getcwd (Errno::ENOENT)"
)

func isNotCreated(err error) bool {
	return os.IsNotExist(err) || strings.Contains(err.Error(), errNotCreated) ||
		strings.Contains(err.Error(), errRubyNotExists)
}

// The following errors are returned by the Wait function:
var (
	ErrBoxAlreadyExists  = errors.New("box already exists")
	ErrBoxInvalidVersion = errors.New("invalid box version")
	ErrBoxNotAvailable   = errors.New("box is not available")
	ErrBoxDownload       = errors.New("unable to download the box")
)

var defaultWaiter Waiter

// Waiter is used to consume output channel from a Vagrant command, parsing
// each line looking for an error when command execution fails.
type Waiter struct {
	// OutputFunc, when non-nil, is called each time a Wait method receives
	// a line of output from command channel.
	OutputFunc func(string)
}

// Wait is a convenience method that consumes Vagrant output looking
// for well-known errors.
//
// It returns an error variable for any known error condition, which makes it
// easier for the caller to recover from failure.
//
// If OutputFunc is non-nil, it's called on each line of output received
// from the out channel.
func (w *Waiter) Wait(out <-chan *CommandOutput, err error) error {
	var e error
	for o := range out {
		if w.OutputFunc != nil {
			w.OutputFunc(o.Line)
		}
		for s, err := range errMapping {
			if strings.Contains(o.Line, s) {
				e = nonil(e, err)
			}
		}
		e = nonil(e, o.Error)
	}
	return nonil(e, err)
}

// Wait is a convenience function that consumes Vagrant output looking
// for well-known errors.
func Wait(out <-chan *CommandOutput, err error) error {
	return defaultWaiter.Wait(out, err)
}

var errMapping = map[string]error{
	"The box you're attempting to add already exists.":     ErrBoxAlreadyExists,
	"Gem::Requirement::BadRequirementError":                ErrBoxInvalidVersion,
	"could not be accessed in the remote catalog.":         ErrBoxNotAvailable,
	"An error occurred while downloading the remote file.": ErrBoxDownload,
}

func nonil(err ...error) error {
	for _, e := range err {
		if e != nil {
			return e
		}
	}
	return nil
}
<commit_msg>vagrantutil: detect VirtualBox errors<commit_after>package vagrantutil

import (
	"errors"
	"os"
	"strings"
)

// List of errors ignored by Destroy / Status methods:
const (
	errNotCreated    = "A Vagrant environment or target machine is required to run this"
	errRubyNotExists = "No such file or directory - getcwd (Errno::ENOENT)"
)

func isNotCreated(err error) bool {
	return os.IsNotExist(err) || strings.Contains(err.Error(), errNotCreated) ||
		strings.Contains(err.Error(), errRubyNotExists)
}

// The following errors are returned by the Wait function:
var (
	ErrBoxAlreadyExists  = errors.New("box already exists")
	ErrBoxInvalidVersion = errors.New("invalid box version")
	ErrBoxNotAvailable   = errors.New("box is not available")
	ErrBoxDownload       = errors.New("unable to download the box")
	ErrVirtualBox        = errors.New("VirtualBox is missing or not operational")
)

var defaultWaiter Waiter

// Waiter is used to consume output channel from a Vagrant command, parsing
// each line looking for an error when command execution fails.
type Waiter struct {
	// OutputFunc, when non-nil, is called each time a Wait method receives
	// a line of output from command channel.
	OutputFunc func(string)
}

// Wait is a convenience method that consumes Vagrant output looking
// for well-known errors.
//
// It returns an error variable for any known error condition, which makes it
// easier for the caller to recover from failure.
//
// If OutputFunc is non-nil, it's called on each line of output received
// from the out channel.
func (w *Waiter) Wait(out <-chan *CommandOutput, err error) error {
	var e error
	for o := range out {
		if w.OutputFunc != nil {
			w.OutputFunc(o.Line)
		}
		for s, err := range errMapping {
			if strings.Contains(o.Line, s) {
				e = nonil(e, err)
			}
		}
		e = nonil(e, o.Error)
	}
	return nonil(e, err)
}

// Wait is a convenience function that consumes Vagrant output looking
// for well-known errors.
func Wait(out <-chan *CommandOutput, err error) error {
	return defaultWaiter.Wait(out, err)
}

var errMapping = map[string]error{
	"The box you're attempting to add already exists.":               ErrBoxAlreadyExists,
	"Gem::Requirement::BadRequirementError":                          ErrBoxInvalidVersion,
	"could not be accessed in the remote catalog.":                   ErrBoxNotAvailable,
	"An error occurred while downloading the remote file.":           ErrBoxDownload,
	"VirtualBox is complaining that the kernel module is not loaded": ErrVirtualBox,
}

func nonil(err ...error) error {
	for _, e := range err {
		if e != nil {
			return e
		}
	}
	return nil
}
<|endoftext|>


<commit_before>package cdp

type causer interface {
	Cause() error
}

// ErrorCause returns the underlying cause for this error, if possible.
// If err does not implement causer.Cause(), then err is returned.
func ErrorCause(err error) error {
	if err == nil {
		return nil
	}
	if err, ok := err.(causer); ok {
		return err.Cause()
	}
	return err
}
<commit_msg>Return original cause in ErrorCause instead of the next error<commit_after>package cdp

type causer interface {
	Cause() error
}

// ErrorCause returns the underlying cause for this error, if possible.
// If err does not implement causer.Cause(), then err is returned.
func ErrorCause(err error) error {
	for err != nil {
		if c, ok := err.(causer); ok {
			err = c.Cause()
		} else {
			return err
		}
	}
	return err
}
<|endoftext|>


<commit_before>package ds

import (
	"log"

	"cloud.google.com/go/datastore"
	"google.golang.org/api/iterator"
)

// NotFound checks is error means not found
func NotFound(err error) bool {
	return err == iterator.Done || err == datastore.ErrNoSuchEntity || err == datastore.ErrInvalidKey
}

// FieldMismatch checks is error field mismatch
func FieldMismatch(err error) bool {
	_, ok := err.(*datastore.ErrFieldMismatch)
	return ok
}

// Ignore removes error(s) from err if f(err)
func Ignore(err error, f func(error) bool) error {
	if f(err) {
		return nil
	}

	if errs, ok := err.(datastore.MultiError); ok {
		if len(errs) == 0 {
			return nil
		}
		es := make(datastore.MultiError, 0)
		for _, err := range errs {
			if !f(err) && err != nil {
				log.Println(err)
				es = append(es, err)
			}
		}
		if len(es) > 0 {
			return es
		}
		return nil
	}
	return err
}

// IgnoreFieldMismatch returns nil if err is field mismatch error(s)
func IgnoreFieldMismatch(err error) error {
	return Ignore(err, FieldMismatch)
}

// IgnoreNotFound returns nil if err is not found error(s)
func IgnoreNotFound(err error) error {
	return Ignore(err, NotFound)
}
<commit_msg>cleanup<commit_after>package ds

import (
	"cloud.google.com/go/datastore"
	"google.golang.org/api/iterator"
)

// NotFound checks is error means not found
func NotFound(err error) bool {
	return err == iterator.Done || err == datastore.ErrNoSuchEntity || err == datastore.ErrInvalidKey
}

// FieldMismatch checks is error field mismatch
func FieldMismatch(err error) bool {
	_, ok := err.(*datastore.ErrFieldMismatch)
	return ok
}

// Ignore removes error(s) from err if f(err)
func Ignore(err error, f func(error) bool) error {
	if f(err) {
		return nil
	}

	if errs, ok := err.(datastore.MultiError); ok {
		if len(errs) == 0 {
			return nil
		}
		es := make(datastore.MultiError, 0)
		for _, err := range errs {
			if !f(err) && err != nil {
				es = append(es, err)
			}
		}
		if len(es) > 0 {
			return es
		}
		return nil
	}
	return err
}

// IgnoreFieldMismatch returns nil if err is field mismatch error(s)
func IgnoreFieldMismatch(err error) error {
	return Ignore(err, FieldMismatch)
}

// IgnoreNotFound returns nil if err is not found error(s)
func IgnoreNotFound(err error) error {
	return Ignore(err, NotFound)
}
<|endoftext|>


<commit_before>// Copyright 2011, 2012, 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.

package environs

import (
	"fmt"
	"io/ioutil"

	"launchpad.net/juju-core/environs/config"
	"launchpad.net/juju-core/environs/storage"
	"launchpad.net/juju-core/errors"
)

var InvalidEnvironmentError = fmt.Errorf("environment is not a juju-core environment")

// ConfigForName returns the configuration for the environment with the
// given name from the default environments file. If the name is blank,
// the default environment will be used. If the configuration is not
// found, an errors.NotFoundError is returned.
func ConfigForName(name string) (*config.Config, error) {
	envs, err := ReadEnvirons("")
	if err != nil {
		return nil, err
	}
	return envs.Config(name)
}

// NewFromName opens the environment with the given
// name from the default environments file. If the
// name is blank, the default environment will be used.
func NewFromName(name string) (Environ, error) {
	cfg, err := ConfigForName(name)
	if err != nil {
		return nil, err
	}
	return New(cfg)
}

// PrepareFromName is the same as NewFromName except
// that the environment is is prepared as well as opened.
func PrepareFromName(name string) (Environ, error) {
	cfg, err := ConfigForName(name)
	if err != nil {
		return nil, err
	}
	return Prepare(cfg)
}

// NewFromAttrs returns a new environment based on the provided configuration
// attributes.
func NewFromAttrs(attrs map[string]interface{}) (Environ, error) {
	cfg, err := config.New(config.NoDefaults, attrs)
	if err != nil {
		return nil, err
	}
	return New(cfg)
}

// New returns a new environment based on the provided configuration.
func New(config *config.Config) (Environ, error) {
	p, err := Provider(config.Type())
	if err != nil {
		return nil, err
	}
	return p.Open(config)
}

// Prepare prepares a new environment based on the provided configuration.
func Prepare(config *config.Config) (Environ, error) {
	p, err := Provider(config.Type())
	if err != nil {
		return nil, err
	}
	return p.Prepare(config)
}

// CheckEnvironment checks if an environment has a bootstrap-verify
// that is written by juju-core commands (as compared to one being
// written by Python juju).
//
// If there is no bootstrap-verify file in the storage, it is still
// considered to be a Juju-core environment since early versions have
// not written it out.
//
// Returns InvalidEnvironmentError on failure, nil otherwise.
func CheckEnvironment(environ Environ) error {
	stor := environ.Storage()
	reader, err := storage.Get(stor, verificationFilename)
	if errors.IsNotFoundError(err) {
		// When verification file does not exist, this is a juju-core
		// environment.
		return nil
	} else if err != nil {
		return err
	} else if content, err := ioutil.ReadAll(reader); err != nil {
		return err
	} else if string(content) != verificationContent {
		return InvalidEnvironmentError
	}
	return nil
}
<commit_msg>environs: Prepare creates environment info<commit_after>// Copyright 2011, 2012, 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.

package environs

import (
	"fmt"
	"io/ioutil"

	"launchpad.net/juju-core/environs/config"
	"launchpad.net/juju-core/environs/storage"
	"launchpad.net/juju-core/errors"
)

var InvalidEnvironmentError = fmt.Errorf("environment is not a juju-core environment")

// ConfigForName returns the configuration for the environment with the
// given name from the default environments file. If the name is blank,
// the default environment will be used. If the configuration is not
// found, an errors.NotFoundError is returned.
func ConfigForName(name string) (*config.Config, error) {
	envs, err := ReadEnvirons("")
	if err != nil {
		return nil, err
	}
	return envs.Config(name)
}

// NewFromName opens the environment with the given
// name from the default environments file. If the
// name is blank, the default environment will be used.
func NewFromName(name string) (Environ, error) {
	cfg, err := ConfigForName(name)
	if err != nil {
		return nil, err
	}
	return New(cfg)
}

// DefaultConfigStorage returns disk-based environment config storage
// rooted at JujuHome.
func DefaultConfigStorage() (ConfigStorage, error) {
	return configstore.NewDisk(config.JujuHomePath("environments"))
}

// PrepareFromName is the same as NewFromName except
// that the environment is is prepared as well as opened,
// and environment information is created using the
// given store. If store is nil, DefaultConfigStorage will be
// used.
func PrepareFromName(name string, store ConfigStorage) (Environ, error) {
	if store == nil {
		store1, err := DefaultConfigStorage()
		if err != nil {
			return nil, err
		}
		store = store1
	}
	cfg, err := ConfigForName(name)
	if err != nil {
		return nil, err
	}
	return Prepare(cfg, store)
}

// NewFromAttrs returns a new environment based on the provided configuration
// attributes.
func NewFromAttrs(attrs map[string]interface{}) (Environ, error) {
	cfg, err := config.New(config.NoDefaults, attrs)
	if err != nil {
		return nil, err
	}
	return New(cfg)
}

// New returns a new environment based on the provided configuration.
func New(config *config.Config) (Environ, error) {
	p, err := Provider(config.Type())
	if err != nil {
		return nil, err
	}
	return p.Open(config)
}

// Prepare prepares a new environment based on the provided configuration.
func Prepare(config *config.Config, store ConfigStorage) (Environ, error) {
	p, err := Provider(config.Type())
	if err != nil {
		return nil, err
	}
	info, err = store.CreateInfo(config.Name())
	if err != nil {
		return nil, fmt.Errorf("cannot create new info for environment %q: %v", config.Name(), err)
	}
	env, err := p.Prepare(config)
	if err != nil {
		if err := info.Destroy(); err != nil {
			logger.Warningf("cannot destroy newly created environment info: %v", err)
		}
		return nil, err
	}
	// TODO(rog) 2013-09-19 write out newly added attributes from environ to store
	return env, nil
}

// CheckEnvironment checks if an environment has a bootstrap-verify
// that is written by juju-core commands (as compared to one being
// written by Python juju).
//
// If there is no bootstrap-verify file in the storage, it is still
// considered to be a Juju-core environment since early versions have
// not written it out.
//
// Returns InvalidEnvironmentError on failure, nil otherwise.
func CheckEnvironment(environ Environ) error {
	stor := environ.Storage()
	reader, err := storage.Get(stor, verificationFilename)
	if errors.IsNotFoundError(err) {
		// When verification file does not exist, this is a juju-core
		// environment.
		return nil
	} else if err != nil {
		return err
	} else if content, err := ioutil.ReadAll(reader); err != nil {
		return err
	} else if string(content) != verificationContent {
		return InvalidEnvironmentError
	}
	return nil
}
<|endoftext|>


<commit_before>//GstEvent — Structure describing events that are passed up and down a pipeline
package gst

/*
#include <stdlib.h>
#include <gst/gst.h>
*/
import "C"

import (
	//"errors"
	"github.com/lidouf/glib"
	//"time"
	//"unsafe"
)

type Event struct {
	glib.Object
}

func (o *Event) g() *C.GstEvent {
	return (*C.GstEvent)(o.GetPtr())
}

func (o *Event) AsEvent() *Event {
	return o
}
<commit_msg>Add GstEventType definition<commit_after>//GstEvent — Structure describing events that are passed up and down a pipeline
package gst

/*
#include <stdlib.h>
#include <gst/gst.h>
*/
import "C"

import (
	//"errors"
	"github.com/lidouf/glib"
	//"time"
	//"unsafe"
)

type Event struct {
	glib.Object
}

func (o *Event) g() *C.GstEvent {
	return (*C.GstEvent)(o.GetPtr())
}

func (o *Event) AsEvent() *Event {
	return o
}

type EventType C.GstEventType

const (
	EVENT_UNKNOWN = EventType(C.GST_EVENT_UNKNOWN)
	/* bidirectional events */
	EVENT_FLUSH_START = EventType(C.GST_EVENT_FLUSH_START)
	EVENT_FLUSH_STOP  = EventType(C.GST_EVENT_FLUSH_STOP)
	/* downstream serialized events */
	EVENT_STREAM_START = EventType(C.GST_EVENT_STREAM_START)
	EVENT_CAPS         = EventType(C.GST_EVENT_CAPS)
	EVENT_SEGMENT      = EventType(C.GST_EVENT_SEGMENT)
	EVENT_TAG          = EventType(C.GST_EVENT_TAG)
	EVENT_BUFFERSIZE   = EventType(C.GST_EVENT_BUFFERSIZE)
	EVENT_SINK_MESSAGE = EventType(C.GST_EVENT_SINK_MESSAGE)
	EVENT_EOS          = EventType(C.GST_EVENT_EOS)
	EVENT_TOC          = EventType(C.GST_EVENT_TOC)
	EVENT_PROTECTION   = EventType(C.GST_EVENT_PROTECTION)
	/* non-sticky downstream serialized */
	EVENT_SEGMENT_DONE = EventType(C.GST_EVENT_SEGMENT_DONE)
	EVENT_GAP          = EventType(C.GST_EVENT_GAP)
	/* upstream events */
	EVENT_QOS         = EventType(C.GST_EVENT_QOS)
	EVENT_SEEK        = EventType(C.GST_EVENT_SEEK)
	EVENT_NAVIGATION  = EventType(C.GST_EVENT_NAVIGATION)
	EVENT_LATENCY     = EventType(C.GST_EVENT_LATENCY)
	EVENT_STEP        = EventType(C.GST_EVENT_STEP)
	EVENT_RECONFIGURE = EventType(C.GST_EVENT_RECONFIGURE)
	EVENT_TOC_SELECT  = EventType(C.GST_EVENT_TOC_SELECT)
	/* custom events start here */
	EVENT_CUSTOM_UPSTREAM          = EventType(C.GST_EVENT_CUSTOM_UPSTREAM)
	EVENT_CUSTOM_DOWNSTREAM        = EventType(C.GST_EVENT_CUSTOM_DOWNSTREAM)
	EVENT_CUSTOM_DOWNSTREAM_OOB    = EventType(C.GST_EVENT_CUSTOM_DOWNSTREAM_OOB)
	EVENT_CUSTOM_DOWNSTREAM_STICKY = EventType(C.GST_EVENT_CUSTOM_DOWNSTREAM_STICKY)
	EVENT_CUSTOM_BOTH              = EventType(C.GST_EVENT_CUSTOM_BOTH)
	EVENT_CUSTOM_BOTH_OOB          = EventType(C.GST_EVENT_CUSTOM_BOTH_OOB)
)
<|endoftext|>


<commit_before>package api

import (
	"cf"
	"cf/configuration"
	"code.google.com/p/go.net/websocket"
	"code.google.com/p/gogoprotobuf/proto"
	"github.com/cloudfoundry/loggregatorlib/logmessage"
	"github.com/stretchr/testify/assert"
	"net/http/httptest"
	"strings"
	testapi "testhelpers/api"
	"testing"
	"time"
)

func TestRecentLogsFor(t *testing.T) {

	messagesSent := [][]byte{
		marshalledLogMessageWithTime(t, "My message", int64(3000)),
	}

	websocketEndpoint := func(conn *websocket.Conn) {
		request := conn.Request()
		assert.Equal(t, request.URL.Path, "/dump/")
		assert.Equal(t, request.URL.RawQuery, "app=my-app-guid")
		assert.Equal(t, request.Method, "GET")
		assert.Contains(t, request.Header.Get("Authorization"), "BEARER my_access_token")

		for _, msg := range messagesSent {
			conn.Write(msg)
		}
		time.Sleep(time.Duration(2) * time.Second)
		conn.Close()
	}
	websocketServer := httptest.NewTLSServer(websocket.Handler(websocketEndpoint))
	defer websocketServer.Close()

	expectedMessage, err := logmessage.ParseMessage(messagesSent[0])
	assert.NoError(t, err)

	config := &configuration.Configuration{AccessToken: "BEARER my_access_token", Target: "https://localhost"}

	endpointRepo := &testapi.FakeEndpointRepo{GetEndpointEndpoints: map[cf.EndpointType]string{
		cf.LoggregatorEndpointKey: strings.Replace(websocketServer.URL, "https", "wss", 1),
	}}

	logsRepo := NewLoggregatorLogsRepository(config, endpointRepo)

	connected := false
	onConnect := func() {
		connected = true
	}

	logChan := make(chan *logmessage.Message, 1000)

	err = logsRepo.RecentLogsFor("my-app-guid", onConnect, logChan)
	close(logChan)

	dumpedMessages := []*logmessage.Message{}
	for msg := range logChan {
		dumpedMessages = append(dumpedMessages, msg)
	}

	assert.NoError(t, err)

	assert.Equal(t, len(dumpedMessages), 1)
	assert.Equal(t, dumpedMessages[0].GetLogMessage().GetSourceName(), expectedMessage.GetLogMessage().GetSourceName())
	assert.Equal(t, dumpedMessages[0].GetLogMessage().GetMessage(), expectedMessage.GetLogMessage().GetMessage())
	assert.Equal(t, dumpedMessages[0].GetLogMessage().GetMessageType(), expectedMessage.GetLogMessage().GetMessageType())
}

func TestTailsLogsFor(t *testing.T) {

	messagesSent := [][]byte{
		marshalledLogMessageWithTime(t, "My message 3", int64(300000)),
		marshalledLogMessageWithTime(t, "My message 1", int64(100000)),
		marshalledLogMessageWithTime(t, "My message 2", int64(200000)),
	}

	websocketEndpoint := func(conn *websocket.Conn) {
		request := conn.Request()
		assert.Equal(t, request.URL.Path, "/tail/")
		assert.Equal(t, request.URL.RawQuery, "app=my-app-guid")
		assert.Equal(t, request.Method, "GET")
		assert.Contains(t, request.Header.Get("Authorization"), "BEARER my_access_token")

		for _, msg := range messagesSent {
			conn.Write(msg)
		}
		time.Sleep(time.Duration(200) * time.Millisecond)
		conn.Close()
	}
	websocketServer := httptest.NewTLSServer(websocket.Handler(websocketEndpoint))
	defer websocketServer.Close()

	config := &configuration.Configuration{AccessToken: "BEARER my_access_token", Target: "https://localhost"}
	endpointRepo := &testapi.FakeEndpointRepo{GetEndpointEndpoints: map[cf.EndpointType]string{
		cf.LoggregatorEndpointKey: strings.Replace(websocketServer.URL, "https", "wss", 1),
	}}

	logsRepo := NewLoggregatorLogsRepository(config, endpointRepo)

	connected := false
	onConnect := func() {
		connected = true
	}

	tailedMessages := []*logmessage.Message{}

	logChan := make(chan *logmessage.Message, 1000)

	controlChan := make(chan bool)

	logsRepo.TailLogsFor("my-app-guid", onConnect, logChan, controlChan, time.Duration(1))
	close(logChan)

	for msg := range logChan {
		tailedMessages = append(tailedMessages, msg)
	}

	assert.True(t, connected)

	assert.Equal(t, len(tailedMessages), 3)

	tailedMessage := tailedMessages[0]
	actualMessage, err := proto.Marshal(tailedMessage.GetLogMessage())
	assert.NoError(t, err)
	assert.Equal(t, actualMessage, messagesSent[1])

	tailedMessage = tailedMessages[1]
	actualMessage, err = proto.Marshal(tailedMessage.GetLogMessage())
	assert.NoError(t, err)
	assert.Equal(t, actualMessage, messagesSent[2])

	tailedMessage = tailedMessages[2]
	actualMessage, err = proto.Marshal(tailedMessage.GetLogMessage())
	assert.NoError(t, err)
	assert.Equal(t, actualMessage, messagesSent[0])
}

func TestMessageOutputTimesDuringNormalFlow(t *testing.T) {

	startTime := time.Now()
	messagesSent := [][]byte{
		marshalledLogMessageWithTime(t, "My message 1", startTime.Add(-9*time.Second).UnixNano()),
		marshalledLogMessageWithTime(t, "My message 2", startTime.Add(-2*time.Second).UnixNano()),
		marshalledLogMessageWithTime(t, "My message 3", startTime.Add(-1*time.Second).UnixNano()),
	}

	websocketEndpoint := func(conn *websocket.Conn) {
		request := conn.Request()
		assert.Equal(t, request.URL.Path, "/tail/")
		assert.Equal(t, request.URL.RawQuery, "app=my-app-guid")
		assert.Equal(t, request.Method, "GET")
		assert.Contains(t, request.Header.Get("Authorization"), "BEARER my_access_token")

		for _, msg := range messagesSent {
			conn.Write(msg)
			time.Sleep(200 * time.Millisecond)
		}
		time.Sleep(1 * time.Second)
		conn.Close()
	}
	websocketServer := httptest.NewTLSServer(websocket.Handler(websocketEndpoint))
	defer websocketServer.Close()

	config := &configuration.Configuration{AccessToken: "BEARER my_access_token", Target: "https://localhost"}
	endpointRepo := &testapi.FakeEndpointRepo{GetEndpointEndpoints: map[cf.EndpointType]string{
		cf.LoggregatorEndpointKey: strings.Replace(websocketServer.URL, "https", "wss", 1),
	}}

	logsRepo := NewLoggregatorLogsRepository(config, endpointRepo)

	logChan := make(chan *logmessage.Message, 1000)
	controlChan := make(chan bool)

	go func() {
		defer close(logChan)
		logsRepo.TailLogsFor("my-app-guid", func() {}, logChan, controlChan, time.Duration(1*time.Second))
	}()

	for msg := range logChan {

		timeWhenOutputtable := startTime.Add(1 * time.Second).UnixNano()
		timeNow := time.Now().UnixNano()

		switch string(msg.GetLogMessage().Message) {
		case "My message 1":
			assert.True(t, (timeNow-timeWhenOutputtable) < (50*time.Millisecond).Nanoseconds())
			assert.True(t, (timeNow-timeWhenOutputtable) > (10*time.Millisecond).Nanoseconds())
		case "My message 2":
			assert.True(t, (timeNow-timeWhenOutputtable) < (250*time.Millisecond).Nanoseconds())
			assert.True(t, (timeNow-timeWhenOutputtable) > (200*time.Millisecond).Nanoseconds())
		case "My message 3":
			assert.True(t, (timeNow-timeWhenOutputtable) < (450*time.Millisecond).Nanoseconds())
			assert.True(t, (timeNow-timeWhenOutputtable) > (400*time.Millisecond).Nanoseconds())
		}
	}
}

func TestMessageOutputWhenFlushingAfterServerDeath(t *testing.T) {

	startTime := time.Now()
	messagesSent := [][]byte{
		marshalledLogMessageWithTime(t, "My message 1", startTime.Add(-9*time.Second).UnixNano()),
		marshalledLogMessageWithTime(t, "My message 2", startTime.Add(-2*time.Second).UnixNano()),
		marshalledLogMessageWithTime(t, "My message 3", startTime.Add(-1*time.Second).UnixNano()),
	}

	websocketEndpoint := func(conn *websocket.Conn) {
		request := conn.Request()
		assert.Equal(t, request.URL.Path, "/tail/")
		assert.Equal(t, request.URL.RawQuery, "app=my-app-guid")
		assert.Equal(t, request.Method, "GET")
		assert.Contains(t, request.Header.Get("Authorization"), "BEARER my_access_token")

		for _, msg := range messagesSent {
			conn.Write(msg)
			time.Sleep(200 * time.Millisecond)
		}
		conn.Close()
	}
	websocketServer := httptest.NewTLSServer(websocket.Handler(websocketEndpoint))
	defer websocketServer.Close()

	config := &configuration.Configuration{AccessToken: "BEARER my_access_token", Target: "https://localhost"}
	endpointRepo := &testapi.FakeEndpointRepo{GetEndpointEndpoints: map[cf.EndpointType]string{
		cf.LoggregatorEndpointKey: strings.Replace(websocketServer.URL, "https", "wss", 1),
	}}

	logsRepo := NewLoggregatorLogsRepository(config, endpointRepo)

	firstMessageTime := time.Now().Add(-10 * time.Second).UnixNano()

	logChan := make(chan *logmessage.Message, 1000)
	controlChan := make(chan bool)

	go func() {
		defer close(logChan)
		logsRepo.TailLogsFor("my-app-guid", func() {}, logChan, controlChan, time.Duration(1*time.Second))
	}()

	for msg := range logChan {
		switch string(msg.GetLogMessage().Message) {
		case "My message 1":
			firstMessageTime = time.Now().UnixNano()
		case "My message 2":
			timeNow := time.Now().UnixNano()
			delta := timeNow - firstMessageTime
			assert.True(t, delta < (5*time.Millisecond).Nanoseconds())
			assert.True(t, delta >= 0)
		case "My message 3":
			timeNow := time.Now().UnixNano()
			delta := timeNow - firstMessageTime
			assert.True(t, delta < (5*time.Millisecond).Nanoseconds())
			assert.True(t, delta >= 0)
		}
	}
}

func marshalledLogMessageWithTime(t *testing.T, messageString string, timestamp int64) []byte {
	messageType := logmessage.LogMessage_OUT
	sourceName := "DEA"
	protoMessage := &logmessage.LogMessage{
		Message:     []byte(messageString),
		AppId:       proto.String("my-app-guid"),
		MessageType: &messageType,
		SourceName:  &sourceName,
		Timestamp:   proto.Int64(timestamp),
	}

	message, err := proto.Marshal(protoMessage)
	assert.NoError(t, err)

	return message
}
<commit_msg>Speed up logs test<commit_after>package api

import (
	"cf"
	"cf/configuration"
	"code.google.com/p/go.net/websocket"
	"code.google.com/p/gogoprotobuf/proto"
	"github.com/cloudfoundry/loggregatorlib/logmessage"
	"github.com/stretchr/testify/assert"
	"net/http/httptest"
	"strings"
	testapi "testhelpers/api"
	"testing"
	"time"
)

func TestRecentLogsFor(t *testing.T) {
	messagesSent := [][]byte{
		marshalledLogMessageWithTime(t, "My message", int64(3000)),
	}

	websocketEndpoint := func(conn *websocket.Conn) {
		request := conn.Request()
		assert.Equal(t, request.URL.Path, "/dump/")
		assert.Equal(t, request.URL.RawQuery, "app=my-app-guid")
		assert.Equal(t, request.Method, "GET")
		assert.Contains(t, request.Header.Get("Authorization"), "BEARER my_access_token")

		for _, msg := range messagesSent {
			conn.Write(msg)
		}
		conn.Close()
	}
	websocketServer := httptest.NewTLSServer(websocket.Handler(websocketEndpoint))
	defer websocketServer.Close()

	expectedMessage, err := logmessage.ParseMessage(messagesSent[0])
	assert.NoError(t, err)

	config := &configuration.Configuration{AccessToken: "BEARER my_access_token", Target: "https://localhost"}

	endpointRepo := &testapi.FakeEndpointRepo{GetEndpointEndpoints: map[cf.EndpointType]string{
		cf.LoggregatorEndpointKey: strings.Replace(websocketServer.URL, "https", "wss", 1),
	}}

	logsRepo := NewLoggregatorLogsRepository(config, endpointRepo)

	connected := false
	onConnect := func() {
		connected = true
	}

	logChan := make(chan *logmessage.Message, 1000)

	err = logsRepo.RecentLogsFor("my-app-guid", onConnect, logChan)
	close(logChan)

	dumpedMessages := []*logmessage.Message{}
	for msg := range logChan {
		dumpedMessages = append(dumpedMessages, msg)
	}

	assert.NoError(t, err)

	assert.Equal(t, len(dumpedMessages), 1)
	assert.Equal(t, dumpedMessages[0].GetLogMessage().GetSourceName(), expectedMessage.GetLogMessage().GetSourceName())
	assert.Equal(t, dumpedMessages[0].GetLogMessage().GetMessage(), expectedMessage.GetLogMessage().GetMessage())
	assert.Equal(t, dumpedMessages[0].GetLogMessage().GetMessageType(), expectedMessage.GetLogMessage().GetMessageType())
}

func TestTailsLogsFor(t *testing.T) {
	messagesSent := [][]byte{
		marshalledLogMessageWithTime(t, "My message 3", int64(300000)),
		marshalledLogMessageWithTime(t, "My message 1", int64(100000)),
		marshalledLogMessageWithTime(t, "My message 2", int64(200000)),
	}

	websocketEndpoint := func(conn *websocket.Conn) {
		request := conn.Request()
		assert.Equal(t, request.URL.Path, "/tail/")
		assert.Equal(t, request.URL.RawQuery, "app=my-app-guid")
		assert.Equal(t, request.Method, "GET")
		assert.Contains(t, request.Header.Get("Authorization"), "BEARER my_access_token")

		for _, msg := range messagesSent {
			conn.Write(msg)
		}
		conn.Close()
	}
	websocketServer := httptest.NewTLSServer(websocket.Handler(websocketEndpoint))
	defer websocketServer.Close()

	config := &configuration.Configuration{AccessToken: "BEARER my_access_token", Target: "https://localhost"}
	endpointRepo := &testapi.FakeEndpointRepo{GetEndpointEndpoints: map[cf.EndpointType]string{
		cf.LoggregatorEndpointKey: strings.Replace(websocketServer.URL, "https", "wss", 1),
	}}

	logsRepo := NewLoggregatorLogsRepository(config, endpointRepo)

	connected := false
	onConnect := func() {
		connected = true
	}

	tailedMessages := []*logmessage.Message{}

	logChan := make(chan *logmessage.Message, 1000)

	controlChan := make(chan bool)

	logsRepo.TailLogsFor("my-app-guid", onConnect, logChan, controlChan, time.Duration(1))
	close(logChan)

	for msg := range logChan {
		tailedMessages = append(tailedMessages, msg)
	}

	assert.True(t, connected)

	assert.Equal(t, len(tailedMessages), 3)

	tailedMessage := tailedMessages[0]
	actualMessage, err := proto.Marshal(tailedMessage.GetLogMessage())
	assert.NoError(t, err)
	assert.Equal(t, actualMessage, messagesSent[1])

	tailedMessage = tailedMessages[1]
	actualMessage, err = proto.Marshal(tailedMessage.GetLogMessage())
	assert.NoError(t, err)
	assert.Equal(t, actualMessage, messagesSent[2])

	tailedMessage = tailedMessages[2]
	actualMessage, err = proto.Marshal(tailedMessage.GetLogMessage())
	assert.NoError(t, err)
	assert.Equal(t, actualMessage, messagesSent[0])
}

func TestMessageOutputOrder(t *testing.T) {
	startTime := time.Now()
	messagesSent := [][]byte{
		marshalledLogMessageWithTime(t, "My message 1", startTime.UnixNano()),
		marshalledLogMessageWithTime(t, "My message 2", startTime.UnixNano()),
		marshalledLogMessageWithTime(t, "My message 3", startTime.UnixNano()),
	}

	websocketEndpoint := func(conn *websocket.Conn) {
		request := conn.Request()
		assert.Equal(t, request.URL.Path, "/tail/")
		assert.Equal(t, request.URL.RawQuery, "app=my-app-guid")
		assert.Equal(t, request.Method, "GET")
		assert.Contains(t, request.Header.Get("Authorization"), "BEARER my_access_token")

		for _, msg := range messagesSent {
			conn.Write(msg)
		}
		conn.Close()
	}
	websocketServer := httptest.NewTLSServer(websocket.Handler(websocketEndpoint))
	defer websocketServer.Close()

	config := &configuration.Configuration{AccessToken: "BEARER my_access_token", Target: "https://localhost"}
	endpointRepo := &testapi.FakeEndpointRepo{GetEndpointEndpoints: map[cf.EndpointType]string{
		cf.LoggregatorEndpointKey: strings.Replace(websocketServer.URL, "https", "wss", 1),
	}}

	logsRepo := NewLoggregatorLogsRepository(config, endpointRepo)

	logChan := make(chan *logmessage.Message, 1000)
	controlChan := make(chan bool)

	go func() {
		defer close(logChan)
		logsRepo.TailLogsFor("my-app-guid", func() {}, logChan, controlChan, time.Duration(1*time.Second))
	}()

	var messages []string
	for msg := range logChan {
		messages = append(messages, string(msg.GetLogMessage().Message))
	}

	assert.Equal(t, messages, []string{"My message 1", "My message 2", "My message 3"})
}

func TestMessageOutputWhenFlushingAfterServerDeath(t *testing.T) {
	startTime := time.Now()
	messagesSent := [][]byte{
		marshalledLogMessageWithTime(t, "My message 1", startTime.UnixNano()),
		marshalledLogMessageWithTime(t, "My message 2", startTime.UnixNano()),
		marshalledLogMessageWithTime(t, "My message 3", startTime.UnixNano()),
	}

	websocketEndpoint := func(conn *websocket.Conn) {
		request := conn.Request()
		assert.Equal(t, request.URL.Path, "/tail/")
		assert.Equal(t, request.URL.RawQuery, "app=my-app-guid")
		assert.Equal(t, request.Method, "GET")
		assert.Contains(t, request.Header.Get("Authorization"), "BEARER my_access_token")

		for _, msg := range messagesSent {
			conn.Write(msg)
		}
		conn.Close()
	}
	websocketServer := httptest.NewTLSServer(websocket.Handler(websocketEndpoint))
	defer websocketServer.Close()

	config := &configuration.Configuration{AccessToken: "BEARER my_access_token", Target: "https://localhost"}
	endpointRepo := &testapi.FakeEndpointRepo{GetEndpointEndpoints: map[cf.EndpointType]string{
		cf.LoggregatorEndpointKey: strings.Replace(websocketServer.URL, "https", "wss", 1),
	}}

	logsRepo := NewLoggregatorLogsRepository(config, endpointRepo)

	firstMessageTime := time.Now().Add(-10 * time.Second).UnixNano()

	logChan := make(chan *logmessage.Message, 1000)
	controlChan := make(chan bool)

	go func() {
		defer close(logChan)
		logsRepo.TailLogsFor("my-app-guid", func() {}, logChan, controlChan, time.Duration(1*time.Second))
	}()

	for msg := range logChan {
		switch string(msg.GetLogMessage().Message) {
		case "My message 1":
			firstMessageTime = time.Now().UnixNano()
		case "My message 2":
			timeNow := time.Now().UnixNano()
			delta := timeNow - firstMessageTime
			assert.True(t, delta < (5*time.Millisecond).Nanoseconds())
			assert.True(t, delta >= 0)
		case "My message 3":
			timeNow := time.Now().UnixNano()
			delta := timeNow - firstMessageTime
			assert.True(t, delta < (5*time.Millisecond).Nanoseconds())
			assert.True(t, delta >= 0)
		}
	}
}

func marshalledLogMessageWithTime(t *testing.T, messageString string, timestamp int64) []byte {
	messageType := logmessage.LogMessage_OUT
	sourceName := "DEA"
	protoMessage := &logmessage.LogMessage{
		Message:     []byte(messageString),
		AppId:       proto.String("my-app-guid"),
		MessageType: &messageType,
		SourceName:  &sourceName,
		Timestamp:   proto.Int64(timestamp),
	}

	message, err := proto.Marshal(protoMessage)
	assert.NoError(t, err)

	return message
}
<|endoftext|>


<commit_before>// Copyright (C) 2016 The Syncthing Authors.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.

package connections

import (
	"crypto/tls"
	"net"
	"net/url"
	"strings"
	"sync"
	"time"

	"github.com/syncthing/syncthing/lib/config"
	"github.com/syncthing/syncthing/lib/dialer"
	"github.com/syncthing/syncthing/lib/nat"
)

func init() {
	factory := &tcpListenerFactory{}
	for _, scheme := range []string{"tcp", "tcp4", "tcp6"} {
		listeners[scheme] = factory
	}
}

type tcpListener struct {
	onAddressesChangedNotifier

	uri     *url.URL
	tlsCfg  *tls.Config
	stop    chan struct{}
	conns   chan IntermediateConnection
	factory listenerFactory

	natService *nat.Service
	mapping    *nat.Mapping

	err error
	mut sync.RWMutex
}

func (t *tcpListener) Serve() {
	t.mut.Lock()
	t.err = nil
	t.mut.Unlock()

	tcaddr, err := net.ResolveTCPAddr(t.uri.Scheme, t.uri.Host)
	if err != nil {
		t.mut.Lock()
		t.err = err
		t.mut.Unlock()
		l.Infoln("listen (BEP/tcp):", err)
		return
	}

	listener, err := net.ListenTCP(t.uri.Scheme, tcaddr)
	if err != nil {
		t.mut.Lock()
		t.err = err
		t.mut.Unlock()
		l.Infoln("listen (BEP/tcp):", err)
		return
	}
	defer listener.Close()

	l.Infof("TCP listener (%v) starting", listener.Addr())
	defer l.Infof("TCP listener (%v) shutting down", listener.Addr())

	mapping := t.natService.NewMapping(nat.TCP, tcaddr.IP, tcaddr.Port)
	mapping.OnChanged(func(_ *nat.Mapping, _, _ []nat.Address) {
		t.notifyAddressesChanged(t)
	})
	defer t.natService.RemoveMapping(mapping)

	t.mut.Lock()
	t.mapping = mapping
	t.mut.Unlock()

	for {
		listener.SetDeadline(time.Now().Add(time.Second))
		conn, err := listener.Accept()
		select {
		case <-t.stop:
			if err == nil {
				conn.Close()
			}
			t.mut.Lock()
			t.mapping = nil
			t.mut.Unlock()
			return
		default:
		}
		if err != nil {
			if err, ok := err.(*net.OpError); !ok || !err.Timeout() {
				l.Warnln("Accepting connection (BEP/tcp):", err)
			}
			continue
		}

		l.Debugln("connect from", conn.RemoteAddr())

		err = dialer.SetTCPOptions(conn.(*net.TCPConn))
		if err != nil {
			l.Infoln(err)
		}

		tc := tls.Server(conn, t.tlsCfg)
		err = tc.Handshake()
		if err != nil {
			l.Infoln("TLS handshake (BEP/tcp):", err)
			tc.Close()
			continue
		}

		t.conns <- IntermediateConnection{tc, "TCP (Server)", tcpPriority}
	}
}

func (t *tcpListener) Stop() {
	close(t.stop)
}

func (t *tcpListener) URI() *url.URL {
	return t.uri
}

func (t *tcpListener) WANAddresses() []*url.URL {
	uris := t.LANAddresses()
	t.mut.RLock()
	if t.mapping != nil {
		addrs := t.mapping.ExternalAddresses()
		for _, addr := range addrs {
			uri := *t.uri
			// Does net.JoinHostPort internally
			uri.Host = addr.String()
			uris = append(uris, &uri)
		}
	}
	t.mut.RUnlock()
	return uris
}

func (t *tcpListener) LANAddresses() []*url.URL {
	return []*url.URL{t.uri}
}

func (t *tcpListener) Error() error {
	t.mut.RLock()
	err := t.err
	t.mut.RUnlock()
	return err
}

func (t *tcpListener) String() string {
	return t.uri.String()
}

func (t *tcpListener) Factory() listenerFactory {
	return t.factory
}

type tcpListenerFactory struct{}

func (f *tcpListenerFactory) New(uri *url.URL, cfg *config.Wrapper, tlsCfg *tls.Config, conns chan IntermediateConnection, natService *nat.Service) genericListener {
	return &tcpListener{
		uri:        fixupPort(uri),
		tlsCfg:     tlsCfg,
		conns:      conns,
		natService: natService,
		stop:       make(chan struct{}),
		factory:    f,
	}
}

func (tcpListenerFactory) Enabled(cfg config.Configuration) bool {
	return true
}

func fixupPort(uri *url.URL) *url.URL {
	copyURI := *uri

	host, port, err := net.SplitHostPort(uri.Host)
	if err != nil && strings.HasPrefix(err.Error(), "missing port") {
		// addr is on the form "1.2.3.4"
		copyURI.Host = net.JoinHostPort(host, "22000")
	} else if err == nil && port == "" {
		// addr is on the form "1.2.3.4:"
		copyURI.Host = net.JoinHostPort(host, "22000")
	}

	return &copyURI
}
<commit_msg>lib/connections: Correctly add port to portless tcp:// URLs (fixes #3115)<commit_after>// Copyright (C) 2016 The Syncthing Authors.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.

package connections

import (
	"crypto/tls"
	"net"
	"net/url"
	"strings"
	"sync"
	"time"

	"github.com/syncthing/syncthing/lib/config"
	"github.com/syncthing/syncthing/lib/dialer"
	"github.com/syncthing/syncthing/lib/nat"
)

func init() {
	factory := &tcpListenerFactory{}
	for _, scheme := range []string{"tcp", "tcp4", "tcp6"} {
		listeners[scheme] = factory
	}
}

type tcpListener struct {
	onAddressesChangedNotifier

	uri     *url.URL
	tlsCfg  *tls.Config
	stop    chan struct{}
	conns   chan IntermediateConnection
	factory listenerFactory

	natService *nat.Service
	mapping    *nat.Mapping

	err error
	mut sync.RWMutex
}

func (t *tcpListener) Serve() {
	t.mut.Lock()
	t.err = nil
	t.mut.Unlock()

	tcaddr, err := net.ResolveTCPAddr(t.uri.Scheme, t.uri.Host)
	if err != nil {
		t.mut.Lock()
		t.err = err
		t.mut.Unlock()
		l.Infoln("listen (BEP/tcp):", err)
		return
	}

	listener, err := net.ListenTCP(t.uri.Scheme, tcaddr)
	if err != nil {
		t.mut.Lock()
		t.err = err
		t.mut.Unlock()
		l.Infoln("listen (BEP/tcp):", err)
		return
	}
	defer listener.Close()

	l.Infof("TCP listener (%v) starting", listener.Addr())
	defer l.Infof("TCP listener (%v) shutting down", listener.Addr())

	mapping := t.natService.NewMapping(nat.TCP, tcaddr.IP, tcaddr.Port)
	mapping.OnChanged(func(_ *nat.Mapping, _, _ []nat.Address) {
		t.notifyAddressesChanged(t)
	})
	defer t.natService.RemoveMapping(mapping)

	t.mut.Lock()
	t.mapping = mapping
	t.mut.Unlock()

	for {
		listener.SetDeadline(time.Now().Add(time.Second))
		conn, err := listener.Accept()
		select {
		case <-t.stop:
			if err == nil {
				conn.Close()
			}
			t.mut.Lock()
			t.mapping = nil
			t.mut.Unlock()
			return
		default:
		}
		if err != nil {
			if err, ok := err.(*net.OpError); !ok || !err.Timeout() {
				l.Warnln("Accepting connection (BEP/tcp):", err)
			}
			continue
		}

		l.Debugln("connect from", conn.RemoteAddr())

		err = dialer.SetTCPOptions(conn.(*net.TCPConn))
		if err != nil {
			l.Infoln(err)
		}

		tc := tls.Server(conn, t.tlsCfg)
		err = tc.Handshake()
		if err != nil {
			l.Infoln("TLS handshake (BEP/tcp):", err)
			tc.Close()
			continue
		}

		t.conns <- IntermediateConnection{tc, "TCP (Server)", tcpPriority}
	}
}

func (t *tcpListener) Stop() {
	close(t.stop)
}

func (t *tcpListener) URI() *url.URL {
	return t.uri
}

func (t *tcpListener) WANAddresses() []*url.URL {
	uris := t.LANAddresses()
	t.mut.RLock()
	if t.mapping != nil {
		addrs := t.mapping.ExternalAddresses()
		for _, addr := range addrs {
			uri := *t.uri
			// Does net.JoinHostPort internally
			uri.Host = addr.String()
			uris = append(uris, &uri)
		}
	}
	t.mut.RUnlock()
	return uris
}

func (t *tcpListener) LANAddresses() []*url.URL {
	return []*url.URL{t.uri}
}

func (t *tcpListener) Error() error {
	t.mut.RLock()
	err := t.err
	t.mut.RUnlock()
	return err
}

func (t *tcpListener) String() string {
	return t.uri.String()
}

func (t *tcpListener) Factory() listenerFactory {
	return t.factory
}

type tcpListenerFactory struct{}

func (f *tcpListenerFactory) New(uri *url.URL, cfg *config.Wrapper, tlsCfg *tls.Config, conns chan IntermediateConnection, natService *nat.Service) genericListener {
	return &tcpListener{
		uri:        fixupPort(uri),
		tlsCfg:     tlsCfg,
		conns:      conns,
		natService: natService,
		stop:       make(chan struct{}),
		factory:    f,
	}
}

func (tcpListenerFactory) Enabled(cfg config.Configuration) bool {
	return true
}

func fixupPort(uri *url.URL) *url.URL {
	copyURI := *uri

	host, port, err := net.SplitHostPort(uri.Host)
	if err != nil && strings.HasPrefix(err.Error(), "missing port") {
		// addr is on the form "1.2.3.4"
		copyURI.Host = net.JoinHostPort(uri.Host, "22000")
	} else if err == nil && port == "" {
		// addr is on the form "1.2.3.4:"
		copyURI.Host = net.JoinHostPort(host, "22000")
	}

	return &copyURI
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"github.com/rbetts/voltdbgo/voltdb"
	"log"
)

// A simple example using the voltdb/examples/voter application.

type ResultsRow struct {
	Contestant string
	Id         int
	Votes      int
}

func (row *ResultsRow) GoString() string {
	return fmt.Sprintf("%v\t%v\t%v\n", row.Contestant, row.Id, row.Votes)
}

func main() {
	volt, err := voltdb.NewConnection("username", "", "localhost:21212")
	if err != nil {
		log.Fatalf("Connection error %v\n", err)
	}
	if !volt.TestConnection() {
		log.Fatalf("Connection error: failed to ping VoltDB database.")
	}
	printResults(volt)
	volt.Close()
}

func printResults(volt *voltdb.Conn) {
	var row ResultsRow
	response, _ := volt.Call("Results")
	table := response.Table(0)

	for table.HasNext() {
		if err := table.Next(&row); err != nil {
			log.Fatalf("Table iteration error %v\n", err)
		}
		fmt.Printf("%#v", &row)
	}
}
<commit_msg>A more complete voter example.<commit_after>// An example using the voltdb/examples/voter application.
// To run this, first start the voltdb voter example:
// `cd voltdb-x.y.z/example/voter && ./run.sh`.
// Then run this go program.
package main

import (
	"fmt"
	"github.com/rbetts/voltdbgo/voltdb"
	"log"
	"math/rand"
    "os"
	"time"
    "runtime/pprof"
)

var ttlContestants = 6
var contestants = "Andy,Bob,Cathy,Doug,Erik,Greg"
var voterGoroutines = 8
var votingDuration time.Duration = 100 * time.Second

// ScalarResult is used to read scalar stored procedures results.
type ScalarResult struct {
	Result int
}

func main() {
	volt, err := voltdb.NewConnection("username", "", "localhost:21212")
	defer volt.Close()
	if err != nil {
		log.Fatalf("Connection error %v\n", err)
	}
	if !volt.TestConnection() {
		log.Fatalf("Connection error: failed to ping VoltDB database.")
	}

    f, err := os.Create("/Users/rbetts/voterprof")
    if err != nil {
        log.Fatal(err)
    }

	initialize(volt)
    pprof.StartCPUProfile(f)
    vote();
    pprof.StopCPUProfile()
	printResults(volt)
}

// Add contestants to the database if necessary
func initialize(volt *voltdb.Conn) {
	rsp, err := volt.Call("Initialize", ttlContestants, contestants)
	if err != nil {
		log.Fatalf("Failed in initialize database. %v\n", err)
	}
	if rsp.Status() == voltdb.SUCCESS {
		var rs ScalarResult
		rsp.Table(0).Next(&rs)
		fmt.Printf("Initialized %d contestants.\n", rs.Result)
	} else {
		log.Fatalf("Failed to initialize %#v.\n", rsp)
    }
}

// vote starts voterGoroutine number votes loops and returns when
// they have all run to conclusion.
func vote() {
	var joiners = make([]chan int, 0)
	for i := 0; i < voterGoroutines; i++ {
		var joinchan = make(chan int)
		joiners = append(joiners, joinchan)
		go placeVotes(joinchan)
	}
    var totalVotes = 0
	for v, join := range joiners {
		votes := <-join
        totalVotes += votes
		fmt.Printf("Voter %v finished and placed %v votes.\n", v, votes)
	}
    fmt.Printf("Generated %v votes in %v seconds (%0.0f votes/second)\n",
        totalVotes, votingDuration.Seconds(),
        float64(totalVotes)/votingDuration.Seconds())
	return
}

// placeVotes votes for votingDuration seconds.
func placeVotes(join chan int) {
	volt, err := voltdb.NewConnection("username", "", "localhost:21212")
	defer volt.Close()
	if err != nil {
		log.Fatalf("Connection error db. %v\n", err)
	}

	timeout := time.After(votingDuration)
	placedVotes := 0

	for {
		select {
		case <-timeout:
			join <- placedVotes
			return
		default:
			// construct a phoneNumber with a valid area code.
			var phoneNumber int64 = (5080000000 + int64(rand.Int31()))
			// pick a contestant at random (contestant ids are 1-based)
			var contestant = (rand.Int() % ttlContestants) + 1
			rsp, err := volt.Call("Vote", phoneNumber, contestant, 100)
			if err != nil {
				log.Fatalf("Error voting. %v\n", err)
			}
			if rsp.Status() == voltdb.SUCCESS {
                placedVotes++
			} else {
				fmt.Printf("Vote failed %#v\n", rsp)
			}
		}
	}
}

// printResults displays the current vote tally for each contestant.
func printResults(volt *voltdb.Conn) {
    type ResultsRow struct {
        Contestant string
        Id         int
        Votes      int
    }
	var row ResultsRow
    fmt.Printf("\nCurrent results:\n")
	response, _ := volt.Call("Results")
	table := response.Table(0)
	for table.HasNext() {
		if err := table.Next(&row); err != nil {
			log.Fatalf("Table iteration error %v\n", err)
		}
        fmt.Printf("%v\t%v\t%v\n", row.Contestant, row.Id, row.Votes)
	}
}
<|endoftext|>


<commit_before>package handlers

import (
	"fmt"
	"net/http"
	"net/url"
	"strings"
	"time"

	"github.com/alphagov/router/logger"
)

const cacheDuration = 30 * time.Minute

func NewRedirectHandler(source, target string, preserve bool, temporary bool) http.Handler {
	statusMoved := http.StatusMovedPermanently
	if temporary {
		statusMoved = http.StatusFound
	}
	if preserve {
		return &pathPreservingRedirectHandler{source, target, statusMoved}
	}
	return &redirectHandler{target, statusMoved}
}

func addCacheHeaders(writer http.ResponseWriter) {
	writer.Header().Set("Expires", time.Now().Add(cacheDuration).Format(time.RFC1123))
	writer.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d, public", cacheDuration/time.Second))
}

func addGAQueryParam(target string, request *http.Request) string {
	if ga := request.URL.Query().Get("_ga"); ga != "" {
		u, err := url.Parse(target)
		if err != nil {
			defer logger.NotifySentry(logger.ReportableError{ Error: err, Request: request })
			return target
		}
		values := u.Query()
		values.Set("_ga", ga)
		u.RawQuery = values.Encode()
		return u.String()
	}
	return target
}

type redirectHandler struct {
	url  string
	code int
}

func (handler *redirectHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
	addCacheHeaders(writer)
	target := addGAQueryParam(handler.url, request)
	http.Redirect(writer, request, target, handler.code)
}

type pathPreservingRedirectHandler struct {
	sourcePrefix string
	targetPrefix string
	code         int
}

func (handler *pathPreservingRedirectHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
	target := handler.targetPrefix + strings.TrimPrefix(request.URL.Path, handler.sourcePrefix)
	if request.URL.RawQuery != "" {
		target = target + "?" + request.URL.RawQuery
	}

	addCacheHeaders(writer)
	http.Redirect(writer, request, target, handler.code)
}
<commit_msg>Run gofmt<commit_after>package handlers

import (
	"fmt"
	"net/http"
	"net/url"
	"strings"
	"time"

	"github.com/alphagov/router/logger"
)

const cacheDuration = 30 * time.Minute

func NewRedirectHandler(source, target string, preserve bool, temporary bool) http.Handler {
	statusMoved := http.StatusMovedPermanently
	if temporary {
		statusMoved = http.StatusFound
	}
	if preserve {
		return &pathPreservingRedirectHandler{source, target, statusMoved}
	}
	return &redirectHandler{target, statusMoved}
}

func addCacheHeaders(writer http.ResponseWriter) {
	writer.Header().Set("Expires", time.Now().Add(cacheDuration).Format(time.RFC1123))
	writer.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d, public", cacheDuration/time.Second))
}

func addGAQueryParam(target string, request *http.Request) string {
	if ga := request.URL.Query().Get("_ga"); ga != "" {
		u, err := url.Parse(target)
		if err != nil {
			defer logger.NotifySentry(logger.ReportableError{Error: err, Request: request})
			return target
		}
		values := u.Query()
		values.Set("_ga", ga)
		u.RawQuery = values.Encode()
		return u.String()
	}
	return target
}

type redirectHandler struct {
	url  string
	code int
}

func (handler *redirectHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
	addCacheHeaders(writer)
	target := addGAQueryParam(handler.url, request)
	http.Redirect(writer, request, target, handler.code)
}

type pathPreservingRedirectHandler struct {
	sourcePrefix string
	targetPrefix string
	code         int
}

func (handler *pathPreservingRedirectHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
	target := handler.targetPrefix + strings.TrimPrefix(request.URL.Path, handler.sourcePrefix)
	if request.URL.RawQuery != "" {
		target = target + "?" + request.URL.RawQuery
	}

	addCacheHeaders(writer)
	http.Redirect(writer, request, target, handler.code)
}
<|endoftext|>