opts.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. package opts
  2. import (
  3. "fmt"
  4. "net"
  5. "path"
  6. "regexp"
  7. "strings"
  8. units "github.com/docker/go-units"
  9. )
  10. var (
  11. alphaRegexp = regexp.MustCompile(`[a-zA-Z]`)
  12. domainRegexp = regexp.MustCompile(`^(:?(:?[a-zA-Z0-9]|(:?[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9]))(:?\.(:?[a-zA-Z0-9]|(:?[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])))*)\.?\s*$`)
  13. )
  14. // ListOpts holds a list of values and a validation function.
  15. type ListOpts struct {
  16. values *[]string
  17. validator ValidatorFctType
  18. }
  19. // NewListOpts creates a new ListOpts with the specified validator.
  20. func NewListOpts(validator ValidatorFctType) ListOpts {
  21. var values []string
  22. return *NewListOptsRef(&values, validator)
  23. }
  24. // NewListOptsRef creates a new ListOpts with the specified values and validator.
  25. func NewListOptsRef(values *[]string, validator ValidatorFctType) *ListOpts {
  26. return &ListOpts{
  27. values: values,
  28. validator: validator,
  29. }
  30. }
  31. func (opts *ListOpts) String() string {
  32. if len(*opts.values) == 0 {
  33. return ""
  34. }
  35. return fmt.Sprintf("%v", *opts.values)
  36. }
  37. // Set validates if needed the input value and adds it to the
  38. // internal slice.
  39. func (opts *ListOpts) Set(value string) error {
  40. if opts.validator != nil {
  41. v, err := opts.validator(value)
  42. if err != nil {
  43. return err
  44. }
  45. value = v
  46. }
  47. (*opts.values) = append((*opts.values), value)
  48. return nil
  49. }
  50. // Delete removes the specified element from the slice.
  51. func (opts *ListOpts) Delete(key string) {
  52. for i, k := range *opts.values {
  53. if k == key {
  54. (*opts.values) = append((*opts.values)[:i], (*opts.values)[i+1:]...)
  55. return
  56. }
  57. }
  58. }
  59. // GetMap returns the content of values in a map in order to avoid
  60. // duplicates.
  61. func (opts *ListOpts) GetMap() map[string]struct{} {
  62. ret := make(map[string]struct{})
  63. for _, k := range *opts.values {
  64. ret[k] = struct{}{}
  65. }
  66. return ret
  67. }
  68. // GetAll returns the values of slice.
  69. func (opts *ListOpts) GetAll() []string {
  70. return (*opts.values)
  71. }
  72. // GetAllOrEmpty returns the values of the slice
  73. // or an empty slice when there are no values.
  74. func (opts *ListOpts) GetAllOrEmpty() []string {
  75. v := *opts.values
  76. if v == nil {
  77. return make([]string, 0)
  78. }
  79. return v
  80. }
  81. // Get checks the existence of the specified key.
  82. func (opts *ListOpts) Get(key string) bool {
  83. for _, k := range *opts.values {
  84. if k == key {
  85. return true
  86. }
  87. }
  88. return false
  89. }
  90. // Len returns the amount of element in the slice.
  91. func (opts *ListOpts) Len() int {
  92. return len((*opts.values))
  93. }
  94. // Type returns a string name for this Option type
  95. func (opts *ListOpts) Type() string {
  96. return "list"
  97. }
  98. // WithValidator returns the ListOpts with validator set.
  99. func (opts *ListOpts) WithValidator(validator ValidatorFctType) *ListOpts {
  100. opts.validator = validator
  101. return opts
  102. }
  103. // NamedOption is an interface that list and map options
  104. // with names implement.
  105. type NamedOption interface {
  106. Name() string
  107. }
  108. // NamedListOpts is a ListOpts with a configuration name.
  109. // This struct is useful to keep reference to the assigned
  110. // field name in the internal configuration struct.
  111. type NamedListOpts struct {
  112. name string
  113. ListOpts
  114. }
  115. var _ NamedOption = &NamedListOpts{}
  116. // NewNamedListOptsRef creates a reference to a new NamedListOpts struct.
  117. func NewNamedListOptsRef(name string, values *[]string, validator ValidatorFctType) *NamedListOpts {
  118. return &NamedListOpts{
  119. name: name,
  120. ListOpts: *NewListOptsRef(values, validator),
  121. }
  122. }
  123. // Name returns the name of the NamedListOpts in the configuration.
  124. func (o *NamedListOpts) Name() string {
  125. return o.name
  126. }
  127. // MapOpts holds a map of values and a validation function.
  128. type MapOpts struct {
  129. values map[string]string
  130. validator ValidatorFctType
  131. }
  132. // Set validates if needed the input value and add it to the
  133. // internal map, by splitting on '='.
  134. func (opts *MapOpts) Set(value string) error {
  135. if opts.validator != nil {
  136. v, err := opts.validator(value)
  137. if err != nil {
  138. return err
  139. }
  140. value = v
  141. }
  142. vals := strings.SplitN(value, "=", 2)
  143. if len(vals) == 1 {
  144. (opts.values)[vals[0]] = ""
  145. } else {
  146. (opts.values)[vals[0]] = vals[1]
  147. }
  148. return nil
  149. }
  150. // GetAll returns the values of MapOpts as a map.
  151. func (opts *MapOpts) GetAll() map[string]string {
  152. return opts.values
  153. }
  154. func (opts *MapOpts) String() string {
  155. return fmt.Sprintf("%v", opts.values)
  156. }
  157. // Type returns a string name for this Option type
  158. func (opts *MapOpts) Type() string {
  159. return "map"
  160. }
  161. // NewMapOpts creates a new MapOpts with the specified map of values and a validator.
  162. func NewMapOpts(values map[string]string, validator ValidatorFctType) *MapOpts {
  163. if values == nil {
  164. values = make(map[string]string)
  165. }
  166. return &MapOpts{
  167. values: values,
  168. validator: validator,
  169. }
  170. }
  171. // NamedMapOpts is a MapOpts struct with a configuration name.
  172. // This struct is useful to keep reference to the assigned
  173. // field name in the internal configuration struct.
  174. type NamedMapOpts struct {
  175. name string
  176. MapOpts
  177. }
  178. var _ NamedOption = &NamedMapOpts{}
  179. // NewNamedMapOpts creates a reference to a new NamedMapOpts struct.
  180. func NewNamedMapOpts(name string, values map[string]string, validator ValidatorFctType) *NamedMapOpts {
  181. return &NamedMapOpts{
  182. name: name,
  183. MapOpts: *NewMapOpts(values, validator),
  184. }
  185. }
  186. // Name returns the name of the NamedMapOpts in the configuration.
  187. func (o *NamedMapOpts) Name() string {
  188. return o.name
  189. }
  190. // ValidatorFctType defines a validator function that returns a validated string and/or an error.
  191. type ValidatorFctType func(val string) (string, error)
  192. // ValidatorFctListType defines a validator function that returns a validated list of string and/or an error
  193. type ValidatorFctListType func(val string) ([]string, error)
  194. // ValidateIPAddress validates an Ip address.
  195. func ValidateIPAddress(val string) (string, error) {
  196. var ip = net.ParseIP(strings.TrimSpace(val))
  197. if ip != nil {
  198. return ip.String(), nil
  199. }
  200. return "", fmt.Errorf("%s is not an ip address", val)
  201. }
  202. // ValidateDNSSearch validates domain for resolvconf search configuration.
  203. // A zero length domain is represented by a dot (.).
  204. func ValidateDNSSearch(val string) (string, error) {
  205. if val = strings.Trim(val, " "); val == "." {
  206. return val, nil
  207. }
  208. return validateDomain(val)
  209. }
  210. func validateDomain(val string) (string, error) {
  211. if alphaRegexp.FindString(val) == "" {
  212. return "", fmt.Errorf("%s is not a valid domain", val)
  213. }
  214. ns := domainRegexp.FindSubmatch([]byte(val))
  215. if len(ns) > 0 && len(ns[1]) < 255 {
  216. return string(ns[1]), nil
  217. }
  218. return "", fmt.Errorf("%s is not a valid domain", val)
  219. }
  220. // ValidateLabel validates that the specified string is a valid label, and returns it.
  221. // Labels are in the form on key=value.
  222. func ValidateLabel(val string) (string, error) {
  223. if strings.Count(val, "=") < 1 {
  224. return "", fmt.Errorf("bad attribute format: %s", val)
  225. }
  226. return val, nil
  227. }
  228. // ParseLink parses and validates the specified string as a link format (name:alias)
  229. func ParseLink(val string) (string, string, error) {
  230. if val == "" {
  231. return "", "", fmt.Errorf("empty string specified for links")
  232. }
  233. arr := strings.Split(val, ":")
  234. if len(arr) > 2 {
  235. return "", "", fmt.Errorf("bad format for links: %s", val)
  236. }
  237. if len(arr) == 1 {
  238. return val, val, nil
  239. }
  240. // This is kept because we can actually get a HostConfig with links
  241. // from an already created container and the format is not `foo:bar`
  242. // but `/foo:/c1/bar`
  243. if strings.HasPrefix(arr[0], "/") {
  244. _, alias := path.Split(arr[1])
  245. return arr[0][1:], alias, nil
  246. }
  247. return arr[0], arr[1], nil
  248. }
  249. // MemBytes is a type for human readable memory bytes (like 128M, 2g, etc)
  250. type MemBytes int64
  251. // String returns the string format of the human readable memory bytes
  252. func (m *MemBytes) String() string {
  253. // NOTE: In spf13/pflag/flag.go, "0" is considered as "zero value" while "0 B" is not.
  254. // We return "0" in case value is 0 here so that the default value is hidden.
  255. // (Sometimes "default 0 B" is actually misleading)
  256. if m.Value() != 0 {
  257. return units.BytesSize(float64(m.Value()))
  258. }
  259. return "0"
  260. }
  261. // Set sets the value of the MemBytes by passing a string
  262. func (m *MemBytes) Set(value string) error {
  263. val, err := units.RAMInBytes(value)
  264. *m = MemBytes(val)
  265. return err
  266. }
  267. // Type returns the type
  268. func (m *MemBytes) Type() string {
  269. return "bytes"
  270. }
  271. // Value returns the value in int64
  272. func (m *MemBytes) Value() int64 {
  273. return int64(*m)
  274. }
  275. // UnmarshalJSON is the customized unmarshaler for MemBytes
  276. func (m *MemBytes) UnmarshalJSON(s []byte) error {
  277. if len(s) <= 2 || s[0] != '"' || s[len(s)-1] != '"' {
  278. return fmt.Errorf("invalid size: %q", s)
  279. }
  280. val, err := units.RAMInBytes(string(s[1 : len(s)-1]))
  281. *m = MemBytes(val)
  282. return err
  283. }