<commit_before>/*
 * Copyright (c) 2014-2015 Conformal Systems LLC <info@conformal.com>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

package main

import (
	"errors"
	"fmt"
	"io"
	"log"
	"math/rand"
	"sync"
	"time"

	"github.com/btcsuite/btcd/btcjson"
	"github.com/btcsuite/btcd/wire"
	rpc "github.com/btcsuite/btcrpcclient"
	"github.com/btcsuite/btcutil"
)

// minFee is the minimum tx fee that can be paid
const minFee btcutil.Amount = 1e4 // 0.0001 BTC

// utxoQueue is the queue of utxos belonging to a actor
// utxos are queued after a block is received and are dispatched
// to their respective owner from com.poolUtxos
// they are dequeued from simulateTx and splitUtxos
type utxoQueue struct {
	utxos   []*TxOut
	enqueue chan *TxOut
	dequeue chan *TxOut
}

// Actor describes an actor on the simulation network.  Each actor runs
// independantly without external input to decide it's behavior.
type Actor struct {
	*Node
	quit             chan struct{}
	wg               sync.WaitGroup
	ownedAddresses   []btcutil.Address
	utxoQueue        *utxoQueue
	miningAddr       chan btcutil.Address
	walletPassphrase string
}

// TxOut is a valid tx output that can be used to generate transactions
type TxOut struct {
	OutPoint *wire.OutPoint
	Amount   btcutil.Amount
}

// NewActor creates a new actor which runs its own wallet process connecting
// to the btcd node server specified by node, and listening for simulator
// websocket connections on the specified port.
func NewActor(node *Node, port uint16) (*Actor, error) {
	// Please don't run this as root.
	if port < 1024 {
		return nil, errors.New("invalid actor port")
	}

	// Set btcwallet node args
	args, err := newBtcwalletArgs(port, node.Args.(*btcdArgs))
	if err != nil {
		return nil, err
	}

	logFile, err := getLogFile(args.prefix)
	if err != nil {
		log.Printf("Cannot get log file, logging disabled: %v", err)
	}
	btcwallet, err := NewNodeFromArgs(args, nil, logFile)
	if err != nil {
		return nil, err
	}

	a := Actor{
		Node:             btcwallet,
		quit:             make(chan struct{}),
		ownedAddresses:   make([]btcutil.Address, *maxAddresses),
		miningAddr:       make(chan btcutil.Address),
		walletPassphrase: "password",
		utxoQueue: &utxoQueue{
			enqueue: make(chan *TxOut),
			dequeue: make(chan *TxOut),
		},
	}
	return &a, nil
}

// Start creates the command to execute a wallet process and starts the
// command in the background, attaching the command's stderr and stdout
// to the passed writers. Nil writers may be used to discard output.
//
// In addition to starting the wallet process, this runs goroutines to
// handle wallet notifications and requests the wallet process to create
// an intial encrypted wallet, so that it can actually send and receive BTC.
//
// If the RPC client connection cannot be established or wallet cannot
// be created, the wallet process is killed and the actor directory
// removed.
func (a *Actor) Start(stderr, stdout io.Writer, com *Communication) error {
	connected := make(chan struct{})
	const timeoutSecs int64 = 3600 * 24

	if err := a.Node.Start(); err != nil {
		a.Shutdown()
		com.errChan <- struct{}{}
		return err
	}

	ntfnHandlers := &rpc.NotificationHandlers{
		OnClientConnected: func() {
			connected <- struct{}{}
		},
	}
	a.handlers = ntfnHandlers

	if err := a.Connect(); err != nil {
		a.Shutdown()
		com.errChan <- struct{}{}
		return err
	}

	// Wait for btcd to connect
	<-connected

	// Wait for wallet sync
	for i := 0; i < *maxConnRetries; i++ {
		if _, err := a.client.GetBalance(""); err != nil {
			time.Sleep(time.Duration(i) * 50 * time.Millisecond)
			continue
		}
		break
	}

	// Create wallet addresses and unlock wallet.
	log.Printf("%s: Creating wallet addresses...", a)
	for i := range a.ownedAddresses {
		fmt.Printf("\r%d/%d", i+1, len(a.ownedAddresses))
		addr, err := a.client.GetNewAddress()
		if err != nil {
			log.Printf("%s: Cannot create address #%d", a, i+1)
			com.errChan <- struct{}{}
			return err
		}
		a.ownedAddresses[i] = addr
	}
	fmt.Printf("\n")

	if err := a.client.WalletPassphrase(a.walletPassphrase, timeoutSecs); err != nil {
		log.Printf("%s: Cannot unlock wallet: %v", a, err)
		com.errChan <- struct{}{}
		return err
	}

	// Send a random address that will be used by the cpu miner.
	a.miningAddr <- a.ownedAddresses[rand.Int()%len(a.ownedAddresses)]

	// Start a goroutine that queues up a set of utxos belonging to this
	// actor. The utxos are sent from com.poolUtxos which in turn receives
	// block notifications from sim.go
	a.wg.Add(1)
	go a.queueUtxos()

	// Start a goroutine to simulate transactions.
	a.wg.Add(1)
	go a.simulateTx(com.downstream, com.txpool)

	// Start a goroutine to split utxos
	a.wg.Add(1)
	go a.splitUtxos(com.split, com.txpool)

	return nil
}

// simulateTx runs as a goroutine and simulates transactions between actors
//
// It receives a random address downstream, dequeues a utxo, sends a raw
// transaction to the address using the utxo as input
func (a *Actor) simulateTx(downstream <-chan btcutil.Address, txpool chan<- struct{}) {
	defer a.wg.Done()

	for {
		select {
		case utxo := <-a.utxoQueue.dequeue:
			select {
			case addr := <-downstream:
				// Create a raw transaction
				inputs := []btcjson.TransactionInput{{
					Txid: utxo.OutPoint.Hash.String(),
					Vout: utxo.OutPoint.Index,
				}}

				// Provide a fees of minFee to ensure the tx gets mined
				// the utxo amount is guaranteed to be > maxSplit*minFee
				amt := utxo.Amount - minFee
				amounts := map[btcutil.Address]btcutil.Amount{
					addr: amt,
				}

				err := a.sendRawTransaction(inputs, amounts)
				if err != nil {
					log.Printf("%s: Error sending raw transaction: %v", a, err)
					select {
					case txpool <- struct{}{}:
					case <-a.quit:
						return
					}
					continue
				}

			case <-a.quit:
				return
			}
		case <-a.quit:
			return
		}
	}
}

// splitUtxos runs as a goroutine and builds up a large set of utxos that
// can be used to simulate large tx/block ratios
//
// It receives a 'split' which is int that indicates the number of resultant utxos
// the tx is sent to addresses from the same actor since we're only interested in
// building up the utxo set
func (a *Actor) splitUtxos(split <-chan int, txpool chan<- struct{}) {
	defer a.wg.Done()

	for {
		select {
		case utxo := <-a.utxoQueue.dequeue:
			select {
			case split := <-split:
				// Create a raw transaction
				inputs := []btcjson.TransactionInput{{
					Txid: utxo.OutPoint.Hash.String(),
					Vout: utxo.OutPoint.Index,
				}}

				// Provide a fees of minFee to ensure the tx gets mined
				// the utxo amount is guaranteed to be > maxSplit*minFee
				amt := utxo.Amount - minFee
				amounts := map[btcutil.Address]btcutil.Amount{}

				// Create a output of random amount and sent it
				// to a random address from the address space
				// total number of outputs is split+1, taking into
				// account this utxo which is consumed in the process

				// set a rand start index for getting different random addrs
				randomIndex := rand.Int() % len(a.ownedAddresses)
				for i := 0; i <= split; i++ {
					var to btcutil.Address
					var change btcutil.Amount
					// pick a random address
					if randomIndex+i < len(a.ownedAddresses) {
						to = a.ownedAddresses[randomIndex+i]
					} else {
						// wrap around incase of an overflow
						to = a.ownedAddresses[randomIndex+i-len(a.ownedAddresses)]
					}
					if i == split {
						// last split, so just set the change
						change = amt
					} else {
						// pick a random change amount which is less than amt
						// but have a lower bound at minFee
						change = btcutil.Amount(rand.Int63n(int64(amt) / 2))
						if change < minFee {
							change = minFee
						}
						amt -= change
					}
					amounts[to] = change
				}

				err := a.sendRawTransaction(inputs, amounts)
				if err != nil {
					log.Printf("%s: Error sending raw transaction: %v", a, err)
					select {
					case txpool <- struct{}{}:
					case <-a.quit:
						return
					}
					continue
				}

			case <-a.quit:
				return
			}
		case <-a.quit:
			return
		}
	}
}

// sendRawTransaction creates a raw transaction, signs it and sends it
func (a *Actor) sendRawTransaction(inputs []btcjson.TransactionInput, amounts map[btcutil.Address]btcutil.Amount) error {
	msgTx, err := a.client.CreateRawTransaction(inputs, amounts)
	if err != nil {
		return err
	}
	// sign it
	msgTx, ok, err := a.client.SignRawTransaction(msgTx)
	if err != nil {
		return err
	}
	if !ok {
		return err
	}
	// and finally send it.
	if _, err := a.client.SendRawTransaction(msgTx, false); err != nil {
		return err
	}
	return nil
}

// queueUtxos receives utxos belonging to this actor and queues them up
func (a *Actor) queueUtxos() {
	defer a.wg.Done()

	enqueue := a.utxoQueue.enqueue
	var dequeue chan *TxOut
	var next *TxOut
out:
	for {
		select {
		case n, ok := <-enqueue:
			if !ok {
				// If no utxos are queued for handling,
				// the queue is finished.
				if len(a.utxoQueue.utxos) == 0 {
					break out
				}
				// nil channel so no more reads can occur.
				enqueue = nil
				continue
			}
			if len(a.utxoQueue.utxos) == 0 {
				next = n
				dequeue = a.utxoQueue.dequeue
			}
			a.utxoQueue.utxos = append(a.utxoQueue.utxos, n)
		case dequeue <- next:
			a.utxoQueue.utxos[0] = nil
			a.utxoQueue.utxos = a.utxoQueue.utxos[1:]
			if len(a.utxoQueue.utxos) != 0 {
				next = a.utxoQueue.utxos[0]
			} else {
				// If no more utxos can be enqueued, the
				// queue is finished.
				if enqueue == nil {
					break out
				}
				dequeue = nil
			}
		case <-a.quit:
			break out
		}
	}
	close(a.utxoQueue.dequeue)
}

// Shutdown performs a shutdown down the actor by first signalling
// all goroutines to stop, waiting for them to stop and them cleaning up
func (a *Actor) Shutdown() {
	select {
	case <-a.quit:
	default:
		close(a.quit)
		a.WaitForShutdown()
		a.Node.Shutdown()
	}
}

// WaitForShutdown waits until every actor goroutine has returned
func (a *Actor) WaitForShutdown() {
	a.wg.Wait()
}
<commit_msg>Update GetNewAddress call to include default acct.<commit_after>/*
 * Copyright (c) 2014-2015 Conformal Systems LLC <info@conformal.com>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

package main

import (
	"errors"
	"fmt"
	"io"
	"log"
	"math/rand"
	"sync"
	"time"

	"github.com/btcsuite/btcd/btcjson"
	"github.com/btcsuite/btcd/wire"
	rpc "github.com/btcsuite/btcrpcclient"
	"github.com/btcsuite/btcutil"
)

// minFee is the minimum tx fee that can be paid
const minFee btcutil.Amount = 1e4 // 0.0001 BTC

// utxoQueue is the queue of utxos belonging to a actor
// utxos are queued after a block is received and are dispatched
// to their respective owner from com.poolUtxos
// they are dequeued from simulateTx and splitUtxos
type utxoQueue struct {
	utxos   []*TxOut
	enqueue chan *TxOut
	dequeue chan *TxOut
}

// Actor describes an actor on the simulation network.  Each actor runs
// independantly without external input to decide it's behavior.
type Actor struct {
	*Node
	quit             chan struct{}
	wg               sync.WaitGroup
	ownedAddresses   []btcutil.Address
	utxoQueue        *utxoQueue
	miningAddr       chan btcutil.Address
	walletPassphrase string
}

// TxOut is a valid tx output that can be used to generate transactions
type TxOut struct {
	OutPoint *wire.OutPoint
	Amount   btcutil.Amount
}

// NewActor creates a new actor which runs its own wallet process connecting
// to the btcd node server specified by node, and listening for simulator
// websocket connections on the specified port.
func NewActor(node *Node, port uint16) (*Actor, error) {
	// Please don't run this as root.
	if port < 1024 {
		return nil, errors.New("invalid actor port")
	}

	// Set btcwallet node args
	args, err := newBtcwalletArgs(port, node.Args.(*btcdArgs))
	if err != nil {
		return nil, err
	}

	logFile, err := getLogFile(args.prefix)
	if err != nil {
		log.Printf("Cannot get log file, logging disabled: %v", err)
	}
	btcwallet, err := NewNodeFromArgs(args, nil, logFile)
	if err != nil {
		return nil, err
	}

	a := Actor{
		Node:             btcwallet,
		quit:             make(chan struct{}),
		ownedAddresses:   make([]btcutil.Address, *maxAddresses),
		miningAddr:       make(chan btcutil.Address),
		walletPassphrase: "password",
		utxoQueue: &utxoQueue{
			enqueue: make(chan *TxOut),
			dequeue: make(chan *TxOut),
		},
	}
	return &a, nil
}

// Start creates the command to execute a wallet process and starts the
// command in the background, attaching the command's stderr and stdout
// to the passed writers. Nil writers may be used to discard output.
//
// In addition to starting the wallet process, this runs goroutines to
// handle wallet notifications and requests the wallet process to create
// an intial encrypted wallet, so that it can actually send and receive BTC.
//
// If the RPC client connection cannot be established or wallet cannot
// be created, the wallet process is killed and the actor directory
// removed.
func (a *Actor) Start(stderr, stdout io.Writer, com *Communication) error {
	connected := make(chan struct{})
	const timeoutSecs int64 = 3600 * 24

	if err := a.Node.Start(); err != nil {
		a.Shutdown()
		com.errChan <- struct{}{}
		return err
	}

	ntfnHandlers := &rpc.NotificationHandlers{
		OnClientConnected: func() {
			connected <- struct{}{}
		},
	}
	a.handlers = ntfnHandlers

	if err := a.Connect(); err != nil {
		a.Shutdown()
		com.errChan <- struct{}{}
		return err
	}

	// Wait for btcd to connect
	<-connected

	// Wait for wallet sync
	for i := 0; i < *maxConnRetries; i++ {
		if _, err := a.client.GetBalance(""); err != nil {
			time.Sleep(time.Duration(i) * 50 * time.Millisecond)
			continue
		}
		break
	}

	// Create wallet addresses and unlock wallet.
	log.Printf("%s: Creating wallet addresses...", a)
	for i := range a.ownedAddresses {
		fmt.Printf("\r%d/%d", i+1, len(a.ownedAddresses))
		addr, err := a.client.GetNewAddress("")
		if err != nil {
			log.Printf("%s: Cannot create address #%d", a, i+1)
			com.errChan <- struct{}{}
			return err
		}
		a.ownedAddresses[i] = addr
	}
	fmt.Printf("\n")

	if err := a.client.WalletPassphrase(a.walletPassphrase, timeoutSecs); err != nil {
		log.Printf("%s: Cannot unlock wallet: %v", a, err)
		com.errChan <- struct{}{}
		return err
	}

	// Send a random address that will be used by the cpu miner.
	a.miningAddr <- a.ownedAddresses[rand.Int()%len(a.ownedAddresses)]

	// Start a goroutine that queues up a set of utxos belonging to this
	// actor. The utxos are sent from com.poolUtxos which in turn receives
	// block notifications from sim.go
	a.wg.Add(1)
	go a.queueUtxos()

	// Start a goroutine to simulate transactions.
	a.wg.Add(1)
	go a.simulateTx(com.downstream, com.txpool)

	// Start a goroutine to split utxos
	a.wg.Add(1)
	go a.splitUtxos(com.split, com.txpool)

	return nil
}

// simulateTx runs as a goroutine and simulates transactions between actors
//
// It receives a random address downstream, dequeues a utxo, sends a raw
// transaction to the address using the utxo as input
func (a *Actor) simulateTx(downstream <-chan btcutil.Address, txpool chan<- struct{}) {
	defer a.wg.Done()

	for {
		select {
		case utxo := <-a.utxoQueue.dequeue:
			select {
			case addr := <-downstream:
				// Create a raw transaction
				inputs := []btcjson.TransactionInput{{
					Txid: utxo.OutPoint.Hash.String(),
					Vout: utxo.OutPoint.Index,
				}}

				// Provide a fees of minFee to ensure the tx gets mined
				// the utxo amount is guaranteed to be > maxSplit*minFee
				amt := utxo.Amount - minFee
				amounts := map[btcutil.Address]btcutil.Amount{
					addr: amt,
				}

				err := a.sendRawTransaction(inputs, amounts)
				if err != nil {
					log.Printf("%s: Error sending raw transaction: %v", a, err)
					select {
					case txpool <- struct{}{}:
					case <-a.quit:
						return
					}
					continue
				}

			case <-a.quit:
				return
			}
		case <-a.quit:
			return
		}
	}
}

// splitUtxos runs as a goroutine and builds up a large set of utxos that
// can be used to simulate large tx/block ratios
//
// It receives a 'split' which is int that indicates the number of resultant utxos
// the tx is sent to addresses from the same actor since we're only interested in
// building up the utxo set
func (a *Actor) splitUtxos(split <-chan int, txpool chan<- struct{}) {
	defer a.wg.Done()

	for {
		select {
		case utxo := <-a.utxoQueue.dequeue:
			select {
			case split := <-split:
				// Create a raw transaction
				inputs := []btcjson.TransactionInput{{
					Txid: utxo.OutPoint.Hash.String(),
					Vout: utxo.OutPoint.Index,
				}}

				// Provide a fees of minFee to ensure the tx gets mined
				// the utxo amount is guaranteed to be > maxSplit*minFee
				amt := utxo.Amount - minFee
				amounts := map[btcutil.Address]btcutil.Amount{}

				// Create a output of random amount and sent it
				// to a random address from the address space
				// total number of outputs is split+1, taking into
				// account this utxo which is consumed in the process

				// set a rand start index for getting different random addrs
				randomIndex := rand.Int() % len(a.ownedAddresses)
				for i := 0; i <= split; i++ {
					var to btcutil.Address
					var change btcutil.Amount
					// pick a random address
					if randomIndex+i < len(a.ownedAddresses) {
						to = a.ownedAddresses[randomIndex+i]
					} else {
						// wrap around incase of an overflow
						to = a.ownedAddresses[randomIndex+i-len(a.ownedAddresses)]
					}
					if i == split {
						// last split, so just set the change
						change = amt
					} else {
						// pick a random change amount which is less than amt
						// but have a lower bound at minFee
						change = btcutil.Amount(rand.Int63n(int64(amt) / 2))
						if change < minFee {
							change = minFee
						}
						amt -= change
					}
					amounts[to] = change
				}

				err := a.sendRawTransaction(inputs, amounts)
				if err != nil {
					log.Printf("%s: Error sending raw transaction: %v", a, err)
					select {
					case txpool <- struct{}{}:
					case <-a.quit:
						return
					}
					continue
				}

			case <-a.quit:
				return
			}
		case <-a.quit:
			return
		}
	}
}

// sendRawTransaction creates a raw transaction, signs it and sends it
func (a *Actor) sendRawTransaction(inputs []btcjson.TransactionInput, amounts map[btcutil.Address]btcutil.Amount) error {
	msgTx, err := a.client.CreateRawTransaction(inputs, amounts)
	if err != nil {
		return err
	}
	// sign it
	msgTx, ok, err := a.client.SignRawTransaction(msgTx)
	if err != nil {
		return err
	}
	if !ok {
		return err
	}
	// and finally send it.
	if _, err := a.client.SendRawTransaction(msgTx, false); err != nil {
		return err
	}
	return nil
}

// queueUtxos receives utxos belonging to this actor and queues them up
func (a *Actor) queueUtxos() {
	defer a.wg.Done()

	enqueue := a.utxoQueue.enqueue
	var dequeue chan *TxOut
	var next *TxOut
out:
	for {
		select {
		case n, ok := <-enqueue:
			if !ok {
				// If no utxos are queued for handling,
				// the queue is finished.
				if len(a.utxoQueue.utxos) == 0 {
					break out
				}
				// nil channel so no more reads can occur.
				enqueue = nil
				continue
			}
			if len(a.utxoQueue.utxos) == 0 {
				next = n
				dequeue = a.utxoQueue.dequeue
			}
			a.utxoQueue.utxos = append(a.utxoQueue.utxos, n)
		case dequeue <- next:
			a.utxoQueue.utxos[0] = nil
			a.utxoQueue.utxos = a.utxoQueue.utxos[1:]
			if len(a.utxoQueue.utxos) != 0 {
				next = a.utxoQueue.utxos[0]
			} else {
				// If no more utxos can be enqueued, the
				// queue is finished.
				if enqueue == nil {
					break out
				}
				dequeue = nil
			}
		case <-a.quit:
			break out
		}
	}
	close(a.utxoQueue.dequeue)
}

// Shutdown performs a shutdown down the actor by first signalling
// all goroutines to stop, waiting for them to stop and them cleaning up
func (a *Actor) Shutdown() {
	select {
	case <-a.quit:
	default:
		close(a.quit)
		a.WaitForShutdown()
		a.Node.Shutdown()
	}
}

// WaitForShutdown waits until every actor goroutine has returned
func (a *Actor) WaitForShutdown() {
	a.wg.Wait()
}
<|endoftext|>


<commit_before><commit_msg>Add a minion that checks tomcat configs<commit_after><|endoftext|>


<commit_before>package ov

import (
	"encoding/json"
	"fmt"

	"github.com/HewlettPackard/oneview-golang/rest"
	"github.com/HewlettPackard/oneview-golang/utils"
	"github.com/docker/machine/libmachine/log"
)

type ipv4Range struct {
	AllocatedFragmentUri    utils.Nstring          `json:"allocatedFragmentUri,omitempty"`
	AllocatedIdCount        int                    `json:"allocatedIdCount,omitempty"`
	AllocatorUri            utils.Nstring          `json:"allocatorUri,omitempty"`
	AssociatedResources     *associatedResources   `json:"associatedResources,omitempty"`
	Category                string                 `json:"category,omitempty"`
	CollectorUri            utils.Nstring          `json:"collectorUri"`
	Created                 string                 `json:"created,omitempty"`
	DefaultRange            bool                   `json:"defaultRange"`
	ETAG                    string                 `json:"eTag,omitempty"`
	Modified                string                 `json:"modified,omitempty"`
	Enabled                 bool                   `json:" enabled,omitempty"`
	Name                    string                 `json:"name,omitempty"`
	EndAddress              utils.Nstring          `json:"endAddress,omitempty"`
	FreeFragmentUri         utils.Nstring          `json:"freeFragmentUri,omitempty"`
	URI                     utils.Nstring          `json:"uri,omitempty"`
	Prefix                  utils.Nstring          `json:"prefix,omitempty"`
	RangeCategory           utils.Nstring          `json:"rangeCategory,omitempty"`
	ReservedIdCount         int                    `json:"reservedIdCount,omitempty"`
	StartAddress            utils.Nstring          `json:"startAddress,omitempty"`
	StartStopFragments      *startStopFragments    `json:"startStopFragments,omitempty"`
	SubnetUri                utils.Nstring         `json:"subnetUri,omitempty"`
	TotalCount               int                   `json:"totalCount,omitempty"`
	Type                     string                `json:"type,omitempty"`
}

type associatedResources struct {
	AssociationType            string           `json:"associationType,omitempty"`
	ResourceCategory           string           `json:"resourceCategory,omitempty"`
	ResourceName               string           `json:"resourceName,omitempty"`
	ResourceUri                utils.Nstring    `json:"resourceUri,omitempty"`
}

type startStopFragments struct {
	EndAddress              utils.Nstring       `json:"endAddress,omitempty"`
	StartAddress            utils.Nstring       `json:"startAddress,omitempty"`
	FragmentType            string              `json:"fragmentType,omitempty"`
}

type fragmentsList struct {
	Category    string        `json:"category,omitempty"`
	Count       int           `json:"count,omitempty"`       // "count": 1,
	ETAG        string        `json:"eTag,omitempty"`
	Created     string        `json:"created,omitempty"`
	Modified    string        `json:"modified,omitempty"`
	Total       string        `json:"total,omitempty"`
	Start       int           `json:"start,omitempty"`       // "start": 0,
	PrevPageURI utils.Nstring `json:"prevPageUri,omitempty"` // "prevPageUri": null,
	NextPageURI utils.Nstring `json:"nextPageUri,omitempty"` // "nextPageUri": null,
	URI         utils.Nstring `json:"uri,omitempty"`         // "uri": "/rest/server-profiles?filter=connectionTemplateUri%20matches%7769cae0-b680-435b-9b87-9b864c81657fsort=name:asc"
	Members     []ipv4Range   `json:"members,omitempty"`     // "members":[]
}

type updateAllocatorList struct {
	Count       int              `json:"count,omitempty"`       // "count": 1,
	ETAG        string           `json:"eTag,omitempty"`
	Valid       bool             `json:"valid,omitempty"`
	IdList      []utils.Nstring  `json:"idList,omitempty"`
}

type updateCollectorList struct {
	ETAG        string           `json:"eTag,omitempty"`
	IdList      []utils.Nstring  `json:"idList,omitempty"`
}

func (c *OVClient) GetIPv4RangebyId(id string) (ipv4Range, error) {
	var (
		uri        = "/rest/id-pools/ipv4/ranges/schema"
		ipv4Ranges ipv4Range
	)

	// refresh login
	c.RefreshLogin()
	c.SetAuthHeaderOptions(c.GetAuthHeaderMap())

	data, err := c.RestAPICall(rest.GET, uri, nil)
	if err != nil {
		return ipv4Ranges, err
	}

	log.Debugf("GetIpv4Ranges %s", data)
	if err := json.Unmarshal(data, &ipv4Ranges); err != nil {
		return ipv4Ranges, err
	}
	return ipv4Ranges, nil
}

func (c *OVClient) GetAllocatedFragments(filter string, sort string, start string, count string, id string) (fragmentsList, error) {
	var (
		uri        = "/rest/id-pools/ipv4/ranges/" + id + "/allocated-fragments"
		q          = make(map[string]interface{})
		allocatedFragments fragmentsList
	)

	if len(filter) > 0 {
		q["filter"] = filter
	}

	if sort != "" {
		q["sort"] = sort
	}

	if start != "" {
		q["start"] = start
	}

	if count != "" {
		q["count"] = count
	}

	// refresh login
	c.RefreshLogin()
	c.SetAuthHeaderOptions(c.GetAuthHeaderMap())
	// Setup query
	if len(q) > 0 {
		c.SetQueryString(q)
	}
	data, err := c.RestAPICall(rest.GET, uri, nil)
	if err != nil {
		return allocatedFragments, err
	}

	log.Debugf("GetallocatedFragments %s", data)
	if err := json.Unmarshal(data, &allocatedFragments); err != nil {
		return allocatedFragments, err
	}
	return allocatedFragments, nil
}

func (c *OVClient) GetFreeFragments(filter string, sort string, start string, count string, id string) (fragmentsList, error) {
	var (
		uri        = "/rest/id-pools/ipv4/ranges/" + id + "/free-fragments"
		q          = make(map[string]interface{})
		freeFragments fragmentsList
	)

	if len(filter) > 0 {
		q["filter"] = filter
	}

	if sort != "" {
		q["sort"] = sort
	}

	if start != "" {
		q["start"] = start
	}

	if count != "" {
		q["count"] = count
	}

	// refresh login
	c.RefreshLogin()
	c.SetAuthHeaderOptions(c.GetAuthHeaderMap())
	// Setup query
	if len(q) > 0 {
		c.SetQueryString(q)
	}
	data, err := c.RestAPICall(rest.GET, uri, nil)
	if err != nil {
		return freeFragments, err
	}

	log.Debugf("GetfreeFragments %s", data)
	if err := json.Unmarshal(data, &freeFragments); err != nil {
		return freeFragments, err
	}
	return freeFragments, nil
}

func (c *OVClient) GetIpV4RangeSchema() (error) {
	var (
		uri        = "/rest/id-pools/ipv4/ranges/schema"
	)

	// refresh login
	c.RefreshLogin()
	c.SetAuthHeaderOptions(c.GetAuthHeaderMap())

	data, err := c.RestAPICall(rest.GET, uri, nil)
	if err != nil {
		t.TaskIsDone = true
		log.Errorf("Error submitting new ipv4Range creation request: %s", err)
		return err
	}

	log.Debugf("Response New ipv4Range %s", data)
	if err := json.Unmarshal(data, &t); err != nil {
		t.TaskIsDone = true
		log.Errorf("Error with task un-marshal: %s", err)
		return err
	}

	err = t.Wait()
	if err != nil {
		return err
	}

	return nil
}

func (c *OVClient) CreateIPv4Range(ipv4 ipv4Range) error {
	log.Infof("Initializing creation of ipv4Range for %s.", ipv4.Name)
	var (
		uri = "/rest/id-pools/ipv4/ranges/"
		t   = (&Task{}).NewProfileTask(c)
	)
	// refresh login
	c.RefreshLogin()
	c.SetAuthHeaderOptions(c.GetAuthHeaderMap())

	t.ResetTask()
	log.Debugf("REST : %s \n %+v\n", uri, ipv4)
	log.Debugf("task -> %+v", t)
	data, err := c.RestAPICall(rest.POST, uri, ipv4)
	if err != nil {
		t.TaskIsDone = true
		log.Errorf("Error submitting new ipv4Range creation request: %s", err)
		return err
	}

	log.Debugf("Response New ipv4Range %s", data)
	if err := json.Unmarshal(data, &t); err != nil {
		t.TaskIsDone = true
		log.Errorf("Error with task un-marshal: %s", err)
		return err
	}

	err = t.Wait()
	if err != nil {
		return err
	}

	return nil
}

func (c *OVClient) DeleteIpv4Range(id string) error {
	var (
		ipv4 ipv4Range
		err   error
		t     *Task
		uri   "/rest/id-pools/ipv4/ranges/"
	)

	ipv4, err = c.GetIPv4RangebyId(id)
	if err != nil {
		return err
	}
	if ipv4.Name != "" {
		t = t.NewProfileTask(c)
		t.ResetTask()
		log.Debugf("REST : %s \n %+v\n", ipv4.URI, ipv4)
		log.Debugf("task -> %+v", t)
		uri = ipv4.URI.String()
		if uri == "" {
			log.Warn("Unable to post delete, no uri found.")
			t.TaskIsDone = true
			return err
		}
		data, err := c.RestAPICall(rest.DELETE, uri, nil)
		if err != nil {
			log.Errorf("Error submitting new fc network request: %s", err)
			t.TaskIsDone = true
			return err
		}

		log.Debugf("Response delete ipv4 Range %s", data)
		if err := json.Unmarshal(data, &t); err != nil {
			t.TaskIsDone = true
			log.Errorf("Error with task un-marshal: %s", err)
			return err
		}
		err = t.Wait()
		if err != nil {
			return err
		}
		return nil
	} else {
		log.Infof("ipv4 Range could not be found to delete, %s, skipping delete ...", name)
	}
	return nil
}

func (c *OVClient) UpdateIpv4Range(ipv4 ipv4Range) error {
	log.Infof("Initializing update of ipv4 Range for %s.", ipv4.Name)
	var (
		uri = "/rest/id-pools/ipv4/ranges/"
		t   *Task
	)
	// refresh login
	c.RefreshLogin()
	c.SetAuthHeaderOptions(c.GetAuthHeaderMap())

	t = t.NewProfileTask(c)
	t.ResetTask()

	log.Debugf("REST : %s \n %+v\n", uri, ipv4)
	log.Debugf("task -> %+v", t)
	data, err := c.RestAPICall(rest.PUT, uri, ipv4)
	if err != nil {
		t.TaskIsDone = true
		log.Errorf("Error submitting update ipv4 Range request: %s", err)
		return err
	}

	log.Debugf("Response update ipv4 Range %s", data)
	if err := json.Unmarshal([]byte(data), &t); err != nil {
		t.TaskIsDone = true
		log.Errorf("Error with task un-marshal: %s", err)
		return err
	}

	return nil
}

func (c *OVClient) UpdateAllocator(id, ipv4[]]) (updateAllocatorList, error) {
	log.Infof("Initializing update of allocator in ipv4Range for %s.", id)
	var (
		uri = "/rest/id-pools/ipv4/ranges/" + id + "/allocator"
		t   *Task
	)
	// refresh login
	c.RefreshLogin()
	c.SetAuthHeaderOptions(c.GetAuthHeaderMap())

	t = t.NewProfileTask(c)
	t.ResetTask()

	log.Debugf("REST : %s \n %+v\n", uri, ipv4)
	log.Debugf("task -> %+v", t)
	data, err := c.RestAPICall(rest.PUT, uri, ipv4)
	if err != nil {
		t.TaskIsDone = true
		log.Errorf("Error submitting update allocator for ipv4 Range request: %s", err)
		return err
	}

	log.Debugf("Response update ipv4 Range %s", data)
	if err := json.Unmarshal([]byte(data), &t); err != nil {
		t.TaskIsDone = true
		log.Errorf("Error with task un-marshal: %s", err)
		return err
	}

	return nil
}

func (c *OVClient) UpdateCollector(id, ipv4[]]) (updateCollectorList, error) {
	log.Infof("Initializing update of collector in ipv4Range for %s.", id)
	var (
		uri = "/rest/id-pools/ipv4/ranges/" + id + "/collector"
		t   *Task
	)
	// refresh login
	c.RefreshLogin()
	c.SetAuthHeaderOptions(c.GetAuthHeaderMap())

	t = t.NewProfileTask(c)
	t.ResetTask()

	log.Debugf("REST : %s \n %+v\n", uri, ipv4)
	log.Debugf("task -> %+v", t)
	data, err := c.RestAPICall(rest.PUT, uri, ipv4)
	if err != nil {
		t.TaskIsDone = true
		log.Errorf("Error submitting update collector for ipv4 Range request: %s", err)
		return err
	}

	log.Debugf("Response update ipv4 Range %s", data)
	if err := json.Unmarshal([]byte(data), &t); err != nil {
		t.TaskIsDone = true
		log.Errorf("Error with task un-marshal: %s", err)
		return err
	}

	return nil
}
<commit_msg>updated library<commit_after>package ov

import (
	"encoding/json"

	"github.com/HewlettPackard/oneview-golang/rest"
	"github.com/HewlettPackard/oneview-golang/utils"
	"github.com/docker/machine/libmachine/log"
)

type ipv4Range struct{
	AllocatedFragmentUri    utils.Nstring          `json:"allocatedFragmentUri,omitempty"`
	AllocatedIdCount        int                    `json:"allocatedIdCount,omitempty"`
	AllocatorUri            utils.Nstring          `json:"allocatorUri,omitempty"`
	AssociatedResources     *associatedResources   `json:"associatedResources,omitempty"`
	Category                string                 `json:"category,omitempty"`
	CollectorUri            utils.Nstring          `json:"collectorUri"`
	Created                 string                 `json:"created,omitempty"`
	DefaultRange            bool                   `json:"defaultRange"`
	ETAG                    string                 `json:"eTag,omitempty"`
	Modified                string                 `json:"modified,omitempty"`
	Enabled                 bool                   `json:" enabled,omitempty"`
	Name                    string                 `json:"name,omitempty"`
	EndAddress              utils.Nstring          `json:"endAddress,omitempty"`
	FreeFragmentUri         utils.Nstring          `json:"freeFragmentUri,omitempty"`
	URI                     utils.Nstring          `json:"uri,omitempty"`
	Prefix                  utils.Nstring          `json:"prefix,omitempty"`
	RangeCategory           utils.Nstring          `json:"rangeCategory,omitempty"`
	ReservedIdCount         int                    `json:"reservedIdCount,omitempty"`
	StartAddress            utils.Nstring          `json:"startAddress,omitempty"`
	StartStopFragments      *startStopFragments    `json:"startStopFragments,omitempty"`
	SubnetUri                utils.Nstring         `json:"subnetUri,omitempty"`
	TotalCount               int                   `json:"totalCount,omitempty"`
	Type                     string                `json:"type,omitempty"`
}

type associatedResources struct {
	AssociationType            string           `json:"associationType,omitempty"`
	ResourceCategory           string           `json:"resourceCategory,omitempty"`
	ResourceName               string           `json:"resourceName,omitempty"`
	ResourceUri                utils.Nstring    `json:"resourceUri,omitempty"`
}

type startStopFragments struct {
	EndAddress              utils.Nstring       `json:"endAddress,omitempty"`
	StartAddress            utils.Nstring       `json:"startAddress,omitempty"`
	FragmentType            string              `json:"fragmentType,omitempty"`
}

type fragmentsList struct {
	Category    string        `json:"category,omitempty"`
	Count       int           `json:"count,omitempty"`       // "count": 1,
	ETAG        string        `json:"eTag,omitempty"`
	Created     string        `json:"created,omitempty"`
	Modified    string        `json:"modified,omitempty"`
	Total       string        `json:"total,omitempty"`
	Start       int           `json:"start,omitempty"`       // "start": 0,
	PrevPageURI utils.Nstring `json:"prevPageUri,omitempty"` // "prevPageUri": null,
	NextPageURI utils.Nstring `json:"nextPageUri,omitempty"` // "nextPageUri": null,
	URI         utils.Nstring `json:"uri,omitempty"`         // "uri": "/rest/server-profiles?filter=connectionTemplateUri%20matches%7769cae0-b680-435b-9b87-9b864c81657fsort=name:asc"
	Members     []ipv4        `json:"members,omitempty"`     // "members":[]
}

type UpdateAllocatorList struct {
	Count       int              `json:"count,omitempty"`       // "count": 1,
	ETAG        string           `json:"eTag,omitempty"`
	Valid       bool             `json:"valid,omitempty"`
	IdList      []utils.Nstring  `json:"idList,omitempty"`
}

type UpdateCollectorList struct {
	ETAG        string           `json:"eTag,omitempty"`
	IdList      []utils.Nstring  `json:"idList,omitempty"`
}

func (c *OVClient) GetIPv4RangebyId(id string) (ipv4Range, error) {
	var (
		uri        = "/rest/id-pools/ipv4/ranges/schema"
		ipv4Ranges ipv4Range
	)

	// refresh login
	c.RefreshLogin()
	c.SetAuthHeaderOptions(c.GetAuthHeaderMap())

	data, err := c.RestAPICall(rest.GET, uri, nil)
	if err != nil {
		return ipv4Ranges, err
	}

	log.Debugf("GetIpv4Ranges %s", data)
	if err := json.Unmarshal(data, &ipv4Ranges); err != nil {
		return ipv4Ranges, err
	}
	return ipv4Ranges, nil
}

func (c *OVClient) GetAllocatedFragments(filter string, sort string, start string, count string, id string) (fragmentsList, error) {
	var (
		uri        = "/rest/id-pools/ipv4/ranges/" + id + "/allocated-fragments"
		q          = make(map[string]interface{})
		allocatedFragments fragmentsList
	)

	if len(filter) > 0 {
		q["filter"] = filter
	}

	if sort != "" {
		q["sort"] = sort
	}

	if start != "" {
		q["start"] = start
	}

	if count != "" {
		q["count"] = count
	}

	// refresh login
	c.RefreshLogin()
	c.SetAuthHeaderOptions(c.GetAuthHeaderMap())
	// Setup query
	if len(q) > 0 {
		c.SetQueryString(q)
	}
	data, err := c.RestAPICall(rest.GET, uri, nil)
	if err != nil {
		return allocatedFragments, err
	}

	log.Debugf("GetallocatedFragments %s", data)
	if err := json.Unmarshal(data, &allocatedFragments); err != nil {
		return allocatedFragments, err
	}
	return allocatedFragments, nil
}

func (c *OVClient) GetFreeFragments(filter string, sort string, start string, count string, id string) (fragmentsList, error) {
	var (
		uri        = "/rest/id-pools/ipv4/ranges/" + id + "/free-fragments"
		q          = make(map[string]interface{})
		freeFragments fragmentsList
	)

	if len(filter) > 0 {
		q["filter"] = filter
	}

	if sort != "" {
		q["sort"] = sort
	}

	if start != "" {
		q["start"] = start
	}

	if count != "" {
		q["count"] = count
	}

	// refresh login
	c.RefreshLogin()
	c.SetAuthHeaderOptions(c.GetAuthHeaderMap())
	// Setup query
	if len(q) > 0 {
		c.SetQueryString(q)
	}
	data, err := c.RestAPICall(rest.GET, uri, nil)
	if err != nil {
		return freeFragments, err
	}

	log.Debugf("GetfreeFragments %s", data)
	if err := json.Unmarshal(data, &freeFragments); err != nil {
		return freeFragments, err
	}
	return freeFragments, nil
}

func (c *OVClient) GetIpV4RangeSchema() (error) {
	var (
		uri   = "/rest/id-pools/ipv4/ranges/schema"
		t     *Task
	)

	// refresh login
	c.RefreshLogin()
	c.SetAuthHeaderOptions(c.GetAuthHeaderMap())
        t = t.NewProfileTask(c)
	t.ResetTask()

	data, err := c.RestAPICall(rest.GET, uri, nil)
	if err != nil {
		t.TaskIsDone = true
		log.Errorf("Error submitting new ipv4Range creation request: %s", err)
		return err
	}

	log.Debugf("Response New ipv4Range %s", data)
	if err := json.Unmarshal(data, &t); err != nil {
		t.TaskIsDone = true
		log.Errorf("Error with task un-marshal: %s", err)
		return err
	}

	err = t.Wait()
	if err != nil {
		return err
	}

	return nil
}

func (c *OVClient) CreateIPv4Range(ipv4 ipv4Range) error {
	log.Infof("Initializing creation of ipv4Range for %s.", ipv4.Name)
	var (
		uri = "/rest/id-pools/ipv4/ranges/"
		t   = (&Task{}).NewProfileTask(c)
	)
	// refresh login
	c.RefreshLogin()
	c.SetAuthHeaderOptions(c.GetAuthHeaderMap())

	t.ResetTask()
	log.Debugf("REST : %s \n %+v\n", uri, ipv4)
	log.Debugf("task -> %+v", t)
	data, err := c.RestAPICall(rest.POST, uri, ipv4)
	if err != nil {
		t.TaskIsDone = true
		log.Errorf("Error submitting new ipv4Range creation request: %s", err)
		return err
	}

	log.Debugf("Response New ipv4Range %s", data)
	if err := json.Unmarshal(data, &t); err != nil {
		t.TaskIsDone = true
		log.Errorf("Error with task un-marshal: %s", err)
		return err
	}

	err = t.Wait()
	if err != nil {
		return err
	}

	return nil
}

func (c *OVClient) DeleteIpv4Range(id string) error {
	var (
		ipv4 ipv4Range
		err   error
		t     *Task
		uri   string
	)

	ipv4, err = c.GetIPv4RangebyId(id)
	if err != nil {
		return err
	}
	if ipv4.Name != "" {
		t = t.NewProfileTask(c)
		t.ResetTask()
		log.Debugf("REST : %s \n %+v\n", ipv4.URI, ipv4)
		log.Debugf("task -> %+v", t)
		uri = ipv4.URI.String()
		if uri == "" {
			log.Warn("Unable to post delete, no uri found.")
			t.TaskIsDone = true
			return err
		}
		data, err := c.RestAPICall(rest.DELETE, uri, nil)
		if err != nil {
			log.Errorf("Error submitting new fc network request: %s", err)
			t.TaskIsDone = true
			return err
		}

		log.Debugf("Response delete ipv4 Range %s", data)
		if err := json.Unmarshal(data, &t); err != nil {
			t.TaskIsDone = true
			log.Errorf("Error with task un-marshal: %s", err)
			return err
		}
		err = t.Wait()
		if err != nil {
			return err
		}
		return nil
	} else {
		log.Infof("ipv4 Range could not be found to delete, %s, skipping delete ...", ipv4.Name)
	}
	return nil
}

func (c *OVClient) UpdateIpv4Range(ipv4 ipv4Range) error {
	log.Infof("Initializing update of ipv4 Range for %s.", ipv4.Name)
	var (
		uri = "/rest/id-pools/ipv4/ranges/"
		t   *Task
	)
	// refresh login
	c.RefreshLogin()
	c.SetAuthHeaderOptions(c.GetAuthHeaderMap())

	t = t.NewProfileTask(c)
	t.ResetTask()

	log.Debugf("REST : %s \n %+v\n", uri, ipv4)
	log.Debugf("task -> %+v", t)
	data, err := c.RestAPICall(rest.PUT, uri, ipv4)
	if err != nil {
		t.TaskIsDone = true
		log.Errorf("Error submitting update ipv4 Range request: %s", err)
		return err
	}

	log.Debugf("Response update ipv4 Range %s", data)
	if err := json.Unmarshal([]byte(data), &t); err != nil {
		t.TaskIsDone = true
		log.Errorf("Error with task un-marshal: %s", err)
		return err
	}

	return nil
}

//func (c *OVClient) UpdateAllocator(id int, []ipv4) (UpdateAllocatorList, error) {
//	log.Infof("Initializing update of allocator in ipv4Range for %s.", id)
//	var (
//		uri = "/rest/id-pools/ipv4/ranges/" + id + "/allocator"
//		t   *Task
//		updateAllocatorList UpdateAllocatorList
//	)
	// refresh login
//	c.RefreshLogin()
//	c.SetAuthHeaderOptions(c.GetAuthHeaderMap())
//
//	t = t.NewProfileTask(c)
//	t.ResetTask()
//
//	log.Debugf("REST : %s \n %+v\n", uri, ipv4)
//	log.Debugf("task -> %+v", t)
//	data, err := c.RestAPICall(rest.PUT, uri, ipv4)
//	if err != nil {
//		t.TaskIsDone = true
//		log.Errorf("Error submitting update allocator for ipv4 Range request: %s", err)
//		return updateAllocatorList, err
//	}

//	log.Debugf("Response update ipv4 Range %s", data)
//	if err := json.Unmarshal([]byte(data), &t); err != nil {
//		t.TaskIsDone = true
//		log.Errorf("Error with task un-marshal: %s", err)
//		return err
//	}

//	return updateAllocatorList
//}

//func (c *OVClient) UpdateCollector(id, []ipv4) (UpdateCollectorList, error) {
//	log.Infof("Initializing update of collector in ipv4Range for %s.", id)
//	var (
//		uri = "/rest/id-pools/ipv4/ranges/" + id + "/collector"
//		t   *Task
//		updatecollectorList UpdateCollectorList
//	)
//	// refresh login
//	c.RefreshLogin()
//	c.SetAuthHeaderOptions(c.GetAuthHeaderMap())

//	t = t.NewProfileTask(c)
//	t.ResetTask()
//
//	log.Debugf("REST : %s \n %+v\n", uri, ipv4)
//	log.Debugf("task -> %+v", t)
//	data, err := c.RestAPICall(rest.PUT, uri, ipv4)
//	if err != nil {
//		t.TaskIsDone = true
//		log.Errorf("Error submitting update collector for ipv4 Range request: %s", err)
//		return updatecollectorList, err
//	}
//
//	log.Debugf("Response update ipv4 Range %s", data)
//	if err := json.Unmarshal([]byte(data), &t); err != nil {
//		t.TaskIsDone = true
//		log.Errorf("Error with task un-marshal: %s", err)
//		return err
//	}

//	return updatecollectorList
//}
<|endoftext|>


<commit_before>package main

import (
	"io/ioutil"
	"os/exec"
	"testing"

	. "gopkg.in/bluesuncorp/assert.v1"
)

// NOTES:
// - Run "go test" to run tests
// - Run "gocov test | gocov report" to report on test converage by file
// - Run "gocov test | gocov annotate -" to report on all code and functions, those ,marked with "MISS" were never called
//
// or
//
// -- may be a good idea to change to output path to somewherelike /tmp
// go test -coverprofile cover.out && go tool cover -html=cover.out -o cover.html
//

func TestOveralls(t *testing.T) {

	args := []string{"-project=github.com/bluesuncorp/overalls/test-files", "-covermode=count", "-debug"}

	cmd := exec.Command("overalls", args...)
	err := cmd.Run()
	Equal(t, err, nil)

	fileBytes, err := ioutil.ReadFile(srcPath + "github.com/bluesuncorp/overalls/test-files/overalls.coverprofile")
	Equal(t, err, nil)
	Equal(t, len(fileBytes), 133)
}
<commit_msg>Update Unit Tests<commit_after>package main

import (
	"io/ioutil"
	"os/exec"
	"strings"
	"testing"

	. "gopkg.in/bluesuncorp/assert.v1"
)

// NOTES:
// - Run "go test" to run tests
// - Run "gocov test | gocov report" to report on test converage by file
// - Run "gocov test | gocov annotate -" to report on all code and functions, those ,marked with "MISS" were never called
//
// or
//
// -- may be a good idea to change to output path to somewherelike /tmp
// go test -coverprofile cover.out && go tool cover -html=cover.out -o cover.html
//

func TestOveralls(t *testing.T) {

	args := []string{"-project=github.com/bluesuncorp/overalls/test-files", "-covermode=count", "-debug"}

	cmd := exec.Command("overalls", args...)
	err := cmd.Run()
	Equal(t, err, nil)

	fileBytes, err := ioutil.ReadFile(srcPath + "github.com/bluesuncorp/overalls/test-files/overalls.coverprofile")
	Equal(t, err, nil)

	final := string(fileBytes)
	NotEqual(t, strings.Index(final, "main.go"), -1)
	NotEqual(t, strings.Index(final, "test-files/good/main.go"), -1)
	NotEqual(t, strings.Index(final, "test-files/good2/main.go"), -1)
}
<|endoftext|>


<commit_before>package main_test

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"time"

	"github.com/concourse/semver-resource/models"
	"github.com/mitchellh/goamz/aws"
	"github.com/mitchellh/goamz/s3"
	"github.com/nu7hatch/gouuid"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/gexec"
)

var _ = Describe("Out", func() {
	var key string

	var source string

	var outCmd *exec.Cmd

	BeforeEach(func() {
		var err error

		source, err = ioutil.TempDir("", "out-source")
		Ω(err).ShouldNot(HaveOccurred())

		outCmd = exec.Command(outPath, source)
	})

	AfterEach(func() {
		os.RemoveAll(source)
	})

	Context("when executed", func() {
		var request models.OutRequest
		var response models.OutResponse

		var bucket *s3.Bucket

		BeforeEach(func() {
			guid, err := uuid.NewV4()
			Ω(err).ShouldNot(HaveOccurred())

			key = guid.String()

			auth := aws.Auth{
				AccessKey: accessKeyID,
				SecretKey: secretAccessKey,
			}

			region, ok := aws.Regions[regionName]
			Ω(ok).Should(BeTrue())

			client := s3.New(auth, region)

			bucket = client.Bucket(bucketName)

			request = models.OutRequest{
				Version: models.Version{},
				Source: models.Source{
					Bucket:          bucketName,
					Key:             key,
					AccessKeyID:     accessKeyID,
					SecretAccessKey: secretAccessKey,
					RegionName:      regionName,
				},
				Params: models.OutParams{},
			}

			response = models.OutResponse{}
		})

		AfterEach(func() {
			err := bucket.Del(key)
			Ω(err).ShouldNot(HaveOccurred())
		})

		JustBeforeEach(func() {
			stdin, err := outCmd.StdinPipe()
			Ω(err).ShouldNot(HaveOccurred())

			session, err := gexec.Start(outCmd, GinkgoWriter, GinkgoWriter)
			Ω(err).ShouldNot(HaveOccurred())

			err = json.NewEncoder(stdin).Encode(request)
			Ω(err).ShouldNot(HaveOccurred())

			// account for roundtrip to s3
			Eventually(session, 5*time.Second).Should(gexec.Exit(0))

			err = json.Unmarshal(session.Out.Contents(), &response)
			Ω(err).ShouldNot(HaveOccurred())
		})

		Context("when setting the version", func() {
			BeforeEach(func() {
				request.Params.File = "number"
			})

			Context("when a valid version is in the file", func() {
				BeforeEach(func() {
					err := ioutil.WriteFile(filepath.Join(source, "number"), []byte("1.2.3"), 0644)
					Ω(err).ShouldNot(HaveOccurred())
				})

				It("reports the version as the resource's version", func() {
					Ω(response.Version.Number).Should(Equal("1.2.3"))
				})

				It("saves the contents of the file in the configured bucket", func() {
					contents, err := bucket.Get(key)
					Ω(err).ShouldNot(HaveOccurred())

					Ω(string(contents)).Should(Equal("1.2.3"))
				})
			})
		})

		Context("when bumping the version", func() {
			BeforeEach(func() {
				err := bucket.Put(key, []byte("1.2.3"), "text/plain", s3.Private)
				Ω(err).ShouldNot(HaveOccurred())
			})

			for bump, result := range map[string]string{
				"final": "1.2.3",
				"patch": "1.2.4",
				"minor": "1.3.0",
				"major": "2.0.0",
			} {
				bumpLocal := bump
				resultLocal := result

				Context(fmt.Sprintf("when bumping %s", bumpLocal), func() {
					BeforeEach(func() {
						request.Params.Bump = bumpLocal
					})

					It("reports the bumped version as the version", func() {
						Ω(response.Version.Number).Should(Equal(resultLocal))
					})

					It("saves the contents of the file in the configured bucket", func() {
						contents, err := bucket.Get(key)
						Ω(err).ShouldNot(HaveOccurred())

						Ω(string(contents)).Should(Equal(resultLocal))
					})
				})
			}
		})

		Context("when bumping the version to a prerelease", func() {
			BeforeEach(func() {
				request.Params.Pre = "alpha"
			})

			Context("when the version is not a prerelease", func() {
				BeforeEach(func() {
					err := bucket.Put(key, []byte("1.2.3"), "text/plain", s3.Private)
					Ω(err).ShouldNot(HaveOccurred())
				})

				It("reports the bumped version as the version", func() {
					Ω(response.Version.Number).Should(Equal("1.2.3-alpha.1"))
				})

				It("saves the contents of the file in the configured bucket", func() {
					contents, err := bucket.Get(key)
					Ω(err).ShouldNot(HaveOccurred())

					Ω(string(contents)).Should(Equal("1.2.3-alpha.1"))
				})

				Context("when doing a semantic bump at the same time", func() {
					BeforeEach(func() {
						request.Params.Bump = "minor"
					})

					It("reports the bumped version as the version", func() {
						Ω(response.Version.Number).Should(Equal("1.3.0-alpha.1"))
					})

					It("saves the contents of the file in the configured bucket", func() {
						contents, err := bucket.Get(key)
						Ω(err).ShouldNot(HaveOccurred())

						Ω(string(contents)).Should(Equal("1.3.0-alpha.1"))
					})
				})
			})

			Context("when the version is the same prerelease", func() {
				BeforeEach(func() {
					err := bucket.Put(key, []byte("1.2.3-alpha.2"), "text/plain", s3.Private)
					Ω(err).ShouldNot(HaveOccurred())
				})

				It("reports the bumped version as the version", func() {
					Ω(response.Version.Number).Should(Equal("1.2.3-alpha.3"))
				})

				It("saves the contents of the file in the configured bucket", func() {
					contents, err := bucket.Get(key)
					Ω(err).ShouldNot(HaveOccurred())

					Ω(string(contents)).Should(Equal("1.2.3-alpha.3"))
				})

				Context("when doing a semantic bump at the same time", func() {
					BeforeEach(func() {
						request.Params.Bump = "minor"
					})

					It("reports the bumped version as the version", func() {
						Ω(response.Version.Number).Should(Equal("1.3.0-alpha.1"))
					})

					It("saves the contents of the file in the configured bucket", func() {
						contents, err := bucket.Get(key)
						Ω(err).ShouldNot(HaveOccurred())

						Ω(string(contents)).Should(Equal("1.2.3-alpha.3"))
					})
				})
			})

			Context("when the version is a different prerelease", func() {
				BeforeEach(func() {
					err := bucket.Put(key, []byte("1.2.3-beta.2"), "text/plain", s3.Private)
					Ω(err).ShouldNot(HaveOccurred())
				})

				It("reports the bumped version as the version", func() {
					Ω(response.Version.Number).Should(Equal("1.2.3-alpha.1"))
				})

				It("saves the contents of the file in the configured bucket", func() {
					contents, err := bucket.Get(key)
					Ω(err).ShouldNot(HaveOccurred())

					Ω(string(contents)).Should(Equal("1.2.3-alpha.1"))
				})

				Context("when doing a semantic bump at the same time", func() {
					BeforeEach(func() {
						request.Params.Bump = "minor"
					})

					It("reports the bumped version as the version", func() {
						Ω(response.Version.Number).Should(Equal("1.3.0-alpha.1"))
					})

					It("saves the contents of the file in the configured bucket", func() {
						contents, err := bucket.Get(key)
						Ω(err).ShouldNot(HaveOccurred())

						Ω(string(contents)).Should(Equal("1.2.3-alpha.1"))
					})
				})
			})
		})
	})
})
<commit_msg>make it work™<commit_after>package main_test

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"time"

	"github.com/concourse/semver-resource/models"
	"github.com/mitchellh/goamz/aws"
	"github.com/mitchellh/goamz/s3"
	"github.com/nu7hatch/gouuid"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/gexec"
)

var _ = Describe("Out", func() {
	var key string

	var source string

	var outCmd *exec.Cmd

	BeforeEach(func() {
		var err error

		source, err = ioutil.TempDir("", "out-source")
		Ω(err).ShouldNot(HaveOccurred())

		outCmd = exec.Command(outPath, source)
	})

	AfterEach(func() {
		os.RemoveAll(source)
	})

	Context("when executed", func() {
		var request models.OutRequest
		var response models.OutResponse

		var bucket *s3.Bucket

		BeforeEach(func() {
			guid, err := uuid.NewV4()
			Ω(err).ShouldNot(HaveOccurred())

			key = guid.String()

			auth := aws.Auth{
				AccessKey: accessKeyID,
				SecretKey: secretAccessKey,
			}

			region, ok := aws.Regions[regionName]
			Ω(ok).Should(BeTrue())

			client := s3.New(auth, region)

			bucket = client.Bucket(bucketName)

			request = models.OutRequest{
				Version: models.Version{},
				Source: models.Source{
					Bucket:          bucketName,
					Key:             key,
					AccessKeyID:     accessKeyID,
					SecretAccessKey: secretAccessKey,
					RegionName:      regionName,
				},
				Params: models.OutParams{},
			}

			response = models.OutResponse{}
		})

		AfterEach(func() {
			err := bucket.Del(key)
			Ω(err).ShouldNot(HaveOccurred())
		})

		JustBeforeEach(func() {
			stdin, err := outCmd.StdinPipe()
			Ω(err).ShouldNot(HaveOccurred())

			session, err := gexec.Start(outCmd, GinkgoWriter, GinkgoWriter)
			Ω(err).ShouldNot(HaveOccurred())

			err = json.NewEncoder(stdin).Encode(request)
			Ω(err).ShouldNot(HaveOccurred())

			// account for roundtrip to s3
			Eventually(session, 5*time.Second).Should(gexec.Exit(0))

			err = json.Unmarshal(session.Out.Contents(), &response)
			Ω(err).ShouldNot(HaveOccurred())
		})

		Context("when setting the version", func() {
			BeforeEach(func() {
				request.Params.File = "number"
			})

			Context("when a valid version is in the file", func() {
				BeforeEach(func() {
					err := ioutil.WriteFile(filepath.Join(source, "number"), []byte("1.2.3"), 0644)
					Ω(err).ShouldNot(HaveOccurred())
				})

				It("reports the version as the resource's version", func() {
					Ω(response.Version.Number).Should(Equal("1.2.3"))
				})

				It("saves the contents of the file in the configured bucket", func() {
					contents, err := bucket.Get(key)
					Ω(err).ShouldNot(HaveOccurred())

					Ω(string(contents)).Should(Equal("1.2.3"))
				})
			})
		})

		Context("when bumping the version", func() {
			BeforeEach(func() {
				err := bucket.Put(key, []byte("1.2.3"), "text/plain", s3.Private)
				Ω(err).ShouldNot(HaveOccurred())
			})

			for bump, result := range map[string]string{
				"final": "1.2.3",
				"patch": "1.2.4",
				"minor": "1.3.0",
				"major": "2.0.0",
			} {
				bumpLocal := bump
				resultLocal := result

				Context(fmt.Sprintf("when bumping %s", bumpLocal), func() {
					BeforeEach(func() {
						request.Params.Bump = bumpLocal
					})

					It("reports the bumped version as the version", func() {
						Ω(response.Version.Number).Should(Equal(resultLocal))
					})

					It("saves the contents of the file in the configured bucket", func() {
						contents, err := bucket.Get(key)
						Ω(err).ShouldNot(HaveOccurred())

						Ω(string(contents)).Should(Equal(resultLocal))
					})
				})
			}
		})

		Context("when bumping the version to a prerelease", func() {
			BeforeEach(func() {
				request.Params.Pre = "alpha"
			})

			Context("when the version is not a prerelease", func() {
				BeforeEach(func() {
					err := bucket.Put(key, []byte("1.2.3"), "text/plain", s3.Private)
					Ω(err).ShouldNot(HaveOccurred())
				})

				It("reports the bumped version as the version", func() {
					Ω(response.Version.Number).Should(Equal("1.2.3-alpha.1"))
				})

				It("saves the contents of the file in the configured bucket", func() {
					contents, err := bucket.Get(key)
					Ω(err).ShouldNot(HaveOccurred())

					Ω(string(contents)).Should(Equal("1.2.3-alpha.1"))
				})

				Context("when doing a semantic bump at the same time", func() {
					BeforeEach(func() {
						request.Params.Bump = "minor"
					})

					It("reports the bumped version as the version", func() {
						Ω(response.Version.Number).Should(Equal("1.3.0-alpha.1"))
					})

					It("saves the contents of the file in the configured bucket", func() {
						contents, err := bucket.Get(key)
						Ω(err).ShouldNot(HaveOccurred())

						Ω(string(contents)).Should(Equal("1.3.0-alpha.1"))
					})
				})
			})

			Context("when the version is the same prerelease", func() {
				BeforeEach(func() {
					err := bucket.Put(key, []byte("1.2.3-alpha.2"), "text/plain", s3.Private)
					Ω(err).ShouldNot(HaveOccurred())
				})

				It("reports the bumped version as the version", func() {
					Ω(response.Version.Number).Should(Equal("1.2.3-alpha.3"))
				})

				It("saves the contents of the file in the configured bucket", func() {
					contents, err := bucket.Get(key)
					Ω(err).ShouldNot(HaveOccurred())

					Ω(string(contents)).Should(Equal("1.2.3-alpha.3"))
				})

				Context("when doing a semantic bump at the same time", func() {
					BeforeEach(func() {
						request.Params.Bump = "minor"
					})

					It("reports the bumped version as the version", func() {
						Ω(response.Version.Number).Should(Equal("1.3.0-alpha.1"))
					})

					It("saves the contents of the file in the configured bucket", func() {
						contents, err := bucket.Get(key)
						Ω(err).ShouldNot(HaveOccurred())

						Ω(string(contents)).Should(Equal("1.3.0-alpha.1"))
					})
				})
			})

			Context("when the version is a different prerelease", func() {
				BeforeEach(func() {
					err := bucket.Put(key, []byte("1.2.3-beta.2"), "text/plain", s3.Private)
					Ω(err).ShouldNot(HaveOccurred())
				})

				It("reports the bumped version as the version", func() {
					Ω(response.Version.Number).Should(Equal("1.2.3-alpha.1"))
				})

				It("saves the contents of the file in the configured bucket", func() {
					contents, err := bucket.Get(key)
					Ω(err).ShouldNot(HaveOccurred())

					Ω(string(contents)).Should(Equal("1.2.3-alpha.1"))
				})

				Context("when doing a semantic bump at the same time", func() {
					BeforeEach(func() {
						request.Params.Bump = "minor"
					})

					It("reports the bumped version as the version", func() {
						Ω(response.Version.Number).Should(Equal("1.3.0-alpha.1"))
					})

					It("saves the contents of the file in the configured bucket", func() {
						contents, err := bucket.Get(key)
						Ω(err).ShouldNot(HaveOccurred())

						Ω(string(contents)).Should(Equal("1.3.0-alpha.1"))
					})
				})
			})
		})
	})
})
<|endoftext|>


<commit_before>package perfM

type Config struct {
	Frequency  int //set for the sampling frequency
	BufferSize int //set for the global time channel buffer size
	BinsNumber int //set the histogram bins number
}
<commit_msg>add comment<commit_after>package perfM

//Config define the Config about perfM
type Config struct {
	Frequency  int //set for the sampling frequency
	BufferSize int //set for the global time channel buffer size
	BinsNumber int //set the histogram bins number
}
<|endoftext|>


<commit_before>// Copyright 2012, Bryan Matsuo. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

/*  Filename:    config.go
 *  Author:      Bryan Matsuo <bmatsuo@soe.ucsc.edu>
 *  Created:     2012-03-04 19:23:27.544554 -0800 PST
 *  Description:
 */

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"os"
	"strconv"

	"github.com/bmatsuo/gutterd/handler"
	"github.com/bmatsuo/gutterd/watcher"
)

