opts.go 8.0 KB

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