blob: 2c1fd1bdbc2d978116f60a672819a35ea3e64a14 [file] [log] [blame]
David K. Bainbridge528b3182017-01-23 08:51:59 -08001// Copyright 2014 Canonical Ltd.
2// Licensed under the LGPLv3, see LICENCE file for details.
3
4package names
5
6import (
7 "fmt"
8 "regexp"
9 "strings"
10)
11
12const 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
16var validVolume = regexp.MustCompile("^(" + MachineSnippet + "/)?" + NumberSnippet + "$")
17
18type VolumeTag struct {
19 id string
20}
21
22func (t VolumeTag) String() string { return t.Kind() + "-" + t.id }
23func (t VolumeTag) Kind() string { return VolumeTagKind }
24func (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.
28func 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.
37func 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.
50func 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.
57func 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
66func 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
74func volumeTagSuffixToId(s string) string {
75 return strings.Replace(s, "-", "/", -1)
76}