type Config struct {
	Path          string           `json:"-"`             // The path of the config file.
	HTTP          string           `json:"http"`          // HTTP service address.
	Statsd        string           `json:"statsd"`        // address of statsd
	Watch         []watcher.Config `json:"watch"`         // Incoming watch directories.
	PollFrequency int64            `json:"pollFrequency"` // Poll frequency in seconds.
	Handlers      []handler.Config `json:"handlers"`      // Ordered set of handlers.
}

func (config Config) Validate() error {
	if config.Path == "" {
		return errors.New("config: no path")
	}
	for _, watcher := range config.Watch {
		if err := watcher.Validate(); err != nil {
			return fmt.Errorf("config: %v", err)
		}
	}
	if config.PollFrequency <= 0 {
		return fmt.Errorf("config: invalid pollFrequency: %d", config.PollFrequency)
	}
	for _, handler := range config.Handlers {
		if err := handler.Validate(); err != nil {
			return fmt.Errorf("config: %v", err)
		}
	}
	// TODO validate Statsd
	return nil
}

func loadConfigFromBytes(p []byte, path string, defaults *Config) (config *Config, err error) {
	if config = new(Config); defaults != nil { // Tightly coupled events.
		*config = *defaults
	}

	if err = json.Unmarshal(p, config); err != nil {
		return config, fmt.Errorf("json error: %v", err)
	}

	config.Path = path // Overwrite any JSON specified value.

	// Validate handlers.
	for i, handler := range config.Handlers {
		name := handler.Name
		if name == "" {
			name = strconv.FormatInt(int64(i), 10)
		}
		if handler.Watch == "" {
			return config, fmt.Errorf("handler %v: no watch directory", i)
		}
		if stat, err := os.Stat(handler.Watch); err != nil {
			return config, err // The return parameter "err" is shadowed.
		} else if !stat.IsDir() {
			return config, fmt.Errorf("'watch' entry is not a directory: %s", handler.Watch)
		}
	}
	return
}

