// NewMachinePool calculates stats from a model.Bot and generates a MachinePool.
// This requires a context because setting the UI Status field requires the current time.
541838
func NewMachinePool(c context.Context, botPool *model.BotPool) *MachinePool {
	fiveMinAgo := clock.Now(c).Add(-time.Minute * 5)
	result := &MachinePool{
		Total:        len(botPool.Bots),
		Bots:         make([]Bot, len(botPool.Bots)),
		Dimensions:   botPool.Descriptor.Dimensions().Format(),
		SwarmingHost: botPool.Descriptor.Host(),
	}
	for i, bot := range botPool.Bots {
		uiBot := Bot{bot, bot.Status} // Wrap the model.Bot
		if bot.Status == model.Offline && bot.LastSeen.After(fiveMinAgo) {
			// If the bot has been offline for less than 5 minutes, mark it as busy.
			uiBot.Status = model.Busy
		}
		switch bot.Status {
		case model.Idle:
			result.Idle++
		case model.Busy:
			result.Busy++
		case model.Offline:
			result.Offline++
		}
		result.Bots[i] = uiBot
	}
	return result
}
427284
func (c *Controller) updateMachine(ch MachineChange) {
	c.ensureModel(ch.ModelUUID).updateMachine(ch, c.manager)
}
1171174
func NewPool(n, bufSize int) *pool {
	return &pool{
		buffers: make(chan []byte, n),
		size:    bufSize,
	}
}
913680
func Pool() *sync.Pool {
	v := new(sync.Pool)
	v.New = func() interface{} {
		return NewFromPool(v)
	}
	return v
}
1334875
func (st modelManagerStateShim) NewModel(args state.ModelArgs) (Model, ModelManagerBackend, error) {
	controller := state.NewController(st.pool)
	otherModel, otherState, err := controller.NewModel(args)
	if err != nil {
		return nil, nil, err
	}
	return modelShim{otherModel}, modelManagerStateShim{otherState, otherModel, st.pool}, nil
}
68961
func NewResourcePool(factory Factory, capacity, maxCap int, idleTimeout time.Duration) *ResourcePool {
	if capacity <= 0 || maxCap <= 0 || capacity > maxCap {
		panic(fmt.Errorf("Invalid/out of range capacity"))
	}
	rp := &ResourcePool{
		resources:   make(chan resourceWrapper, maxCap),
		factory:     factory,
		capacity:    sync2.AtomicInt64(capacity),
		idleTimeout: sync2.AtomicDuration(idleTimeout),
	}
	for i := 0; i < capacity; i++ {
		rp.resources <- resourceWrapper{}
	}
	return rp
}
867291
func NewObjectPoolWithAbandonedConfig(ctx context.Context, factory PooledObjectFactory, config *ObjectPoolConfig, abandonedConfig *AbandonedConfig) *ObjectPool {
	pool := ObjectPool{factory: factory, Config: config,
		idleObjects:             collections.NewDeque(math.MaxInt32),
		allObjects:              collections.NewSyncMap(),
		createCount:             concurrent.AtomicInteger(0),
		destroyedByEvictorCount: concurrent.AtomicInteger(0),
		destroyedCount:          concurrent.AtomicInteger(0),
		AbandonedConfig:         abandonedConfig}
	pool.StartEvictor()
	return &pool
}
610338
func NewIOThrottlerPool(bandwidth Bandwidth) *IOThrottlerPool {

	pool := &IOThrottlerPool{make(chan Bandwidth), make(chan Bandwidth), make(chan Bandwidth), make(chan int64), make(chan bool)}

	go throttlerPoolDriver(pool)

	pool.bandwidthSettingChan <- bandwidth

	return pool
}
1250663
func (st *State) AddOneMachine(template MachineTemplate) (*Machine, error) {
	ms, err := st.AddMachines(template)
	if err != nil {
		return nil, err
	}
	return ms[0], nil
}
48644
func (c *CloudAPI) CreateMachine(name, pkg, image string, networks []string, metadata, tags map[string]string) (*cloudapi.Machine, error) {
	if err := c.ProcessFunctionHook(c, name, pkg, image); err != nil {
		return nil, err
	}

	machineID, err := localservices.NewUUID()
	if err != nil {
		return nil, err
	}

	mPkg, err := c.GetPackage(pkg)
	if err != nil {
		return nil, err
	}

	mImg, err := c.GetImage(image)
	if err != nil {
		return nil, err
	}

	mNetworks := []string{}
	for _, network := range networks {
		mNetwork, err := c.GetNetwork(network)
		if err != nil {
			return nil, err
		}

		mNetworks = append(mNetworks, mNetwork.Id)
	}

	publicIP := generatePublicIPAddress()

	newMachine := cloudapi.Machine{
		Id:        machineID,
		Name:      name,
		Type:      mImg.Type,
		State:     "running",
		Memory:    mPkg.Memory,
		Disk:      mPkg.Disk,
		IPs:       []string{publicIP, generatePrivateIPAddress()},
		Created:   time.Now().Format("2013-11-26T19:47:13.448Z"),
		Package:   pkg,
		Image:     image,
		Metadata:  metadata,
		Tags:      tags,
		PrimaryIP: publicIP,
		Networks:  mNetworks,
	}

	nics := map[string]*cloudapi.NIC{}
	nicNetworks := map[string]string{}
	for i, network := range mNetworks {
		mac, err := localservices.NewMAC()
		if err != nil {
			return nil, err
		}

		nics[mac] = &cloudapi.NIC{
			IP:      fmt.Sprintf("10.88.88.%d", i),
			MAC:     mac,
			Primary: i == 0,
			Netmask: "255.255.255.0",
			Gateway: "10.88.88.2",
			State:   cloudapi.NICStateRunning,
			Network: network,
		}
		nicNetworks[mac] = network
	}

	c.machines = append(c.machines, &machine{newMachine, nics, nicNetworks})

	return &newMachine, nil
}
1088517
func (e *ModelMachinesWatcher) WatchModelMachines() (params.StringsWatchResult, error) {
	result := params.StringsWatchResult{}
	if !e.authorizer.AuthController() {
		return result, ErrPerm
	}
	watch := e.st.WatchModelMachines()
	// Consume the initial event and forward it to the result.
	if changes, ok := <-watch.Changes(); ok {
		result.StringsWatcherId = e.resources.Register(watch)
		result.Changes = changes
	} else {
		err := watcher.EnsureErr(watch)
		return result, fmt.Errorf("cannot obtain initial model machines: %v", err)
	}
	return result, nil
}
295294
func (st *State) AddMachine(series string, jobs ...MachineJob) (*Machine, error) {
	ms, err := st.AddMachines(MachineTemplate{
		Series: series,
		Jobs:   jobs,
	})
	if err != nil {
		return nil, err
	}
	return ms[0], nil
}
185906
func (client *Client) AddMachines(machineParams []params.AddMachineParams) ([]params.AddMachinesResult, error) {
	args := params.AddMachines{
		MachineParams: machineParams,
	}
	results := new(params.AddMachinesResults)
	err := client.facade.FacadeCall("AddMachines", args, results)
	if len(results.Machines) != len(machineParams) {
		return nil, errors.Errorf("expected %d result, got %d", len(machineParams), len(results.Machines))
	}
	return results.Machines, err
}
56070
func (task *provisionerTask) startMachines(machines []apiprovisioner.MachineProvisioner) error {
	if len(machines) == 0 {
		return nil
	}

	// Get the distributionGroups for each machine now to avoid
	// successive calls to DistributionGroupByMachineId which will
	// return the same data.
	machineTags := make([]names.MachineTag, len(machines))
	for i, machine := range machines {
		machineTags[i] = machine.MachineTag()
	}
	machineDistributionGroups, err := task.distributionGroupFinder.DistributionGroupByMachineId(machineTags...)
	if err != nil {
		return err
	}

	var wg sync.WaitGroup
	errMachines := make([]error, len(machines))
	for i, m := range machines {
		if machineDistributionGroups[i].Err != nil {
			task.setErrorStatus(
				"fetching distribution groups for machine %q: %v",
				m, machineDistributionGroups[i].Err,
			)
			continue
		}
		wg.Add(1)
		go func(machine apiprovisioner.MachineProvisioner, dg []string, index int) {
			defer wg.Done()
			if err := task.startMachine(machine, dg); err != nil {
				task.removeMachineFromAZMap(machine)
				errMachines[index] = err
			}
		}(m, machineDistributionGroups[i].MachineIds, i)
	}

	wg.Wait()
	select {
	case <-task.catacomb.Dying():
		return task.catacomb.ErrDying()
	default:
	}
	var errorStrings []string
	for _, err := range errMachines {
		if err != nil {
			errorStrings = append(errorStrings, err.Error())
		}
	}
	if errorStrings != nil {
		return errors.New(strings.Join(errorStrings, "\n"))
	}
	return nil
}
1372864
func NewWorkerPool(ctx interface{}, concurrency uint, namespace string, pool *redis.Pool) *WorkerPool {
	return NewWorkerPoolWithOptions(ctx, concurrency, namespace, pool, WorkerPoolOptions{})
}
18104
func NewMachinerAPI(st *state.State, resources facade.Resources, authorizer facade.Authorizer) (*MachinerAPI, error) {
	if !authorizer.AuthMachineAgent() {
		return nil, common.ErrPerm
	}
	getCanModify := func() (common.AuthFunc, error) {
		return authorizer.AuthOwner, nil
	}
	getCanRead := func() (common.AuthFunc, error) {
		return authorizer.AuthOwner, nil
	}
	return &MachinerAPI{
		LifeGetter:         common.NewLifeGetter(st, getCanRead),
		StatusSetter:       common.NewStatusSetter(st, getCanModify),
		DeadEnsurer:        common.NewDeadEnsurer(st, getCanModify),
		AgentEntityWatcher: common.NewAgentEntityWatcher(st, resources, getCanRead),
		APIAddresser:       common.NewAPIAddresser(st, resources),
		NetworkConfigAPI:   networkingcommon.NewNetworkConfigAPI(st, state.CallContext(st), getCanModify),
		st:                 st,
		auth:               authorizer,
		getCanModify:       getCanModify,
		getCanRead:         getCanRead,
	}, nil
}
1017904
func NewPool(newFn func() (Conn, error), maxIdle int) *Pool {
	return &Pool{Dial: newFn, MaxIdle: maxIdle}
}