opts.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. package swarm
  2. import (
  3. "encoding/csv"
  4. "errors"
  5. "fmt"
  6. "strings"
  7. "time"
  8. "github.com/docker/docker/opts"
  9. "github.com/docker/engine-api/types/swarm"
  10. "github.com/spf13/pflag"
  11. )
  12. const (
  13. defaultListenAddr = "0.0.0.0:2377"
  14. worker = "WORKER"
  15. manager = "MANAGER"
  16. none = "NONE"
  17. flagAutoAccept = "auto-accept"
  18. flagCertExpiry = "cert-expiry"
  19. flagDispatcherHeartbeat = "dispatcher-heartbeat"
  20. flagListenAddr = "listen-addr"
  21. flagSecret = "secret"
  22. flagTaskHistoryLimit = "task-history-limit"
  23. flagExternalCA = "external-ca"
  24. )
  25. var (
  26. defaultPolicies = []swarm.Policy{
  27. {Role: worker, Autoaccept: true},
  28. {Role: manager, Autoaccept: false},
  29. }
  30. )
  31. type swarmOptions struct {
  32. autoAccept AutoAcceptOption
  33. secret string
  34. taskHistoryLimit int64
  35. dispatcherHeartbeat time.Duration
  36. nodeCertExpiry time.Duration
  37. externalCA ExternalCAOption
  38. }
  39. // NodeAddrOption is a pflag.Value for listen and remote addresses
  40. type NodeAddrOption struct {
  41. addr string
  42. }
  43. // String prints the representation of this flag
  44. func (a *NodeAddrOption) String() string {
  45. return a.Value()
  46. }
  47. // Set the value for this flag
  48. func (a *NodeAddrOption) Set(value string) error {
  49. addr, err := opts.ParseTCPAddr(value, a.addr)
  50. if err != nil {
  51. return err
  52. }
  53. a.addr = addr
  54. return nil
  55. }
  56. // Type returns the type of this flag
  57. func (a *NodeAddrOption) Type() string {
  58. return "node-addr"
  59. }
  60. // Value returns the value of this option as addr:port
  61. func (a *NodeAddrOption) Value() string {
  62. return strings.TrimPrefix(a.addr, "tcp://")
  63. }
  64. // NewNodeAddrOption returns a new node address option
  65. func NewNodeAddrOption(addr string) NodeAddrOption {
  66. return NodeAddrOption{addr}
  67. }
  68. // NewListenAddrOption returns a NodeAddrOption with default values
  69. func NewListenAddrOption() NodeAddrOption {
  70. return NewNodeAddrOption(defaultListenAddr)
  71. }
  72. // AutoAcceptOption is a value type for auto-accept policy
  73. type AutoAcceptOption struct {
  74. values map[string]struct{}
  75. }
  76. // String prints a string representation of this option
  77. func (o *AutoAcceptOption) String() string {
  78. keys := []string{}
  79. for key := range o.values {
  80. keys = append(keys, fmt.Sprintf("%s=true", strings.ToLower(key)))
  81. }
  82. return strings.Join(keys, ", ")
  83. }
  84. // Set sets a new value on this option
  85. func (o *AutoAcceptOption) Set(acceptValues string) error {
  86. for _, value := range strings.Split(acceptValues, ",") {
  87. value = strings.ToUpper(value)
  88. switch value {
  89. case none, worker, manager:
  90. o.values[value] = struct{}{}
  91. default:
  92. return fmt.Errorf("must be one / combination of %s, %s; or NONE", worker, manager)
  93. }
  94. }
  95. // NONE must stand alone, so if any non-NONE setting exist with it, error with conflict
  96. if o.isPresent(none) && len(o.values) > 1 {
  97. return fmt.Errorf("value NONE cannot be specified alongside other node types")
  98. }
  99. return nil
  100. }
  101. // Type returns the type of this option
  102. func (o *AutoAcceptOption) Type() string {
  103. return "auto-accept"
  104. }
  105. // Policies returns a representation of this option for the api
  106. func (o *AutoAcceptOption) Policies(secret *string) []swarm.Policy {
  107. policies := []swarm.Policy{}
  108. for _, p := range defaultPolicies {
  109. if len(o.values) != 0 {
  110. if _, ok := o.values[string(p.Role)]; ok {
  111. p.Autoaccept = true
  112. } else {
  113. p.Autoaccept = false
  114. }
  115. }
  116. p.Secret = secret
  117. policies = append(policies, p)
  118. }
  119. return policies
  120. }
  121. // isPresent returns whether the key exists in the set or not
  122. func (o *AutoAcceptOption) isPresent(key string) bool {
  123. _, c := o.values[key]
  124. return c
  125. }
  126. // NewAutoAcceptOption returns a new auto-accept option
  127. func NewAutoAcceptOption() AutoAcceptOption {
  128. return AutoAcceptOption{values: make(map[string]struct{})}
  129. }
  130. // ExternalCAOption is a Value type for parsing external CA specifications.
  131. type ExternalCAOption struct {
  132. values []*swarm.ExternalCA
  133. }
  134. // Set parses an external CA option.
  135. func (m *ExternalCAOption) Set(value string) error {
  136. parsed, err := parseExternalCA(value)
  137. if err != nil {
  138. return err
  139. }
  140. m.values = append(m.values, parsed)
  141. return nil
  142. }
  143. // Type returns the type of this option.
  144. func (m *ExternalCAOption) Type() string {
  145. return "external-ca"
  146. }
  147. // String returns a string repr of this option.
  148. func (m *ExternalCAOption) String() string {
  149. externalCAs := []string{}
  150. for _, externalCA := range m.values {
  151. repr := fmt.Sprintf("%s: %s", externalCA.Protocol, externalCA.URL)
  152. externalCAs = append(externalCAs, repr)
  153. }
  154. return strings.Join(externalCAs, ", ")
  155. }
  156. // Value returns the external CAs
  157. func (m *ExternalCAOption) Value() []*swarm.ExternalCA {
  158. return m.values
  159. }
  160. // parseExternalCA parses an external CA specification from the command line,
  161. // such as protocol=cfssl,url=https://example.com.
  162. func parseExternalCA(caSpec string) (*swarm.ExternalCA, error) {
  163. csvReader := csv.NewReader(strings.NewReader(caSpec))
  164. fields, err := csvReader.Read()
  165. if err != nil {
  166. return nil, err
  167. }
  168. externalCA := swarm.ExternalCA{
  169. Options: make(map[string]string),
  170. }
  171. var (
  172. hasProtocol bool
  173. hasURL bool
  174. )
  175. for _, field := range fields {
  176. parts := strings.SplitN(field, "=", 2)
  177. if len(parts) != 2 {
  178. return nil, fmt.Errorf("invalid field '%s' must be a key=value pair", field)
  179. }
  180. key, value := parts[0], parts[1]
  181. switch strings.ToLower(key) {
  182. case "protocol":
  183. hasProtocol = true
  184. if strings.ToLower(value) == string(swarm.ExternalCAProtocolCFSSL) {
  185. externalCA.Protocol = swarm.ExternalCAProtocolCFSSL
  186. } else {
  187. return nil, fmt.Errorf("unrecognized external CA protocol %s", value)
  188. }
  189. case "url":
  190. hasURL = true
  191. externalCA.URL = value
  192. default:
  193. externalCA.Options[key] = value
  194. }
  195. }
  196. if !hasProtocol {
  197. return nil, errors.New("the external-ca option needs a protocol= parameter")
  198. }
  199. if !hasURL {
  200. return nil, errors.New("the external-ca option needs a url= parameter")
  201. }
  202. return &externalCA, nil
  203. }
  204. func addSwarmFlags(flags *pflag.FlagSet, opts *swarmOptions) {
  205. flags.Var(&opts.autoAccept, flagAutoAccept, "Auto acceptance policy (worker, manager or none)")
  206. flags.StringVar(&opts.secret, flagSecret, "", "Set secret value needed to join a cluster")
  207. flags.Int64Var(&opts.taskHistoryLimit, flagTaskHistoryLimit, 10, "Task history retention limit")
  208. flags.DurationVar(&opts.dispatcherHeartbeat, flagDispatcherHeartbeat, time.Duration(5*time.Second), "Dispatcher heartbeat period")
  209. flags.DurationVar(&opts.nodeCertExpiry, flagCertExpiry, time.Duration(90*24*time.Hour), "Validity period for node certificates")
  210. flags.Var(&opts.externalCA, flagExternalCA, "Specifications of one or more certificate signing endpoints")
  211. }
  212. func (opts *swarmOptions) ToSpec() swarm.Spec {
  213. spec := swarm.Spec{}
  214. if opts.secret != "" {
  215. spec.AcceptancePolicy.Policies = opts.autoAccept.Policies(&opts.secret)
  216. } else {
  217. spec.AcceptancePolicy.Policies = opts.autoAccept.Policies(nil)
  218. }
  219. spec.Orchestration.TaskHistoryRetentionLimit = opts.taskHistoryLimit
  220. spec.Dispatcher.HeartbeatPeriod = uint64(opts.dispatcherHeartbeat.Nanoseconds())
  221. spec.CAConfig.NodeCertExpiry = opts.nodeCertExpiry
  222. spec.CAConfig.ExternalCAs = opts.externalCA.Value()
  223. return spec
  224. }