opts.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. package opts // import "github.com/docker/docker/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. // NamedMapMapOpts is a MapMapOpts with a configuration name.
  128. // This struct is useful to keep reference to the assigned
  129. // field name in the internal configuration struct.
  130. type NamedMapMapOpts struct {
  131. name string
  132. MapMapOpts
  133. }
  134. // NewNamedMapMapOpts creates a reference to a new NamedMapOpts struct.
  135. func NewNamedMapMapOpts(name string, values map[string]map[string]string, validator ValidatorFctType) *NamedMapMapOpts {
  136. return &NamedMapMapOpts{
  137. name: name,
  138. MapMapOpts: *NewMapMapOpts(values, validator),
  139. }
  140. }
  141. // Name returns the name of the NamedListOpts in the configuration.
  142. func (o *NamedMapMapOpts) Name() string {
  143. return o.name
  144. }
  145. // MapMapOpts holds a map of maps of values and a validation function.
  146. type MapMapOpts struct {
  147. values map[string]map[string]string
  148. validator ValidatorFctType
  149. }
  150. // Set validates if needed the input value and add it to the
  151. // internal map, by splitting on '='.
  152. func (opts *MapMapOpts) Set(value string) error {
  153. if opts.validator != nil {
  154. v, err := opts.validator(value)
  155. if err != nil {
  156. return err
  157. }
  158. value = v
  159. }
  160. rk, rv, found := strings.Cut(value, "=")
  161. if !found {
  162. return fmt.Errorf("invalid value %q for map option, should be root-key=key=value", value)
  163. }
  164. k, v, found := strings.Cut(rv, "=")
  165. if !found {
  166. return fmt.Errorf("invalid value %q for map option, should be root-key=key=value", value)
  167. }
  168. if _, ok := opts.values[rk]; !ok {
  169. opts.values[rk] = make(map[string]string)
  170. }
  171. opts.values[rk][k] = v
  172. return nil
  173. }
  174. // GetAll returns the values of MapOpts as a map.
  175. func (opts *MapMapOpts) GetAll() map[string]map[string]string {
  176. return opts.values
  177. }
  178. func (opts *MapMapOpts) String() string {
  179. return fmt.Sprintf("%v", opts.values)
  180. }
  181. // Type returns a string name for this Option type
  182. func (opts *MapMapOpts) Type() string {
  183. return "mapmap"
  184. }
  185. // NewMapMapOpts creates a new MapMapOpts with the specified map of values and a validator.
  186. func NewMapMapOpts(values map[string]map[string]string, validator ValidatorFctType) *MapMapOpts {
  187. if values == nil {
  188. values = make(map[string]map[string]string)
  189. }
  190. return &MapMapOpts{
  191. values: values,
  192. validator: validator,
  193. }
  194. }
  195. // MapOpts holds a map of values and a validation function.
  196. type MapOpts struct {
  197. values map[string]string
  198. validator ValidatorFctType
  199. }
  200. // Set validates if needed the input value and add it to the
  201. // internal map, by splitting on '='.
  202. func (opts *MapOpts) Set(value string) error {
  203. if opts.validator != nil {
  204. v, err := opts.validator(value)
  205. if err != nil {
  206. return err
  207. }
  208. value = v
  209. }
  210. k, v, _ := strings.Cut(value, "=")
  211. (opts.values)[k] = v
  212. return nil
  213. }
  214. // GetAll returns the values of MapOpts as a map.
  215. func (opts *MapOpts) GetAll() map[string]string {
  216. return opts.values
  217. }
  218. func (opts *MapOpts) String() string {
  219. return fmt.Sprintf("%v", opts.values)
  220. }
  221. // Type returns a string name for this Option type
  222. func (opts *MapOpts) Type() string {
  223. return "map"
  224. }
  225. // NewMapOpts creates a new MapOpts with the specified map of values and a validator.
  226. func NewMapOpts(values map[string]string, validator ValidatorFctType) *MapOpts {
  227. if values == nil {
  228. values = make(map[string]string)
  229. }
  230. return &MapOpts{
  231. values: values,
  232. validator: validator,
  233. }
  234. }
  235. // NamedMapOpts is a MapOpts struct with a configuration name.
  236. // This struct is useful to keep reference to the assigned
  237. // field name in the internal configuration struct.
  238. type NamedMapOpts struct {
  239. name string
  240. MapOpts
  241. }
  242. var _ NamedOption = &NamedMapOpts{}
  243. // NewNamedMapOpts creates a reference to a new NamedMapOpts struct.
  244. func NewNamedMapOpts(name string, values map[string]string, validator ValidatorFctType) *NamedMapOpts {
  245. return &NamedMapOpts{
  246. name: name,
  247. MapOpts: *NewMapOpts(values, validator),
  248. }
  249. }
  250. // Name returns the name of the NamedMapOpts in the configuration.
  251. func (o *NamedMapOpts) Name() string {
  252. return o.name
  253. }
  254. // ValidatorFctType defines a validator function that returns a validated string and/or an error.
  255. type ValidatorFctType func(val string) (string, error)
  256. // ValidatorFctListType defines a validator function that returns a validated list of string and/or an error
  257. type ValidatorFctListType func(val string) ([]string, error)
  258. // ValidateIPAddress validates if the given value is a correctly formatted
  259. // IP address, and returns the value in normalized form. Leading and trailing
  260. // whitespace is allowed, but it does not allow IPv6 addresses surrounded by
  261. // square brackets ("[::1]").
  262. //
  263. // Refer to [net.ParseIP] for accepted formats.
  264. func ValidateIPAddress(val string) (string, error) {
  265. ip := net.ParseIP(strings.TrimSpace(val))
  266. if ip != nil {
  267. return ip.String(), nil
  268. }
  269. return "", fmt.Errorf("IP address is not correctly formatted: %s", val)
  270. }
  271. // ValidateDNSSearch validates domain for resolvconf search configuration.
  272. // A zero length domain is represented by a dot (.).
  273. func ValidateDNSSearch(val string) (string, error) {
  274. if val = strings.Trim(val, " "); val == "." {
  275. return val, nil
  276. }
  277. return validateDomain(val)
  278. }
  279. func validateDomain(val string) (string, error) {
  280. if alphaRegexp.FindString(val) == "" {
  281. return "", fmt.Errorf("%s is not a valid domain", val)
  282. }
  283. ns := domainRegexp.FindSubmatch([]byte(val))
  284. if len(ns) > 0 && len(ns[1]) < 255 {
  285. return string(ns[1]), nil
  286. }
  287. return "", fmt.Errorf("%s is not a valid domain", val)
  288. }
  289. // ValidateLabel validates that the specified string is a valid label,
  290. // it does not use the reserved namespaces com.docker.*, io.docker.*, org.dockerproject.*
  291. // and returns it.
  292. // Labels are in the form on key=value.
  293. func ValidateLabel(val string) (string, error) {
  294. if strings.Count(val, "=") < 1 {
  295. return "", fmt.Errorf("bad attribute format: %s", val)
  296. }
  297. lowered := strings.ToLower(val)
  298. if strings.HasPrefix(lowered, "com.docker.") || strings.HasPrefix(lowered, "io.docker.") ||
  299. strings.HasPrefix(lowered, "org.dockerproject.") {
  300. return "", fmt.Errorf(
  301. "label %s is not allowed: the namespaces com.docker.*, io.docker.*, and org.dockerproject.* are reserved for internal use",
  302. val)
  303. }
  304. return val, nil
  305. }
  306. // ValidateSingleGenericResource validates that a single entry in the
  307. // generic resource list is valid.
  308. // i.e 'GPU=UID1' is valid however 'GPU:UID1' or 'UID1' isn't
  309. func ValidateSingleGenericResource(val string) (string, error) {
  310. if strings.Count(val, "=") < 1 {
  311. return "", fmt.Errorf("invalid node-generic-resource format `%s` expected `name=value`", val)
  312. }
  313. return val, nil
  314. }
  315. // ParseLink parses and validates the specified string as a link format (name:alias)
  316. func ParseLink(val string) (string, string, error) {
  317. if val == "" {
  318. return "", "", fmt.Errorf("empty string specified for links")
  319. }
  320. arr := strings.Split(val, ":")
  321. if len(arr) > 2 {
  322. return "", "", fmt.Errorf("bad format for links: %s", val)
  323. }
  324. if len(arr) == 1 {
  325. return val, val, nil
  326. }
  327. // This is kept because we can actually get a HostConfig with links
  328. // from an already created container and the format is not `foo:bar`
  329. // but `/foo:/c1/bar`
  330. if strings.HasPrefix(arr[0], "/") {
  331. _, alias := path.Split(arr[1])
  332. return arr[0][1:], alias, nil
  333. }
  334. return arr[0], arr[1], nil
  335. }
  336. // MemBytes is a type for human readable memory bytes (like 128M, 2g, etc)
  337. type MemBytes int64
  338. // String returns the string format of the human readable memory bytes
  339. func (m *MemBytes) String() string {
  340. // NOTE: In spf13/pflag/flag.go, "0" is considered as "zero value" while "0 B" is not.
  341. // We return "0" in case value is 0 here so that the default value is hidden.
  342. // (Sometimes "default 0 B" is actually misleading)
  343. if m.Value() != 0 {
  344. return units.BytesSize(float64(m.Value()))
  345. }
  346. return "0"
  347. }
  348. // Set sets the value of the MemBytes by passing a string
  349. func (m *MemBytes) Set(value string) error {
  350. val, err := units.RAMInBytes(value)
  351. *m = MemBytes(val)
  352. return err
  353. }
  354. // Type returns the type
  355. func (m *MemBytes) Type() string {
  356. return "bytes"
  357. }
  358. // Value returns the value in int64
  359. func (m *MemBytes) Value() int64 {
  360. return int64(*m)
  361. }
  362. // UnmarshalJSON is the customized unmarshaler for MemBytes
  363. func (m *MemBytes) UnmarshalJSON(s []byte) error {
  364. if len(s) <= 2 || s[0] != '"' || s[len(s)-1] != '"' {
  365. return fmt.Errorf("invalid size: %q", s)
  366. }
  367. val, err := units.RAMInBytes(string(s[1 : len(s)-1]))
  368. *m = MemBytes(val)
  369. return err
  370. }