func LoadConfig(path string, defaults *Config) (*Config, error) {
	if _, err := os.Stat(path); err != nil {
		if os.IsNotExist(err) {
			return config, nil
		}
		return config, err
	}
	p, err := ioutil.ReadFile(path)
	if err != nil {
		return config, fmt.Errorf("read error: %v", err)
	}
	config, err := loadConfigFromBytes(p, path, defaults)
	if err != nil {
		return nil, err
	}
	err = config.Validate()
	return config, err
}

func (c *Config) MakeHandlers() []*handler.Handler {
	handlers := make([]*handler.Handler, len(c.Handlers))
	for i := range c.Handlers {
		handlers[i] = c.Handlers[i].Handler()
	}
	return handlers
}
<commit_msg>LoadConfig bug fix<commit_after>// Copyright 2012, Bryan Matsuo. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

/*  Filename:    config.go
 *  Author:      Bryan Matsuo <bmatsuo@soe.ucsc.edu>
 *  Created:     2012-03-04 19:23:27.544554 -0800 PST
 *  Description:
 */

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"os"
	"strconv"

	"github.com/bmatsuo/gutterd/handler"
	"github.com/bmatsuo/gutterd/watcher"
)

type Config struct {
	Path          string           `json:"-"`             // The path of the config file.
	HTTP          string           `json:"http"`          // HTTP service address.
	Statsd        string           `json:"statsd"`        // address of statsd
	Watch         []watcher.Config `json:"watch"`         // Incoming watch directories.
	PollFrequency int64            `json:"pollFrequency"` // Poll frequency in seconds.
	Handlers      []handler.Config `json:"handlers"`      // Ordered set of handlers.
}

