opts.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. package opts
  2. import (
  3. "fmt"
  4. "math/big"
  5. "net"
  6. "path"
  7. "regexp"
  8. "strings"
  9. "github.com/docker/docker/api/types/filters"
  10. units "github.com/docker/go-units"
  11. )
  12. var (
  13. alphaRegexp = regexp.MustCompile(`[a-zA-Z]`)
  14. 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*$`)
  15. )
  16. // ListOpts holds a list of values and a validation function.
  17. type ListOpts struct {
  18. values *[]string
  19. validator ValidatorFctType
  20. }
  21. // NewListOpts creates a new ListOpts with the specified validator.
  22. func NewListOpts(validator ValidatorFctType) ListOpts {
  23. var values []string
  24. return *NewListOptsRef(&values, validator)
  25. }
  26. // NewListOptsRef creates a new ListOpts with the specified values and validator.
  27. func NewListOptsRef(values *[]string, validator ValidatorFctType) *ListOpts {
  28. return &ListOpts{
  29. values: values,
  30. validator: validator,
  31. }
  32. }
  33. func (opts *ListOpts) String() string {
  34. return fmt.Sprintf("%v", []string((*opts.values)))
  35. }
  36. // Set validates if needed the input value and adds it to the
  37. // internal slice.
  38. func (opts *ListOpts) Set(value string) error {
  39. if opts.validator != nil {
  40. v, err := opts.validator(value)
  41. if err != nil {
  42. return err
  43. }
  44. value = v
  45. }
  46. (*opts.values) = append((*opts.values), value)
  47. return nil
  48. }
  49. // Delete removes the specified element from the slice.
  50. func (opts *ListOpts) Delete(key string) {
  51. for i, k := range *opts.values {
  52. if k == key {
  53. (*opts.values) = append((*opts.values)[:i], (*opts.values)[i+1:]...)
  54. return
  55. }
  56. }
  57. }
  58. // GetMap returns the content of values in a map in order to avoid
  59. // duplicates.
  60. func (opts *ListOpts) GetMap() map[string]struct{} {
  61. ret := make(map[string]struct{})
  62. for _, k := range *opts.values {
  63. ret[k] = struct{}{}
  64. }
  65. return ret
  66. }
  67. // GetAll returns the values of slice.
  68. func (opts *ListOpts) GetAll() []string {
  69. return (*opts.values)
  70. }
  71. // GetAllOrEmpty returns the values of the slice
  72. // or an empty slice when there are no values.
  73. func (opts *ListOpts) GetAllOrEmpty() []string {
  74. v := *opts.values
  75. if v == nil {
  76. return make([]string, 0)
  77. }
  78. return v
  79. }
  80. // Get checks the existence of the specified key.
  81. func (opts *ListOpts) Get(key string) bool {
  82. for _, k := range *opts.values {
  83. if k == key {
  84. return true
  85. }
  86. }
  87. return false
  88. }
  89. // Len returns the amount of element in the slice.
  90. func (opts *ListOpts) Len() int {
  91. return len((*opts.values))
  92. }
  93. // Type returns a string name for this Option type
  94. func (opts *ListOpts) Type() string {
  95. return "list"
  96. }
  97. // WithValidator returns the ListOpts with validator set.
  98. func (opts *ListOpts) WithValidator(validator ValidatorFctType) *ListOpts {
  99. opts.validator = validator
  100. return opts
  101. }
  102. // NamedOption is an interface that list and map options
  103. // with names implement.
  104. type NamedOption interface {
  105. Name() string
  106. }
  107. // NamedListOpts is a ListOpts with a configuration name.
  108. // This struct is useful to keep reference to the assigned
  109. // field name in the internal configuration struct.
  110. type NamedListOpts struct {
  111. name string
  112. ListOpts
  113. }
  114. var _ NamedOption = &NamedListOpts{}
  115. // NewNamedListOptsRef creates a reference to a new NamedListOpts struct.
  116. func NewNamedListOptsRef(name string, values *[]string, validator ValidatorFctType) *NamedListOpts {
  117. return &NamedListOpts{
  118. name: name,
  119. ListOpts: *NewListOptsRef(values, validator),
  120. }
  121. }
  122. // Name returns the name of the NamedListOpts in the configuration.
  123. func (o *NamedListOpts) Name() string {
  124. return o.name
  125. }
  126. // MapOpts holds a map of values and a validation function.
  127. type MapOpts struct {
  128. values map[string]string
  129. validator ValidatorFctType
  130. }
  131. // Set validates if needed the input value and add it to the
  132. // internal map, by splitting on '='.
  133. func (opts *MapOpts) Set(value string) error {
  134. if opts.validator != nil {
  135. v, err := opts.validator(value)
  136. if err != nil {
  137. return err
  138. }
  139. value = v
  140. }
  141. vals := strings.SplitN(value, "=", 2)
  142. if len(vals) == 1 {
  143. (opts.values)[vals[0]] = ""
  144. } else {
  145. (opts.values)[vals[0]] = vals[1]
  146. }
  147. return nil
  148. }
  149. // GetAll returns the values of MapOpts as a map.
  150. func (opts *MapOpts) GetAll() map[string]string {
  151. return opts.values
  152. }
  153. func (opts *MapOpts) String() string {
  154. return fmt.Sprintf("%v", map[string]string((opts.values)))
  155. }
  156. // Type returns a string name for this Option type
  157. func (opts *MapOpts) Type() string {
  158. return "map"
  159. }
  160. // NewMapOpts creates a new MapOpts with the specified map of values and a validator.
  161. func NewMapOpts(values map[string]string, validator ValidatorFctType) *MapOpts {
  162. if values == nil {
  163. values = make(map[string]string)
  164. }
  165. return &MapOpts{
  166. values: values,
  167. validator: validator,
  168. }
  169. }
  170. // NamedMapOpts is a MapOpts struct with a configuration name.
  171. // This struct is useful to keep reference to the assigned
  172. // field name in the internal configuration struct.
  173. type NamedMapOpts struct {
  174. name string
  175. MapOpts
  176. }
  177. var _ NamedOption = &NamedMapOpts{}
  178. // NewNamedMapOpts creates a reference to a new NamedMapOpts struct.
  179. func NewNamedMapOpts(name string, values map[string]string, validator ValidatorFctType) *NamedMapOpts {
  180. return &NamedMapOpts{
  181. name: name,
  182. MapOpts: *NewMapOpts(values, validator),
  183. }
  184. }
  185. // Name returns the name of the NamedMapOpts in the configuration.
  186. func (o *NamedMapOpts) Name() string {
  187. return o.name
  188. }
  189. // ValidatorFctType defines a validator function that returns a validated string and/or an error.
  190. type ValidatorFctType func(val string) (string, error)
  191. // ValidatorFctListType defines a validator function that returns a validated list of string and/or an error
  192. type ValidatorFctListType func(val string) ([]string, error)
  193. // ValidateIPAddress validates an Ip address.
  194. func ValidateIPAddress(val string) (string, error) {
  195. var ip = net.ParseIP(strings.TrimSpace(val))
  196. if ip != nil {
  197. return ip.String(), nil
  198. }
  199. return "", fmt.Errorf("%s is not an ip address", val)
  200. }
  201. // ValidateMACAddress validates a MAC address.
  202. func ValidateMACAddress(val string) (string, error) {
  203. _, err := net.ParseMAC(strings.TrimSpace(val))
  204. if err != nil {
  205. return "", err
  206. }
  207. return val, nil
  208. }
  209. // ValidateDNSSearch validates domain for resolvconf search configuration.
  210. // A zero length domain is represented by a dot (.).
  211. func ValidateDNSSearch(val string) (string, error) {
  212. if val = strings.Trim(val, " "); val == "." {
  213. return val, nil
  214. }
  215. return validateDomain(val)
  216. }
  217. func validateDomain(val string) (string, error) {
  218. if alphaRegexp.FindString(val) == "" {
  219. return "", fmt.Errorf("%s is not a valid domain", val)
  220. }
  221. ns := domainRegexp.FindSubmatch([]byte(val))
  222. if len(ns) > 0 && len(ns[1]) < 255 {
  223. return string(ns[1]), nil
  224. }
  225. return "", fmt.Errorf("%s is not a valid domain", val)
  226. }
  227. // ValidateLabel validates that the specified string is a valid label, and returns it.
  228. // Labels are in the form on key=value.
  229. func ValidateLabel(val string) (string, error) {
  230. if strings.Count(val, "=") < 1 {
  231. return "", fmt.Errorf("bad attribute format: %s", val)
  232. }
  233. return val, nil
  234. }
  235. // ValidateSysctl validates a sysctl and returns it.
  236. func ValidateSysctl(val string) (string, error) {
  237. validSysctlMap := map[string]bool{
  238. "kernel.msgmax": true,
  239. "kernel.msgmnb": true,
  240. "kernel.msgmni": true,
  241. "kernel.sem": true,
  242. "kernel.shmall": true,
  243. "kernel.shmmax": true,
  244. "kernel.shmmni": true,
  245. "kernel.shm_rmid_forced": true,
  246. }
  247. validSysctlPrefixes := []string{
  248. "net.",
  249. "fs.mqueue.",
  250. }
  251. arr := strings.Split(val, "=")
  252. if len(arr) < 2 {
  253. return "", fmt.Errorf("sysctl '%s' is not whitelisted", val)
  254. }
  255. if validSysctlMap[arr[0]] {
  256. return val, nil
  257. }
  258. for _, vp := range validSysctlPrefixes {
  259. if strings.HasPrefix(arr[0], vp) {
  260. return val, nil
  261. }
  262. }
  263. return "", fmt.Errorf("sysctl '%s' is not whitelisted", val)
  264. }
  265. // FilterOpt is a flag type for validating filters
  266. type FilterOpt struct {
  267. filter filters.Args
  268. }
  269. // NewFilterOpt returns a new FilterOpt
  270. func NewFilterOpt() FilterOpt {
  271. return FilterOpt{filter: filters.NewArgs()}
  272. }
  273. func (o *FilterOpt) String() string {
  274. repr, err := filters.ToParam(o.filter)
  275. if err != nil {
  276. return "invalid filters"
  277. }
  278. return repr
  279. }
  280. // Set sets the value of the opt by parsing the command line value
  281. func (o *FilterOpt) Set(value string) error {
  282. var err error
  283. o.filter, err = filters.ParseFlag(value, o.filter)
  284. return err
  285. }
  286. // Type returns the option type
  287. func (o *FilterOpt) Type() string {
  288. return "filter"
  289. }
  290. // Value returns the value of this option
  291. func (o *FilterOpt) Value() filters.Args {
  292. return o.filter
  293. }
  294. // NanoCPUs is a type for fixed point fractional number.
  295. type NanoCPUs int64
  296. // String returns the string format of the number
  297. func (c *NanoCPUs) String() string {
  298. return big.NewRat(c.Value(), 1e9).FloatString(3)
  299. }
  300. // Set sets the value of the NanoCPU by passing a string
  301. func (c *NanoCPUs) Set(value string) error {
  302. cpus, err := ParseCPUs(value)
  303. *c = NanoCPUs(cpus)
  304. return err
  305. }
  306. // Type returns the type
  307. func (c *NanoCPUs) Type() string {
  308. return "decimal"
  309. }
  310. // Value returns the value in int64
  311. func (c *NanoCPUs) Value() int64 {
  312. return int64(*c)
  313. }
  314. // ParseCPUs takes a string ratio and returns an integer value of nano cpus
  315. func ParseCPUs(value string) (int64, error) {
  316. cpu, ok := new(big.Rat).SetString(value)
  317. if !ok {
  318. return 0, fmt.Errorf("failed to parse %v as a rational number", value)
  319. }
  320. nano := cpu.Mul(cpu, big.NewRat(1e9, 1))
  321. if !nano.IsInt() {
  322. return 0, fmt.Errorf("value is too precise")
  323. }
  324. return nano.Num().Int64(), nil
  325. }
  326. // ParseLink parses and validates the specified string as a link format (name:alias)
  327. func ParseLink(val string) (string, string, error) {
  328. if val == "" {
  329. return "", "", fmt.Errorf("empty string specified for links")
  330. }
  331. arr := strings.Split(val, ":")
  332. if len(arr) > 2 {
  333. return "", "", fmt.Errorf("bad format for links: %s", val)
  334. }
  335. if len(arr) == 1 {
  336. return val, val, nil
  337. }
  338. // This is kept because we can actually get a HostConfig with links
  339. // from an already created container and the format is not `foo:bar`
  340. // but `/foo:/c1/bar`
  341. if strings.HasPrefix(arr[0], "/") {
  342. _, alias := path.Split(arr[1])
  343. return arr[0][1:], alias, nil
  344. }
  345. return arr[0], arr[1], nil
  346. }
  347. // ValidateLink validates that the specified string has a valid link format (containerName:alias).
  348. func ValidateLink(val string) (string, error) {
  349. _, _, err := ParseLink(val)
  350. return val, err
  351. }
  352. // MemBytes is a type for human readable memory bytes (like 128M, 2g, etc)
  353. type MemBytes int64
  354. // String returns the string format of the human readable memory bytes
  355. func (m *MemBytes) String() string {
  356. // NOTE: In spf13/pflag/flag.go, "0" is considered as "zero value" while "0 B" is not.
  357. // We return "0" in case value is 0 here so that the default value is hidden.
  358. // (Sometimes "default 0 B" is actually misleading)
  359. if m.Value() != 0 {
  360. return units.BytesSize(float64(m.Value()))
  361. }
  362. return "0"
  363. }
  364. // Set sets the value of the MemBytes by passing a string
  365. func (m *MemBytes) Set(value string) error {
  366. val, err := units.RAMInBytes(value)
  367. *m = MemBytes(val)
  368. return err
  369. }
  370. // Type returns the type
  371. func (m *MemBytes) Type() string {
  372. return "bytes"
  373. }
  374. // Value returns the value in int64
  375. func (m *MemBytes) Value() int64 {
  376. return int64(*m)
  377. }
  378. // UnmarshalJSON is the customized unmarshaler for MemBytes
  379. func (m *MemBytes) UnmarshalJSON(s []byte) error {
  380. if len(s) <= 2 || s[0] != '"' || s[len(s)-1] != '"' {
  381. return fmt.Errorf("invalid size: %q", s)
  382. }
  383. val, err := units.RAMInBytes(string(s[1 : len(s)-1]))
  384. *m = MemBytes(val)
  385. return err
  386. }