github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/worker/lease/secretaries.go (about) 1 // Copyright 2018 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package lease 5 6 import ( 7 "time" 8 9 "github.com/juju/errors" 10 "gopkg.in/juju/names.v2" 11 12 "github.com/juju/juju/core/lease" 13 ) 14 15 // SingularSecretary implements Secretary to restrict claims to either 16 // a lease for the controller or the specific model it's asking for, 17 // holdable only by machine-tag strings. 18 type SingularSecretary struct { 19 ControllerUUID string 20 } 21 22 // CheckLease is part of the lease.Secretary interface. 23 func (s SingularSecretary) CheckLease(key lease.Key) error { 24 if key.Lease != s.ControllerUUID && key.Lease != key.ModelUUID { 25 return errors.New("expected controller or model UUID") 26 } 27 return nil 28 } 29 30 // CheckHolder is part of the lease.Secretary interface. 31 func (s SingularSecretary) CheckHolder(name string) error { 32 if _, err := names.ParseMachineTag(name); err != nil { 33 return errors.New("expected machine tag") 34 } 35 return nil 36 } 37 38 // CheckDuration is part of the lease.Secretary interface. 39 func (s SingularSecretary) CheckDuration(duration time.Duration) error { 40 if duration <= 0 { 41 return errors.NewNotValid(nil, "non-positive") 42 } 43 return nil 44 } 45 46 // LeadershipSecretary implements Secretary; it checks that leases are 47 // application names, and holders are unit names. 48 type LeadershipSecretary struct{} 49 50 // CheckLease is part of the lease.Secretary interface. 51 func (LeadershipSecretary) CheckLease(key lease.Key) error { 52 if !names.IsValidApplication(key.Lease) { 53 return errors.NewNotValid(nil, "not an application name") 54 } 55 return nil 56 } 57 58 // CheckHolder is part of the lease.Secretary interface. 59 func (LeadershipSecretary) CheckHolder(name string) error { 60 if !names.IsValidUnit(name) { 61 return errors.NewNotValid(nil, "not a unit name") 62 } 63 return nil 64 } 65 66 // CheckDuration is part of the lease.Secretary interface. 67 func (LeadershipSecretary) CheckDuration(duration time.Duration) error { 68 if duration <= 0 { 69 return errors.NewNotValid(nil, "non-positive") 70 } 71 return nil 72 } 73 74 // SecretaryFinder returns a function to find the correct secretary to 75 // use for validation for a specific lease namespace (or an error if 76 // the namespace isn't valid). 77 func SecretaryFinder(controllerUUID string) func(string) (Secretary, error) { 78 secretaries := map[string]Secretary{ 79 lease.ApplicationLeadershipNamespace: LeadershipSecretary{}, 80 lease.SingularControllerNamespace: SingularSecretary{ 81 ControllerUUID: controllerUUID, 82 }, 83 } 84 return func(namespace string) (Secretary, error) { 85 result, found := secretaries[namespace] 86 if !found { 87 return nil, errors.NotValidf("namespace %q", namespace) 88 } 89 return result, nil 90 } 91 }