func (config Config) Validate() error {
	if config.Path == "" {
		return errors.New("config: no path")
	}
	for _, watcher := range config.Watch {
		if err := watcher.Validate(); err != nil {
			return fmt.Errorf("config: %v", err)
		}
	}
	if config.PollFrequency <= 0 {
		return fmt.Errorf("config: invalid pollFrequency: %d", config.PollFrequency)
	}
	for _, handler := range config.Handlers {
		if err := handler.Validate(); err != nil {
			return fmt.Errorf("config: %v", err)
		}
	}
	// TODO validate Statsd
	return nil
}

func loadConfigFromBytes(p []byte, path string, defaults *Config) (config *Config, err error) {
	if config = new(Config); defaults != nil { // Tightly coupled events.
		*config = *defaults
	}

	if err = json.Unmarshal(p, config); err != nil {
		return config, fmt.Errorf("json error: %v", err)
	}

	config.Path = path // Overwrite any JSON specified value.

	// Validate handlers.
	for i, handler := range config.Handlers {
		name := handler.Name
		if name == "" {
			name = strconv.FormatInt(int64(i), 10)
		}
		if handler.Watch == "" {
			return config, fmt.Errorf("handler %v: no watch directory", i)
		}
		if stat, err := os.Stat(handler.Watch); err != nil {
			return config, err // The return parameter "err" is shadowed.
		} else if !stat.IsDir() {
			return config, fmt.Errorf("'watch' entry is not a directory: %s", handler.Watch)
		}
	}
	return
}

