github.com/makyo/juju@v0.0.0-20160425123129-2608902037e9/state/distribution.go (about) 1 // Copyright 2014 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package state 5 6 import ( 7 "fmt" 8 9 "github.com/juju/errors" 10 11 "github.com/juju/juju/instance" 12 ) 13 14 // distributeuUnit takes a unit and set of clean, possibly empty, instances 15 // and asks the InstanceDistributor policy (if any) which ones are suitable 16 // for assigning the unit to. If there is no InstanceDistributor, or the 17 // distribution group is empty, then all of the candidates will be returned. 18 func distributeUnit(u *Unit, candidates []instance.Id) ([]instance.Id, error) { 19 if len(candidates) == 0 { 20 return nil, nil 21 } 22 if u.st.policy == nil { 23 return candidates, nil 24 } 25 cfg, err := u.st.ModelConfig() 26 if err != nil { 27 return nil, err 28 } 29 distributor, err := u.st.policy.InstanceDistributor(cfg) 30 if errors.IsNotImplemented(err) { 31 return candidates, nil 32 } else if err != nil { 33 return nil, err 34 } 35 if distributor == nil { 36 return nil, fmt.Errorf("policy returned nil instance distributor without an error") 37 } 38 distributionGroup, err := ServiceInstances(u.st, u.doc.Service) 39 if err != nil { 40 return nil, err 41 } 42 if len(distributionGroup) == 0 { 43 return candidates, nil 44 } 45 return distributor.DistributeInstances(candidates, distributionGroup) 46 } 47 48 // ServiceInstances returns the instance IDs of provisioned 49 // machines that are assigned units of the specified service. 50 func ServiceInstances(st *State, service string) ([]instance.Id, error) { 51 units, err := allUnits(st, service) 52 if err != nil { 53 return nil, err 54 } 55 instanceIds := make([]instance.Id, 0, len(units)) 56 for _, unit := range units { 57 machineId, err := unit.AssignedMachineId() 58 if errors.IsNotAssigned(err) { 59 continue 60 } else if err != nil { 61 return nil, err 62 } 63 machine, err := st.Machine(machineId) 64 if err != nil { 65 return nil, err 66 } 67 instanceId, err := machine.InstanceId() 68 if err == nil { 69 instanceIds = append(instanceIds, instanceId) 70 } else if errors.IsNotProvisioned(err) { 71 continue 72 } else { 73 return nil, err 74 } 75 } 76 return instanceIds, nil 77 }