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 | "regexp" |
| 9 | "strings" |
| 10 | ) |
| 11 | |
| 12 | const VolumeTagKind = "volume" |
| 13 | |
| 14 | // Volumes may be bound to a machine, meaning that the volume cannot |
| 15 | // exist without that machine. We encode this in the tag to allow |
| 16 | var validVolume = regexp.MustCompile("^(" + MachineSnippet + "/)?" + NumberSnippet + "$") |
| 17 | |
| 18 | type VolumeTag struct { |
| 19 | id string |
| 20 | } |
| 21 | |
| 22 | func (t VolumeTag) String() string { return t.Kind() + "-" + t.id } |
| 23 | func (t VolumeTag) Kind() string { return VolumeTagKind } |
| 24 | func (t VolumeTag) Id() string { return volumeTagSuffixToId(t.id) } |
| 25 | |
| 26 | // NewVolumeTag returns the tag for the volume with the given ID. |
| 27 | // It will panic if the given volume ID is not valid. |
| 28 | func NewVolumeTag(id string) VolumeTag { |
| 29 | tag, ok := tagFromVolumeId(id) |
| 30 | if !ok { |
| 31 | panic(fmt.Sprintf("%q is not a valid volume ID", id)) |
| 32 | } |
| 33 | return tag |
| 34 | } |
| 35 | |
| 36 | // ParseVolumeTag parses a volume tag string. |
| 37 | func ParseVolumeTag(volumeTag string) (VolumeTag, error) { |
| 38 | tag, err := ParseTag(volumeTag) |
| 39 | if err != nil { |
| 40 | return VolumeTag{}, err |
| 41 | } |
| 42 | dt, ok := tag.(VolumeTag) |
| 43 | if !ok { |
| 44 | return VolumeTag{}, invalidTagError(volumeTag, VolumeTagKind) |
| 45 | } |
| 46 | return dt, nil |
| 47 | } |
| 48 | |
| 49 | // IsValidVolume returns whether id is a valid volume ID. |
| 50 | func IsValidVolume(id string) bool { |
| 51 | return validVolume.MatchString(id) |
| 52 | } |
| 53 | |
| 54 | // VolumeMachine returns the machine component of the volume |
| 55 | // tag, and a boolean indicating whether or not there is a |
| 56 | // machine component. |
| 57 | func VolumeMachine(tag VolumeTag) (MachineTag, bool) { |
| 58 | id := tag.Id() |
| 59 | pos := strings.LastIndex(id, "/") |
| 60 | if pos == -1 { |
| 61 | return MachineTag{}, false |
| 62 | } |
| 63 | return NewMachineTag(id[:pos]), true |
| 64 | } |
| 65 | |
| 66 | func tagFromVolumeId(id string) (VolumeTag, bool) { |
| 67 | if !IsValidVolume(id) { |
| 68 | return VolumeTag{}, false |
| 69 | } |
| 70 | id = strings.Replace(id, "/", "-", -1) |
| 71 | return VolumeTag{id}, true |
| 72 | } |
| 73 | |
| 74 | func volumeTagSuffixToId(s string) string { |
| 75 | return strings.Replace(s, "-", "/", -1) |
| 76 | } |