func LoadConfig(path string, defaults *Config) (*Config, error) {
	if _, err := os.Stat(path); err != nil {
		if os.IsNotExist(err) {
			return defaults, nil
		}
		return nil, err
	}
	p, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, fmt.Errorf("read error: %v", err)
	}
	config, err := loadConfigFromBytes(p, path, defaults)
	if err != nil {
		return nil, err
	}
	err = config.Validate()
	return config, err
}

func (c *Config) MakeHandlers() []*handler.Handler {
	handlers := make([]*handler.Handler, len(c.Handlers))
	for i := range c.Handlers {
		handlers[i] = c.Handlers[i].Handler()
	}
	return handlers
}
<|endoftext|>


<commit_before>package main

import (
	"encoding/json"
	"github.com/mitchellh/osext"
	"github.com/mitchellh/packer/packer"
	"github.com/mitchellh/packer/packer/plugin"
	"io"
	"log"
	"os/exec"
	"path/filepath"
)

// This is the default, built-in configuration that ships with
// Packer.
const defaultConfig = `
{
	"plugin_min_port": 10000,
	"plugin_max_port": 25000,

	"builders": {
		"amazon-ebs": "packer-builder-amazon-ebs",
		"amazon-chroot": "packer-builder-amazon-chroot",
		"amazon-instance": "packer-builder-amazon-instance",
		"digitalocean": "packer-builder-digitalocean",
		"openstack": "packer-builder-openstack",
		"qemu": "packer-builder-qemu",
		"virtualbox": "packer-builder-virtualbox",
		"vmware": "packer-builder-vmware"
	},

	"commands": {
		"build": "packer-command-build",
		"fix": "packer-command-fix",
		"inspect": "packer-command-inspect",
		"validate": "packer-command-validate"
	},

	"post-processors": {
		"vagrant": "packer-post-processor-vagrant"
	},

	"provisioners": {
		"ansible-local": "packer-provisioner-ansible-local",
		"chef-solo": "packer-provisioner-chef-solo",
		"file": "packer-provisioner-file",
		"puppet-masterless": "packer-provisioner-puppet-masterless",
		"shell": "packer-provisioner-shell",
		"salt-masterless": "packer-provisioner-salt-masterless"
	}
}
`

