David K. Bainbridge | 528b318 | 2017-01-23 08:51:59 -0800 | [diff] [blame] | 1 | // Copyright 2014 Canonical Ltd. |
| 2 | // Licensed under the LGPLv3, see LICENCE file for details. |
| 3 | |
| 4 | package names |
| 5 | |
| 6 | import ( |
| 7 | "fmt" |
| 8 | |
| 9 | "github.com/juju/errors" |
| 10 | "github.com/juju/utils" |
| 11 | ) |
| 12 | |
| 13 | const ActionTagKind = "action" |
| 14 | |
| 15 | type ActionTag struct { |
| 16 | // Tags that are serialized need to have fields exported. |
| 17 | ID utils.UUID |
| 18 | } |
| 19 | |
| 20 | // NewActionTag returns the tag of an action with the given id (UUID). |
| 21 | func NewActionTag(id string) ActionTag { |
| 22 | uuid, err := utils.UUIDFromString(id) |
| 23 | if err != nil { |
| 24 | panic(err) |
| 25 | } |
| 26 | return ActionTag{ID: uuid} |
| 27 | } |
| 28 | |
| 29 | // ParseActionTag parses an action tag string. |
| 30 | func ParseActionTag(actionTag string) (ActionTag, error) { |
| 31 | tag, err := ParseTag(actionTag) |
| 32 | if err != nil { |
| 33 | return ActionTag{}, err |
| 34 | } |
| 35 | at, ok := tag.(ActionTag) |
| 36 | if !ok { |
| 37 | return ActionTag{}, invalidTagError(actionTag, ActionTagKind) |
| 38 | } |
| 39 | return at, nil |
| 40 | } |
| 41 | |
| 42 | func (t ActionTag) String() string { return t.Kind() + "-" + t.Id() } |
| 43 | func (t ActionTag) Kind() string { return ActionTagKind } |
| 44 | func (t ActionTag) Id() string { return t.ID.String() } |
| 45 | |
| 46 | // IsValidAction returns whether id is a valid action id (UUID). |
| 47 | func IsValidAction(id string) bool { |
| 48 | return utils.IsValidUUIDString(id) |
| 49 | } |
| 50 | |
| 51 | // ActionReceiverTag returns an ActionReceiver Tag from a |
| 52 | // machine or unit name. |
| 53 | func ActionReceiverTag(name string) (Tag, error) { |
| 54 | if IsValidUnit(name) { |
| 55 | return NewUnitTag(name), nil |
| 56 | } |
| 57 | if IsValidApplication(name) { |
| 58 | // TODO(jcw4) enable when leader elections complete |
| 59 | //return NewApplicationTag(name), nil |
| 60 | } |
| 61 | if IsValidMachine(name) { |
| 62 | return NewMachineTag(name), nil |
| 63 | } |
| 64 | return nil, fmt.Errorf("invalid actionreceiver name %q", name) |
| 65 | } |
| 66 | |
| 67 | // ActionReceiverFrom Tag returns an ActionReceiver tag from |
| 68 | // a machine or unit tag. |
| 69 | func ActionReceiverFromTag(tag string) (Tag, error) { |
| 70 | unitTag, err := ParseUnitTag(tag) |
| 71 | if err == nil { |
| 72 | return unitTag, nil |
| 73 | } |
| 74 | machineTag, err := ParseMachineTag(tag) |
| 75 | if err == nil { |
| 76 | return machineTag, nil |
| 77 | } |
| 78 | return nil, errors.Errorf("invalid actionreceiver tag %q", tag) |
| 79 | } |