type config struct {
	PluginMinPort uint
	PluginMaxPort uint

	Builders       map[string]string
	Commands       map[string]string
	PostProcessors map[string]string `json:"post-processors"`
	Provisioners   map[string]string
}

// Decodes configuration in JSON format from the given io.Reader into
// the config object pointed to.
func decodeConfig(r io.Reader, c *config) error {
	decoder := json.NewDecoder(r)
	return decoder.Decode(c)
}

// Returns an array of defined command names.
func (c *config) CommandNames() (result []string) {
	result = make([]string, 0, len(c.Commands))
	for name := range c.Commands {
		result = append(result, name)
	}
	return
}

// This is a proper packer.BuilderFunc that can be used to load packer.Builder
// implementations from the defined plugins.
func (c *config) LoadBuilder(name string) (packer.Builder, error) {
	log.Printf("Loading builder: %s\n", name)
	bin, ok := c.Builders[name]
	if !ok {
		log.Printf("Builder not found: %s\n", name)
		return nil, nil
	}

	return c.pluginClient(bin).Builder()
}

// This is a proper packer.CommandFunc that can be used to load packer.Command
// implementations from the defined plugins.
func (c *config) LoadCommand(name string) (packer.Command, error) {
	log.Printf("Loading command: %s\n", name)
	bin, ok := c.Commands[name]
	if !ok {
		log.Printf("Command not found: %s\n", name)
		return nil, nil
	}

	return c.pluginClient(bin).Command()
}

// This is a proper implementation of packer.HookFunc that can be used
// to load packer.Hook implementations from the defined plugins.
func (c *config) LoadHook(name string) (packer.Hook, error) {
	log.Printf("Loading hook: %s\n", name)
	return c.pluginClient(name).Hook()
}

// This is a proper packer.PostProcessorFunc that can be used to load
// packer.PostProcessor implementations from defined plugins.
func (c *config) LoadPostProcessor(name string) (packer.PostProcessor, error) {
	log.Printf("Loading post-processor: %s", name)
	bin, ok := c.PostProcessors[name]
	if !ok {
		log.Printf("Post-processor not found: %s", name)
		return nil, nil
	}

	return c.pluginClient(bin).PostProcessor()
}

// This is a proper packer.ProvisionerFunc that can be used to load
// packer.Provisioner implementations from defined plugins.
func (c *config) LoadProvisioner(name string) (packer.Provisioner, error) {
	log.Printf("Loading provisioner: %s\n", name)
	bin, ok := c.Provisioners[name]
	if !ok {
		log.Printf("Provisioner not found: %s\n", name)
		return nil, nil
	}

	return c.pluginClient(bin).Provisioner()
}

func (c *config) pluginClient(path string) *plugin.Client {
	originalPath := path

	// First attempt to find the executable by consulting the PATH.
	path, err := exec.LookPath(path)
	if err != nil {
		// If that doesn't work, look for it in the same directory
		// as the `packer` executable (us).
		log.Printf("Plugin could not be found. Checking same directory as executable.")
		exePath, err := osext.Executable()
		if err != nil {
			log.Printf("Couldn't get current exe path: %s", err)
		} else {
			log.Printf("Current exe path: %s", exePath)
			path = filepath.Join(filepath.Dir(exePath), filepath.Base(originalPath))
		}
	}

	// If everything failed, just use the original path and let the error
	// bubble through.
	if path == "" {
		path = originalPath
	}

	log.Printf("Creating plugin client for path: %s", path)
	var config plugin.ClientConfig
	config.Cmd = exec.Command(path)
	config.Managed = true
	config.MinPort = c.PluginMinPort
	config.MaxPort = c.PluginMaxPort
	return plugin.NewClient(&config)
}
<commit_msg>main: Default config has docker<commit_after>package main

import (
	"encoding/json"
	"github.com/mitchellh/osext"
	"github.com/mitchellh/packer/packer"
	"github.com/mitchellh/packer/packer/plugin"
	"io"
	"log"
	"os/exec"
	"path/filepath"
)

// This is the default, built-in configuration that ships with
// Packer.
const defaultConfig = `
{
	"plugin_min_port": 10000,
	"plugin_max_port": 25000,

	"builders": {
		"amazon-ebs": "packer-builder-amazon-ebs",
		"amazon-chroot": "packer-builder-amazon-chroot",
		"amazon-instance": "packer-builder-amazon-instance",
		"digitalocean": "packer-builder-digitalocean",
		"docker": "packer-builder-docker",
		"openstack": "packer-builder-openstack",
		"qemu": "packer-builder-qemu",
		"virtualbox": "packer-builder-virtualbox",
		"vmware": "packer-builder-vmware"
	},

	"commands": {
		"build": "packer-command-build",
		"fix": "packer-command-fix",
		"inspect": "packer-command-inspect",
		"validate": "packer-command-validate"
	},

	"post-processors": {
		"vagrant": "packer-post-processor-vagrant"
	},

	"provisioners": {
		"ansible-local": "packer-provisioner-ansible-local",
		"chef-solo": "packer-provisioner-chef-solo",
		"file": "packer-provisioner-file",
		"puppet-masterless": "packer-provisioner-puppet-masterless",
		"shell": "packer-provisioner-shell",
		"salt-masterless": "packer-provisioner-salt-masterless"
	}
}
`

type config struct {
	PluginMinPort uint
	PluginMaxPort uint

	Builders       map[string]string
	Commands       map[string]string
	PostProcessors map[string]string `json:"post-processors"`
	Provisioners   map[string]string
}

// Decodes configuration in JSON format from the given io.Reader into
// the config object pointed to.
func decodeConfig(r io.Reader, c *config) error {
	decoder := json.NewDecoder(r)
	return decoder.Decode(c)
}

// Returns an array of defined command names.
func (c *config) CommandNames() (result []string) {
	result = make([]string, 0, len(c.Commands))
	for name := range c.Commands {
		result = append(result, name)
	}
	return
}

// This is a proper packer.BuilderFunc that can be used to load packer.Builder
// implementations from the defined plugins.
func (c *config) LoadBuilder(name string) (packer.Builder, error) {
	log.Printf("Loading builder: %s\n", name)
	bin, ok := c.Builders[name]
	if !ok {
		log.Printf("Builder not found: %s\n", name)
		return nil, nil
	}

	return c.pluginClient(bin).Builder()
}

// This is a proper packer.CommandFunc that can be used to load packer.Command
// implementations from the defined plugins.
func (c *config) LoadCommand(name string) (packer.Command, error) {
	log.Printf("Loading command: %s\n", name)
	bin, ok := c.Commands[name]
	if !ok {
		log.Printf("Command not found: %s\n", name)
		return nil, nil
	}

	return c.pluginClient(bin).Command()
}

// This is a proper implementation of packer.HookFunc that can be used
// to load packer.Hook implementations from the defined plugins.
func (c *config) LoadHook(name string) (packer.Hook, error) {
	log.Printf("Loading hook: %s\n", name)
	return c.pluginClient(name).Hook()
}

// This is a proper packer.PostProcessorFunc that can be used to load
// packer.PostProcessor implementations from defined plugins.
func (c *config) LoadPostProcessor(name string) (packer.PostProcessor, error) {
	log.Printf("Loading post-processor: %s", name)
	bin, ok := c.PostProcessors[name]
	if !ok {
		log.Printf("Post-processor not found: %s", name)
		return nil, nil
	}

	return c.pluginClient(bin).PostProcessor()
}

// This is a proper packer.ProvisionerFunc that can be used to load
// packer.Provisioner implementations from defined plugins.
func (c *config) LoadProvisioner(name string) (packer.Provisioner, error) {
	log.Printf("Loading provisioner: %s\n", name)
	bin, ok := c.Provisioners[name]
	if !ok {
		log.Printf("Provisioner not found: %s\n", name)
		return nil, nil
	}

	return c.pluginClient(bin).Provisioner()
}

func (c *config) pluginClient(path string) *plugin.Client {
	originalPath := path

	// First attempt to find the executable by consulting the PATH.
	path, err := exec.LookPath(path)
	if err != nil {
		// If that doesn't work, look for it in the same directory
		// as the `packer` executable (us).
		log.Printf("Plugin could not be found. Checking same directory as executable.")
		exePath, err := osext.Executable()
		if err != nil {
			log.Printf("Couldn't get current exe path: %s", err)
		} else {
			log.Printf("Current exe path: %s", exePath)
			path = filepath.Join(filepath.Dir(exePath), filepath.Base(originalPath))
		}
	}

	// If everything failed, just use the original path and let the error
	// bubble through.
	if path == "" {
		path = originalPath
	}

	log.Printf("Creating plugin client for path: %s", path)
	var config plugin.ClientConfig
	config.Cmd = exec.Command(path)
	config.Managed = true
	config.MinPort = c.PluginMinPort
	config.MaxPort = c.PluginMaxPort
	return plugin.NewClient(&config)
}
<|endoftext|>


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

package bleve

import (
	"expvar"
	"github.com/blevesearch/bleve/registry"
	"time"

	// token maps
	_ "github.com/blevesearch/bleve/analysis/token_map"

	// fragment formatters
	_ "github.com/blevesearch/bleve/search/highlight/fragment_formatters/ansi"
	_ "github.com/blevesearch/bleve/search/highlight/fragment_formatters/html"

	// fragmenters
	_ "github.com/blevesearch/bleve/search/highlight/fragmenters/simple"

	// highlighters
	_ "github.com/blevesearch/bleve/search/highlight/highlighters/simple"

	// char filters
	_ "github.com/blevesearch/bleve/analysis/char_filters/html_char_filter"
	_ "github.com/blevesearch/bleve/analysis/char_filters/regexp_char_filter"
	_ "github.com/blevesearch/bleve/analysis/char_filters/zero_width_non_joiner"

	// analyzers
	_ "github.com/blevesearch/bleve/analysis/analyzers/custom_analyzer"
	_ "github.com/blevesearch/bleve/analysis/analyzers/keyword_analyzer"
	_ "github.com/blevesearch/bleve/analysis/analyzers/simple_analyzer"
	_ "github.com/blevesearch/bleve/analysis/analyzers/standard_analyzer"

	// token filters
	_ "github.com/blevesearch/bleve/analysis/token_filters/apostrophe_filter"
	_ "github.com/blevesearch/bleve/analysis/token_filters/edge_ngram_filter"
	_ "github.com/blevesearch/bleve/analysis/token_filters/elision_filter"
	_ "github.com/blevesearch/bleve/analysis/token_filters/keyword_marker_filter"
	_ "github.com/blevesearch/bleve/analysis/token_filters/length_filter"
	_ "github.com/blevesearch/bleve/analysis/token_filters/lower_case_filter"
	_ "github.com/blevesearch/bleve/analysis/token_filters/ngram_filter"
	_ "github.com/blevesearch/bleve/analysis/token_filters/shingle"
	_ "github.com/blevesearch/bleve/analysis/token_filters/stop_tokens_filter"
	_ "github.com/blevesearch/bleve/analysis/token_filters/truncate_token_filter"
	_ "github.com/blevesearch/bleve/analysis/token_filters/unicode_normalize"

	// tokenizers
	_ "github.com/blevesearch/bleve/analysis/tokenizers/regexp_tokenizer"
	_ "github.com/blevesearch/bleve/analysis/tokenizers/single_token"
	_ "github.com/blevesearch/bleve/analysis/tokenizers/whitespace_tokenizer"

	// date time parsers
	_ "github.com/blevesearch/bleve/analysis/datetime_parsers/datetime_optional"
	_ "github.com/blevesearch/bleve/analysis/datetime_parsers/flexible_go"

	// languages
	_ "github.com/blevesearch/bleve/analysis/language/ar"
	_ "github.com/blevesearch/bleve/analysis/language/bg"
	_ "github.com/blevesearch/bleve/analysis/language/ca"
	_ "github.com/blevesearch/bleve/analysis/language/ckb"
	_ "github.com/blevesearch/bleve/analysis/language/cs"
	_ "github.com/blevesearch/bleve/analysis/language/da"
	_ "github.com/blevesearch/bleve/analysis/language/de"
	_ "github.com/blevesearch/bleve/analysis/language/el"
	_ "github.com/blevesearch/bleve/analysis/language/en"
	_ "github.com/blevesearch/bleve/analysis/language/es"
	_ "github.com/blevesearch/bleve/analysis/language/eu"
	_ "github.com/blevesearch/bleve/analysis/language/fa"
	_ "github.com/blevesearch/bleve/analysis/language/fi"
	_ "github.com/blevesearch/bleve/analysis/language/fr"
	_ "github.com/blevesearch/bleve/analysis/language/ga"
	_ "github.com/blevesearch/bleve/analysis/language/gl"
	_ "github.com/blevesearch/bleve/analysis/language/hi"
	_ "github.com/blevesearch/bleve/analysis/language/hu"
	_ "github.com/blevesearch/bleve/analysis/language/hy"
	_ "github.com/blevesearch/bleve/analysis/language/id"
	_ "github.com/blevesearch/bleve/analysis/language/it"
	_ "github.com/blevesearch/bleve/analysis/language/nl"
	_ "github.com/blevesearch/bleve/analysis/language/no"
	_ "github.com/blevesearch/bleve/analysis/language/pt"
	_ "github.com/blevesearch/bleve/analysis/language/ro"
	_ "github.com/blevesearch/bleve/analysis/language/ru"
	_ "github.com/blevesearch/bleve/analysis/language/sv"
	_ "github.com/blevesearch/bleve/analysis/language/th"
	_ "github.com/blevesearch/bleve/analysis/language/tr"

	// kv stores
	_ "github.com/blevesearch/bleve/index/store/boltdb"
	_ "github.com/blevesearch/bleve/index/store/inmem"

	// byte array converters
	_ "github.com/blevesearch/bleve/analysis/byte_array_converters/ignore"
	_ "github.com/blevesearch/bleve/analysis/byte_array_converters/json"
	_ "github.com/blevesearch/bleve/analysis/byte_array_converters/string"
)

var bleveExpVar = expvar.NewMap("bleve")

type configuration struct {
	Cache              *registry.Cache
	DefaultHighlighter string
	DefaultKVStore     string
}

func newConfiguration() *configuration {
	return &configuration{
		Cache: registry.NewCache(),
	}
}

// Config contains library level configuration
var Config *configuration

func init() {
	bootStart := time.Now()

	// build the default configuration
	Config = newConfiguration()

	Config.Cache.DefineFragmentFormatter("highlightSpanHTML",
		map[string]interface{}{
			"type":   "html",
			"before": `<span class="highlight">`,
			"after":  `</span>`,
		})

	Config.Cache.DefineHighlighter("html",
		map[string]interface{}{
			"type":       "simple",
			"fragmenter": "simple",
			"formatter":  "highlightSpanHTML",
		})

	Config.Cache.DefineHighlighter("ansi",
		map[string]interface{}{
			"type":       "simple",
			"fragmenter": "simple",
			"formatter":  "ansi",
		})

	// set the default highlighter
	Config.DefaultHighlighter = "html"

	// default kv store
	Config.DefaultKVStore = "boltdb"

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

package bleve

import (
	"expvar"
	"github.com/blevesearch/bleve/registry"
	"time"

	// token maps
	_ "github.com/blevesearch/bleve/analysis/token_map"

	// fragment formatters
	_ "github.com/blevesearch/bleve/search/highlight/fragment_formatters/ansi"
	_ "github.com/blevesearch/bleve/search/highlight/fragment_formatters/html"

	// fragmenters
	_ "github.com/blevesearch/bleve/search/highlight/fragmenters/simple"

	// highlighters
	_ "github.com/blevesearch/bleve/search/highlight/highlighters/simple"

	// char filters
	_ "github.com/blevesearch/bleve/analysis/char_filters/html_char_filter"
	_ "github.com/blevesearch/bleve/analysis/char_filters/regexp_char_filter"
	_ "github.com/blevesearch/bleve/analysis/char_filters/zero_width_non_joiner"

	// analyzers
	_ "github.com/blevesearch/bleve/analysis/analyzers/custom_analyzer"
	_ "github.com/blevesearch/bleve/analysis/analyzers/keyword_analyzer"
	_ "github.com/blevesearch/bleve/analysis/analyzers/simple_analyzer"
	_ "github.com/blevesearch/bleve/analysis/analyzers/standard_analyzer"

	// token filters
	_ "github.com/blevesearch/bleve/analysis/token_filters/apostrophe_filter"
	_ "github.com/blevesearch/bleve/analysis/token_filters/edge_ngram_filter"
	_ "github.com/blevesearch/bleve/analysis/token_filters/elision_filter"
	_ "github.com/blevesearch/bleve/analysis/token_filters/keyword_marker_filter"
	_ "github.com/blevesearch/bleve/analysis/token_filters/length_filter"
	_ "github.com/blevesearch/bleve/analysis/token_filters/lower_case_filter"
	_ "github.com/blevesearch/bleve/analysis/token_filters/ngram_filter"
	_ "github.com/blevesearch/bleve/analysis/token_filters/shingle"
	_ "github.com/blevesearch/bleve/analysis/token_filters/stop_tokens_filter"
	_ "github.com/blevesearch/bleve/analysis/token_filters/truncate_token_filter"
	_ "github.com/blevesearch/bleve/analysis/token_filters/unicode_normalize"

	// tokenizers
	_ "github.com/blevesearch/bleve/analysis/tokenizers/regexp_tokenizer"
	_ "github.com/blevesearch/bleve/analysis/tokenizers/single_token"
	_ "github.com/blevesearch/bleve/analysis/tokenizers/whitespace_tokenizer"

	// date time parsers
	_ "github.com/blevesearch/bleve/analysis/datetime_parsers/datetime_optional"
	_ "github.com/blevesearch/bleve/analysis/datetime_parsers/flexible_go"

	// languages
	_ "github.com/blevesearch/bleve/analysis/language/ar"
	_ "github.com/blevesearch/bleve/analysis/language/bg"
	_ "github.com/blevesearch/bleve/analysis/language/ca"
	_ "github.com/blevesearch/bleve/analysis/language/cjk"
	_ "github.com/blevesearch/bleve/analysis/language/ckb"
	_ "github.com/blevesearch/bleve/analysis/language/cs"
	_ "github.com/blevesearch/bleve/analysis/language/da"
	_ "github.com/blevesearch/bleve/analysis/language/de"
	_ "github.com/blevesearch/bleve/analysis/language/el"
	_ "github.com/blevesearch/bleve/analysis/language/en"
	_ "github.com/blevesearch/bleve/analysis/language/es"
	_ "github.com/blevesearch/bleve/analysis/language/eu"
	_ "github.com/blevesearch/bleve/analysis/language/fa"
	_ "github.com/blevesearch/bleve/analysis/language/fi"
	_ "github.com/blevesearch/bleve/analysis/language/fr"
	_ "github.com/blevesearch/bleve/analysis/language/ga"
	_ "github.com/blevesearch/bleve/analysis/language/gl"
	_ "github.com/blevesearch/bleve/analysis/language/hi"
	_ "github.com/blevesearch/bleve/analysis/language/hu"
	_ "github.com/blevesearch/bleve/analysis/language/hy"
	_ "github.com/blevesearch/bleve/analysis/language/id"
	_ "github.com/blevesearch/bleve/analysis/language/it"
	_ "github.com/blevesearch/bleve/analysis/language/nl"
	_ "github.com/blevesearch/bleve/analysis/language/no"
	_ "github.com/blevesearch/bleve/analysis/language/pt"
	_ "github.com/blevesearch/bleve/analysis/language/ro"
	_ "github.com/blevesearch/bleve/analysis/language/ru"
	_ "github.com/blevesearch/bleve/analysis/language/sv"
	_ "github.com/blevesearch/bleve/analysis/language/th"
	_ "github.com/blevesearch/bleve/analysis/language/tr"

	// kv stores
	_ "github.com/blevesearch/bleve/index/store/boltdb"
	_ "github.com/blevesearch/bleve/index/store/inmem"

	// byte array converters
	_ "github.com/blevesearch/bleve/analysis/byte_array_converters/ignore"
	_ "github.com/blevesearch/bleve/analysis/byte_array_converters/json"
	_ "github.com/blevesearch/bleve/analysis/byte_array_converters/string"
)

var bleveExpVar = expvar.NewMap("bleve")

type configuration struct {
	Cache              *registry.Cache
	DefaultHighlighter string
	DefaultKVStore     string
}

func newConfiguration() *configuration {
	return &configuration{
		Cache: registry.NewCache(),
	}
}

// Config contains library level configuration
var Config *configuration

func init() {
	bootStart := time.Now()

	// build the default configuration
	Config = newConfiguration()

	Config.Cache.DefineFragmentFormatter("highlightSpanHTML",
		map[string]interface{}{
			"type":   "html",
			"before": `<span class="highlight">`,
			"after":  `</span>`,
		})

	Config.Cache.DefineHighlighter("html",
		map[string]interface{}{
			"type":       "simple",
			"fragmenter": "simple",
			"formatter":  "highlightSpanHTML",
		})

	Config.Cache.DefineHighlighter("ansi",
		map[string]interface{}{
			"type":       "simple",
			"fragmenter": "simple",
			"formatter":  "ansi",
		})

	// set the default highlighter
	Config.DefaultHighlighter = "html"

	// default kv store
	Config.DefaultKVStore = "boltdb"

	bootDuration := time.Since(bootStart)
	bleveExpVar.Add("bootDuration", int64(bootDuration))
}
<|endoftext|>


<commit_before>package lxd

import (
	"fmt"
	"io/ioutil"
	"os"
	"path"
	"path/filepath"
	"strings"

	"gopkg.in/yaml.v2"

	"github.com/lxc/lxd/shared"
)

// Config holds settings to be used by a client or daemon.
type Config struct {
	// DefaultRemote holds the remote daemon name from the Remotes map
	// that the client should communicate with by default.
	// If empty it defaults to "local".
	DefaultRemote string `yaml:"default-remote"`

	// Remotes defines a map of remote daemon names to the details for
	// communication with the named daemon.
	// The implicit "local" remote is always available and communicates
	// with the local daemon over a unix socket.
	Remotes map[string]RemoteConfig `yaml:"remotes"`

	// Command line aliases for `lxc`
	Aliases map[string]string `yaml:"aliases"`

	// This is the path to the config directory, so the client can find
	// previously stored server certs, give good error messages, and save
	// new server certs, etc.
	//
	// We don't need to store it, because of course once we've loaded this
	// structure we already know where it is :)
	ConfigDir string `yaml:"-"`
}

// RemoteConfig holds details for communication with a remote daemon.
type RemoteConfig struct {
	Addr     string `yaml:"addr"`
	Public   bool   `yaml:"public"`
	Protocol string `yaml:"protocol,omitempty"`
	Static   bool   `yaml:"-"`
}

var LocalRemote = RemoteConfig{
	Addr:   "unix://",
	Static: true,
	Public: false}

var UbuntuRemote = RemoteConfig{
	Addr:     "https://cloud-images.ubuntu.com/releases",
	Static:   true,
	Public:   true,
	Protocol: "simplestreams"}

var UbuntuDailyRemote = RemoteConfig{
	Addr:     "https://cloud-images.ubuntu.com/daily",
	Static:   true,
	Public:   true,
	Protocol: "simplestreams"}

var StaticRemotes = map[string]RemoteConfig{
	"local":        LocalRemote,
	"ubuntu":       UbuntuRemote,
	"ubuntu-daily": UbuntuDailyRemote}

var DefaultConfig = Config{
	Remotes:       StaticRemotes,
	DefaultRemote: "local",
	Aliases:       map[string]string{},
}

// LoadConfig reads the configuration from the config path; if the path does
// not exist, it returns a default configuration.
func LoadConfig(path string) (*Config, error) {
	data, err := ioutil.ReadFile(path)
	if os.IsNotExist(err) {
		// A missing file is equivalent to the default configuration.
		withPath := DefaultConfig
		withPath.ConfigDir = filepath.Dir(path)
		return &withPath, nil
	}
	if err != nil {
		return nil, fmt.Errorf("cannot read config file: %v", err)
	}

	var c Config
	err = yaml.Unmarshal(data, &c)
	if err != nil {
		return nil, fmt.Errorf("cannot parse configuration: %v", err)
	}
	if c.Remotes == nil {
		c.Remotes = make(map[string]RemoteConfig)
	}
	c.ConfigDir = filepath.Dir(path)

	for k, v := range StaticRemotes {
		c.Remotes[k] = v
	}

	return &c, nil
}

// SaveConfig writes the provided configuration to the config file.
func SaveConfig(c *Config, fname string) error {
	for k, _ := range StaticRemotes {
		delete(c.Remotes, k)
	}

	// Ignore errors on these two calls. Create will report any problems.
	os.Remove(fname + ".new")
	os.Mkdir(filepath.Dir(fname), 0700)
	f, err := os.Create(fname + ".new")
	if err != nil {
		return fmt.Errorf("cannot create config file: %v", err)
	}

	// If there are any errors, do not leave it around.
	defer f.Close()
	defer os.Remove(fname + ".new")

	data, err := yaml.Marshal(c)
	_, err = f.Write(data)
	if err != nil {
		return fmt.Errorf("cannot write configuration: %v", err)
	}

	f.Close()
	err = shared.FileMove(fname+".new", fname)
	if err != nil {
		return fmt.Errorf("cannot rename temporary config file: %v", err)
	}
	return nil
}

func (c *Config) ParseRemoteAndContainer(raw string) (string, string) {
	result := strings.SplitN(raw, ":", 2)
	if len(result) == 1 {
		return c.DefaultRemote, result[0]
	}
	return result[0], result[1]
}

func (c *Config) ParseRemote(raw string) string {
	return strings.SplitN(raw, ":", 2)[0]
}

func (c *Config) ConfigPath(file string) string {
	return path.Join(c.ConfigDir, file)
}

func (c *Config) ServerCertPath(name string) string {
	return path.Join(c.ConfigDir, "servercerts", fmt.Sprintf("%s.crt", name))
}
<commit_msg>Add the images remote to default config<commit_after>package lxd

import (
	"fmt"
	"io/ioutil"
	"os"
	"path"
	"path/filepath"
	"strings"

	"gopkg.in/yaml.v2"

	"github.com/lxc/lxd/shared"
)

// Config holds settings to be used by a client or daemon.
type Config struct {
	// DefaultRemote holds the remote daemon name from the Remotes map
	// that the client should communicate with by default.
	// If empty it defaults to "local".
	DefaultRemote string `yaml:"default-remote"`

	// Remotes defines a map of remote daemon names to the details for
	// communication with the named daemon.
	// The implicit "local" remote is always available and communicates
	// with the local daemon over a unix socket.
	Remotes map[string]RemoteConfig `yaml:"remotes"`

	// Command line aliases for `lxc`
	Aliases map[string]string `yaml:"aliases"`

	// This is the path to the config directory, so the client can find
	// previously stored server certs, give good error messages, and save
	// new server certs, etc.
	//
	// We don't need to store it, because of course once we've loaded this
	// structure we already know where it is :)
	ConfigDir string `yaml:"-"`
}

// RemoteConfig holds details for communication with a remote daemon.
type RemoteConfig struct {
	Addr     string `yaml:"addr"`
	Public   bool   `yaml:"public"`
	Protocol string `yaml:"protocol,omitempty"`
	Static   bool   `yaml:"-"`
}

var LocalRemote = RemoteConfig{
	Addr:   "unix://",
	Static: true,
	Public: false}

var ImagesRemote = RemoteConfig{
	Addr:   "https://images.linuxcontainers.org",
	Public: true}

var UbuntuRemote = RemoteConfig{
	Addr:     "https://cloud-images.ubuntu.com/releases",
	Static:   true,
	Public:   true,
	Protocol: "simplestreams"}

var UbuntuDailyRemote = RemoteConfig{
	Addr:     "https://cloud-images.ubuntu.com/daily",
	Static:   true,
	Public:   true,
	Protocol: "simplestreams"}

var StaticRemotes = map[string]RemoteConfig{
	"local":        LocalRemote,
	"ubuntu":       UbuntuRemote,
	"ubuntu-daily": UbuntuDailyRemote}

var DefaultRemotes = map[string]RemoteConfig{
	"images":       ImagesRemote,
	"local":        LocalRemote,
	"ubuntu":       UbuntuRemote,
	"ubuntu-daily": UbuntuDailyRemote}

var DefaultConfig = Config{
	Remotes:       DefaultRemotes,
	DefaultRemote: "local",
	Aliases:       map[string]string{},
}

// LoadConfig reads the configuration from the config path; if the path does
// not exist, it returns a default configuration.
func LoadConfig(path string) (*Config, error) {
	data, err := ioutil.ReadFile(path)
	if os.IsNotExist(err) {
		// A missing file is equivalent to the default configuration.
		withPath := DefaultConfig
		withPath.ConfigDir = filepath.Dir(path)
		return &withPath, nil
	}
	if err != nil {
		return nil, fmt.Errorf("cannot read config file: %v", err)
	}

	var c Config
	err = yaml.Unmarshal(data, &c)
	if err != nil {
		return nil, fmt.Errorf("cannot parse configuration: %v", err)
	}
	if c.Remotes == nil {
		c.Remotes = make(map[string]RemoteConfig)
	}
	c.ConfigDir = filepath.Dir(path)

	for k, v := range StaticRemotes {
		c.Remotes[k] = v
	}

	return &c, nil
}

// SaveConfig writes the provided configuration to the config file.
func SaveConfig(c *Config, fname string) error {
	for k, _ := range StaticRemotes {
		delete(c.Remotes, k)
	}

	// Ignore errors on these two calls. Create will report any problems.
	os.Remove(fname + ".new")
	os.Mkdir(filepath.Dir(fname), 0700)
	f, err := os.Create(fname + ".new")
	if err != nil {
		return fmt.Errorf("cannot create config file: %v", err)
	}

	// If there are any errors, do not leave it around.
	defer f.Close()
	defer os.Remove(fname + ".new")

	data, err := yaml.Marshal(c)
	_, err = f.Write(data)
	if err != nil {
		return fmt.Errorf("cannot write configuration: %v", err)
	}

	f.Close()
	err = shared.FileMove(fname+".new", fname)
	if err != nil {
		return fmt.Errorf("cannot rename temporary config file: %v", err)
	}
	return nil
}

func (c *Config) ParseRemoteAndContainer(raw string) (string, string) {
	result := strings.SplitN(raw, ":", 2)
	if len(result) == 1 {
		return c.DefaultRemote, result[0]
	}
	return result[0], result[1]
}

func (c *Config) ParseRemote(raw string) string {
	return strings.SplitN(raw, ":", 2)[0]
}

func (c *Config) ConfigPath(file string) string {
	return path.Join(c.ConfigDir, file)
}

func (c *Config) ServerCertPath(name string) string {
	return path.Join(c.ConfigDir, "servercerts", fmt.Sprintf("%s.crt", name))
}
<|endoftext|>