config.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. // Copyright 2016 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package embed
  15. import (
  16. "fmt"
  17. "io/ioutil"
  18. "net"
  19. "net/http"
  20. "net/url"
  21. "path/filepath"
  22. "strings"
  23. "time"
  24. "github.com/coreos/etcd/etcdserver"
  25. "github.com/coreos/etcd/pkg/cors"
  26. "github.com/coreos/etcd/pkg/netutil"
  27. "github.com/coreos/etcd/pkg/srv"
  28. "github.com/coreos/etcd/pkg/tlsutil"
  29. "github.com/coreos/etcd/pkg/transport"
  30. "github.com/coreos/etcd/pkg/types"
  31. "github.com/ghodss/yaml"
  32. "google.golang.org/grpc"
  33. )
  34. const (
  35. ClusterStateFlagNew = "new"
  36. ClusterStateFlagExisting = "existing"
  37. DefaultName = "default"
  38. DefaultMaxSnapshots = 5
  39. DefaultMaxWALs = 5
  40. DefaultMaxRequestBytes = 1.5 * 1024 * 1024
  41. DefaultGRPCKeepAliveMinTime = 5 * time.Second
  42. DefaultGRPCKeepAliveInterval = 2 * time.Hour
  43. DefaultGRPCKeepAliveTimeout = 20 * time.Second
  44. DefaultListenPeerURLs = "http://localhost:2380"
  45. DefaultListenClientURLs = "http://localhost:2379"
  46. // maxElectionMs specifies the maximum value of election timeout.
  47. // More details are listed in ../Documentation/tuning.md#time-parameters.
  48. maxElectionMs = 50000
  49. )
  50. var (
  51. ErrConflictBootstrapFlags = fmt.Errorf("multiple discovery or bootstrap flags are set. " +
  52. "Choose one of \"initial-cluster\", \"discovery\" or \"discovery-srv\"")
  53. ErrUnsetAdvertiseClientURLsFlag = fmt.Errorf("--advertise-client-urls is required when --listen-client-urls is set explicitly")
  54. DefaultInitialAdvertisePeerURLs = "http://localhost:2380"
  55. DefaultAdvertiseClientURLs = "http://localhost:2379"
  56. defaultHostname string
  57. defaultHostStatus error
  58. )
  59. func init() {
  60. defaultHostname, defaultHostStatus = netutil.GetDefaultHost()
  61. }
  62. // Config holds the arguments for configuring an etcd server.
  63. type Config struct {
  64. // member
  65. CorsInfo *cors.CORSInfo
  66. LPUrls, LCUrls []url.URL
  67. Dir string `json:"data-dir"`
  68. WalDir string `json:"wal-dir"`
  69. MaxSnapFiles uint `json:"max-snapshots"`
  70. MaxWalFiles uint `json:"max-wals"`
  71. Name string `json:"name"`
  72. SnapCount uint64 `json:"snapshot-count"`
  73. AutoCompactionRetention int `json:"auto-compaction-retention"`
  74. // TickMs is the number of milliseconds between heartbeat ticks.
  75. // TODO: decouple tickMs and heartbeat tick (current heartbeat tick = 1).
  76. // make ticks a cluster wide configuration.
  77. TickMs uint `json:"heartbeat-interval"`
  78. ElectionMs uint `json:"election-timeout"`
  79. // InitialElectionTickAdvance is true, then local member fast-forwards
  80. // election ticks to speed up "initial" leader election trigger. This
  81. // benefits the case of larger election ticks. For instance, cross
  82. // datacenter deployment may require longer election timeout of 10-second.
  83. // If true, local node does not need wait up to 10-second. Instead,
  84. // forwards its election ticks to 8-second, and have only 2-second left
  85. // before leader election.
  86. //
  87. // Major assumptions are that:
  88. // - cluster has no active leader thus advancing ticks enables faster
  89. // leader election, or
  90. // - cluster already has an established leader, and rejoining follower
  91. // is likely to receive heartbeats from the leader after tick advance
  92. // and before election timeout.
  93. //
  94. // However, when network from leader to rejoining follower is congested,
  95. // and the follower does not receive leader heartbeat within left election
  96. // ticks, disruptive election has to happen thus affecting cluster
  97. // availabilities.
  98. //
  99. // Disabling this would slow down initial bootstrap process for cross
  100. // datacenter deployments. Make your own tradeoffs by configuring
  101. // --initial-election-tick-advance at the cost of slow initial bootstrap.
  102. //
  103. // If single-node, it advances ticks regardless.
  104. //
  105. // See https://github.com/coreos/etcd/issues/9333 for more detail.
  106. InitialElectionTickAdvance bool `json:"initial-election-tick-advance"`
  107. QuotaBackendBytes int64 `json:"quota-backend-bytes"`
  108. MaxRequestBytes uint `json:"max-request-bytes"`
  109. // gRPC server options
  110. // GRPCKeepAliveMinTime is the minimum interval that a client should
  111. // wait before pinging server. When client pings "too fast", server
  112. // sends goaway and closes the connection (errors: too_many_pings,
  113. // http2.ErrCodeEnhanceYourCalm). When too slow, nothing happens.
  114. // Server expects client pings only when there is any active streams
  115. // (PermitWithoutStream is set false).
  116. GRPCKeepAliveMinTime time.Duration `json:"grpc-keepalive-min-time"`
  117. // GRPCKeepAliveInterval is the frequency of server-to-client ping
  118. // to check if a connection is alive. Close a non-responsive connection
  119. // after an additional duration of Timeout. 0 to disable.
  120. GRPCKeepAliveInterval time.Duration `json:"grpc-keepalive-interval"`
  121. // GRPCKeepAliveTimeout is the additional duration of wait
  122. // before closing a non-responsive connection. 0 to disable.
  123. GRPCKeepAliveTimeout time.Duration `json:"grpc-keepalive-timeout"`
  124. // clustering
  125. APUrls, ACUrls []url.URL
  126. ClusterState string `json:"initial-cluster-state"`
  127. DNSCluster string `json:"discovery-srv"`
  128. Dproxy string `json:"discovery-proxy"`
  129. Durl string `json:"discovery"`
  130. InitialCluster string `json:"initial-cluster"`
  131. InitialClusterToken string `json:"initial-cluster-token"`
  132. StrictReconfigCheck bool `json:"strict-reconfig-check"`
  133. EnableV2 bool `json:"enable-v2"`
  134. // security
  135. ClientTLSInfo transport.TLSInfo
  136. ClientAutoTLS bool
  137. PeerTLSInfo transport.TLSInfo
  138. PeerAutoTLS bool
  139. // CipherSuites is a list of supported TLS cipher suites between
  140. // client/server and peers. If empty, Go auto-populates the list.
  141. // Note that cipher suites are prioritized in the given order.
  142. CipherSuites []string `json:"cipher-suites"`
  143. // debug
  144. Debug bool `json:"debug"`
  145. LogPkgLevels string `json:"log-package-levels"`
  146. EnablePprof bool `json:"enable-pprof"`
  147. Metrics string `json:"metrics"`
  148. // ForceNewCluster starts a new cluster even if previously started; unsafe.
  149. ForceNewCluster bool `json:"force-new-cluster"`
  150. // UserHandlers is for registering users handlers and only used for
  151. // embedding etcd into other applications.
  152. // The map key is the route path for the handler, and
  153. // you must ensure it can't be conflicted with etcd's.
  154. UserHandlers map[string]http.Handler `json:"-"`
  155. // ServiceRegister is for registering users' gRPC services. A simple usage example:
  156. // cfg := embed.NewConfig()
  157. // cfg.ServerRegister = func(s *grpc.Server) {
  158. // pb.RegisterFooServer(s, &fooServer{})
  159. // pb.RegisterBarServer(s, &barServer{})
  160. // }
  161. // embed.StartEtcd(cfg)
  162. ServiceRegister func(*grpc.Server) `json:"-"`
  163. // auth
  164. AuthToken string `json:"auth-token"`
  165. }
  166. // configYAML holds the config suitable for yaml parsing
  167. type configYAML struct {
  168. Config
  169. configJSON
  170. }
  171. // configJSON has file options that are translated into Config options
  172. type configJSON struct {
  173. LPUrlsJSON string `json:"listen-peer-urls"`
  174. LCUrlsJSON string `json:"listen-client-urls"`
  175. CorsJSON string `json:"cors"`
  176. APUrlsJSON string `json:"initial-advertise-peer-urls"`
  177. ACUrlsJSON string `json:"advertise-client-urls"`
  178. ClientSecurityJSON securityConfig `json:"client-transport-security"`
  179. PeerSecurityJSON securityConfig `json:"peer-transport-security"`
  180. }
  181. type securityConfig struct {
  182. CAFile string `json:"ca-file"`
  183. CertFile string `json:"cert-file"`
  184. KeyFile string `json:"key-file"`
  185. CertAuth bool `json:"client-cert-auth"`
  186. TrustedCAFile string `json:"trusted-ca-file"`
  187. AutoTLS bool `json:"auto-tls"`
  188. }
  189. // NewConfig creates a new Config populated with default values.
  190. func NewConfig() *Config {
  191. lpurl, _ := url.Parse(DefaultListenPeerURLs)
  192. apurl, _ := url.Parse(DefaultInitialAdvertisePeerURLs)
  193. lcurl, _ := url.Parse(DefaultListenClientURLs)
  194. acurl, _ := url.Parse(DefaultAdvertiseClientURLs)
  195. cfg := &Config{
  196. CorsInfo: &cors.CORSInfo{},
  197. MaxSnapFiles: DefaultMaxSnapshots,
  198. MaxWalFiles: DefaultMaxWALs,
  199. Name: DefaultName,
  200. SnapCount: etcdserver.DefaultSnapCount,
  201. MaxRequestBytes: DefaultMaxRequestBytes,
  202. GRPCKeepAliveMinTime: DefaultGRPCKeepAliveMinTime,
  203. GRPCKeepAliveInterval: DefaultGRPCKeepAliveInterval,
  204. GRPCKeepAliveTimeout: DefaultGRPCKeepAliveTimeout,
  205. TickMs: 100,
  206. ElectionMs: 1000,
  207. InitialElectionTickAdvance: true,
  208. LPUrls: []url.URL{*lpurl},
  209. LCUrls: []url.URL{*lcurl},
  210. APUrls: []url.URL{*apurl},
  211. ACUrls: []url.URL{*acurl},
  212. ClusterState: ClusterStateFlagNew,
  213. InitialClusterToken: "etcd-cluster",
  214. StrictReconfigCheck: true,
  215. Metrics: "basic",
  216. EnableV2: true,
  217. AuthToken: "simple",
  218. }
  219. cfg.InitialCluster = cfg.InitialClusterFromName(cfg.Name)
  220. return cfg
  221. }
  222. func ConfigFromFile(path string) (*Config, error) {
  223. cfg := &configYAML{Config: *NewConfig()}
  224. if err := cfg.configFromFile(path); err != nil {
  225. return nil, err
  226. }
  227. return &cfg.Config, nil
  228. }
  229. func (cfg *configYAML) configFromFile(path string) error {
  230. b, err := ioutil.ReadFile(path)
  231. if err != nil {
  232. return err
  233. }
  234. defaultInitialCluster := cfg.InitialCluster
  235. err = yaml.Unmarshal(b, cfg)
  236. if err != nil {
  237. return err
  238. }
  239. if cfg.LPUrlsJSON != "" {
  240. u, err := types.NewURLs(strings.Split(cfg.LPUrlsJSON, ","))
  241. if err != nil {
  242. plog.Fatalf("unexpected error setting up listen-peer-urls: %v", err)
  243. }
  244. cfg.LPUrls = []url.URL(u)
  245. }
  246. if cfg.LCUrlsJSON != "" {
  247. u, err := types.NewURLs(strings.Split(cfg.LCUrlsJSON, ","))
  248. if err != nil {
  249. plog.Fatalf("unexpected error setting up listen-client-urls: %v", err)
  250. }
  251. cfg.LCUrls = []url.URL(u)
  252. }
  253. if cfg.CorsJSON != "" {
  254. if err := cfg.CorsInfo.Set(cfg.CorsJSON); err != nil {
  255. plog.Panicf("unexpected error setting up cors: %v", err)
  256. }
  257. }
  258. if cfg.APUrlsJSON != "" {
  259. u, err := types.NewURLs(strings.Split(cfg.APUrlsJSON, ","))
  260. if err != nil {
  261. plog.Fatalf("unexpected error setting up initial-advertise-peer-urls: %v", err)
  262. }
  263. cfg.APUrls = []url.URL(u)
  264. }
  265. if cfg.ACUrlsJSON != "" {
  266. u, err := types.NewURLs(strings.Split(cfg.ACUrlsJSON, ","))
  267. if err != nil {
  268. plog.Fatalf("unexpected error setting up advertise-peer-urls: %v", err)
  269. }
  270. cfg.ACUrls = []url.URL(u)
  271. }
  272. // If a discovery flag is set, clear default initial cluster set by InitialClusterFromName
  273. if (cfg.Durl != "" || cfg.DNSCluster != "") && cfg.InitialCluster == defaultInitialCluster {
  274. cfg.InitialCluster = ""
  275. }
  276. if cfg.ClusterState == "" {
  277. cfg.ClusterState = ClusterStateFlagNew
  278. }
  279. copySecurityDetails := func(tls *transport.TLSInfo, ysc *securityConfig) {
  280. tls.CAFile = ysc.CAFile
  281. tls.CertFile = ysc.CertFile
  282. tls.KeyFile = ysc.KeyFile
  283. tls.ClientCertAuth = ysc.CertAuth
  284. tls.TrustedCAFile = ysc.TrustedCAFile
  285. }
  286. copySecurityDetails(&cfg.ClientTLSInfo, &cfg.ClientSecurityJSON)
  287. copySecurityDetails(&cfg.PeerTLSInfo, &cfg.PeerSecurityJSON)
  288. cfg.ClientAutoTLS = cfg.ClientSecurityJSON.AutoTLS
  289. cfg.PeerAutoTLS = cfg.PeerSecurityJSON.AutoTLS
  290. return cfg.Validate()
  291. }
  292. func updateCipherSuites(tls *transport.TLSInfo, ss []string) error {
  293. if len(tls.CipherSuites) > 0 && len(ss) > 0 {
  294. return fmt.Errorf("TLSInfo.CipherSuites is already specified (given %v)", ss)
  295. }
  296. if len(ss) > 0 {
  297. cs := make([]uint16, len(ss))
  298. for i, s := range ss {
  299. var ok bool
  300. cs[i], ok = tlsutil.GetCipherSuite(s)
  301. if !ok {
  302. return fmt.Errorf("unexpected TLS cipher suite %q", s)
  303. }
  304. }
  305. tls.CipherSuites = cs
  306. }
  307. return nil
  308. }
  309. // Validate ensures that '*embed.Config' fields are properly configured.
  310. func (cfg *Config) Validate() error {
  311. if err := checkBindURLs(cfg.LPUrls); err != nil {
  312. return err
  313. }
  314. if err := checkBindURLs(cfg.LCUrls); err != nil {
  315. return err
  316. }
  317. // Check if conflicting flags are passed.
  318. nSet := 0
  319. for _, v := range []bool{cfg.Durl != "", cfg.InitialCluster != "", cfg.DNSCluster != ""} {
  320. if v {
  321. nSet++
  322. }
  323. }
  324. if cfg.ClusterState != ClusterStateFlagNew && cfg.ClusterState != ClusterStateFlagExisting {
  325. return fmt.Errorf("unexpected clusterState %q", cfg.ClusterState)
  326. }
  327. if nSet > 1 {
  328. return ErrConflictBootstrapFlags
  329. }
  330. if 5*cfg.TickMs > cfg.ElectionMs {
  331. return fmt.Errorf("--election-timeout[%vms] should be at least as 5 times as --heartbeat-interval[%vms]", cfg.ElectionMs, cfg.TickMs)
  332. }
  333. if cfg.ElectionMs > maxElectionMs {
  334. return fmt.Errorf("--election-timeout[%vms] is too long, and should be set less than %vms", cfg.ElectionMs, maxElectionMs)
  335. }
  336. // check this last since proxying in etcdmain may make this OK
  337. if cfg.LCUrls != nil && cfg.ACUrls == nil {
  338. return ErrUnsetAdvertiseClientURLsFlag
  339. }
  340. return nil
  341. }
  342. // PeerURLsMapAndToken sets up an initial peer URLsMap and cluster token for bootstrap or discovery.
  343. func (cfg *Config) PeerURLsMapAndToken(which string) (urlsmap types.URLsMap, token string, err error) {
  344. token = cfg.InitialClusterToken
  345. switch {
  346. case cfg.Durl != "":
  347. urlsmap = types.URLsMap{}
  348. // If using discovery, generate a temporary cluster based on
  349. // self's advertised peer URLs
  350. urlsmap[cfg.Name] = cfg.APUrls
  351. token = cfg.Durl
  352. case cfg.DNSCluster != "":
  353. clusterStrs, cerr := srv.GetCluster("etcd-server", cfg.Name, cfg.DNSCluster, cfg.APUrls)
  354. if cerr != nil {
  355. plog.Errorf("couldn't resolve during SRV discovery (%v)", cerr)
  356. return nil, "", cerr
  357. }
  358. for _, s := range clusterStrs {
  359. plog.Noticef("got bootstrap from DNS for etcd-server at %s", s)
  360. }
  361. clusterStr := strings.Join(clusterStrs, ",")
  362. if strings.Contains(clusterStr, "https://") && cfg.PeerTLSInfo.CAFile == "" {
  363. cfg.PeerTLSInfo.ServerName = cfg.DNSCluster
  364. }
  365. urlsmap, err = types.NewURLsMap(clusterStr)
  366. // only etcd member must belong to the discovered cluster.
  367. // proxy does not need to belong to the discovered cluster.
  368. if which == "etcd" {
  369. if _, ok := urlsmap[cfg.Name]; !ok {
  370. return nil, "", fmt.Errorf("cannot find local etcd member %q in SRV records", cfg.Name)
  371. }
  372. }
  373. default:
  374. // We're statically configured, and cluster has appropriately been set.
  375. urlsmap, err = types.NewURLsMap(cfg.InitialCluster)
  376. }
  377. return urlsmap, token, err
  378. }
  379. func (cfg Config) InitialClusterFromName(name string) (ret string) {
  380. if len(cfg.APUrls) == 0 {
  381. return ""
  382. }
  383. n := name
  384. if name == "" {
  385. n = DefaultName
  386. }
  387. for i := range cfg.APUrls {
  388. ret = ret + "," + n + "=" + cfg.APUrls[i].String()
  389. }
  390. return ret[1:]
  391. }
  392. func (cfg Config) IsNewCluster() bool { return cfg.ClusterState == ClusterStateFlagNew }
  393. func (cfg Config) ElectionTicks() int { return int(cfg.ElectionMs / cfg.TickMs) }
  394. func (cfg Config) defaultPeerHost() bool {
  395. return len(cfg.APUrls) == 1 && cfg.APUrls[0].String() == DefaultInitialAdvertisePeerURLs
  396. }
  397. func (cfg Config) defaultClientHost() bool {
  398. return len(cfg.ACUrls) == 1 && cfg.ACUrls[0].String() == DefaultAdvertiseClientURLs
  399. }
  400. func (cfg *Config) ClientSelfCert() (err error) {
  401. if !cfg.ClientAutoTLS {
  402. return nil
  403. }
  404. if !cfg.ClientTLSInfo.Empty() {
  405. plog.Warningf("ignoring client auto TLS since certs given")
  406. return nil
  407. }
  408. chosts := make([]string, len(cfg.LCUrls))
  409. for i, u := range cfg.LCUrls {
  410. chosts[i] = u.Host
  411. }
  412. cfg.ClientTLSInfo, err = transport.SelfCert(filepath.Join(cfg.Dir, "fixtures", "client"), chosts)
  413. if err != nil {
  414. return err
  415. }
  416. return updateCipherSuites(&cfg.ClientTLSInfo, cfg.CipherSuites)
  417. }
  418. func (cfg *Config) PeerSelfCert() (err error) {
  419. if !cfg.PeerAutoTLS {
  420. return nil
  421. }
  422. if !cfg.PeerTLSInfo.Empty() {
  423. plog.Warningf("ignoring peer auto TLS since certs given")
  424. return nil
  425. }
  426. phosts := make([]string, len(cfg.LPUrls))
  427. for i, u := range cfg.LPUrls {
  428. phosts[i] = u.Host
  429. }
  430. cfg.PeerTLSInfo, err = transport.SelfCert(filepath.Join(cfg.Dir, "fixtures", "peer"), phosts)
  431. if err != nil {
  432. return err
  433. }
  434. return updateCipherSuites(&cfg.PeerTLSInfo, cfg.CipherSuites)
  435. }
  436. // UpdateDefaultClusterFromName updates cluster advertise URLs with, if available, default host,
  437. // if advertise URLs are default values(localhost:2379,2380) AND if listen URL is 0.0.0.0.
  438. // e.g. advertise peer URL localhost:2380 or listen peer URL 0.0.0.0:2380
  439. // then the advertise peer host would be updated with machine's default host,
  440. // while keeping the listen URL's port.
  441. // User can work around this by explicitly setting URL with 127.0.0.1.
  442. // It returns the default hostname, if used, and the error, if any, from getting the machine's default host.
  443. // TODO: check whether fields are set instead of whether fields have default value
  444. func (cfg *Config) UpdateDefaultClusterFromName(defaultInitialCluster string) (string, error) {
  445. if defaultHostname == "" || defaultHostStatus != nil {
  446. // update 'initial-cluster' when only the name is specified (e.g. 'etcd --name=abc')
  447. if cfg.Name != DefaultName && cfg.InitialCluster == defaultInitialCluster {
  448. cfg.InitialCluster = cfg.InitialClusterFromName(cfg.Name)
  449. }
  450. return "", defaultHostStatus
  451. }
  452. used := false
  453. pip, pport := cfg.LPUrls[0].Hostname(), cfg.LPUrls[0].Port()
  454. if cfg.defaultPeerHost() && pip == "0.0.0.0" {
  455. cfg.APUrls[0] = url.URL{Scheme: cfg.APUrls[0].Scheme, Host: fmt.Sprintf("%s:%s", defaultHostname, pport)}
  456. used = true
  457. }
  458. // update 'initial-cluster' when only the name is specified (e.g. 'etcd --name=abc')
  459. if cfg.Name != DefaultName && cfg.InitialCluster == defaultInitialCluster {
  460. cfg.InitialCluster = cfg.InitialClusterFromName(cfg.Name)
  461. }
  462. cip, cport := cfg.LCUrls[0].Hostname(), cfg.LCUrls[0].Port()
  463. if cfg.defaultClientHost() && cip == "0.0.0.0" {
  464. cfg.ACUrls[0] = url.URL{Scheme: cfg.ACUrls[0].Scheme, Host: fmt.Sprintf("%s:%s", defaultHostname, cport)}
  465. used = true
  466. }
  467. dhost := defaultHostname
  468. if !used {
  469. dhost = ""
  470. }
  471. return dhost, defaultHostStatus
  472. }
  473. // checkBindURLs returns an error if any URL uses a domain name.
  474. // TODO: return error in 3.2.0
  475. func checkBindURLs(urls []url.URL) error {
  476. for _, url := range urls {
  477. if url.Scheme == "unix" || url.Scheme == "unixs" {
  478. continue
  479. }
  480. host, _, err := net.SplitHostPort(url.Host)
  481. if err != nil {
  482. return err
  483. }
  484. if host == "localhost" {
  485. // special case for local address
  486. // TODO: support /etc/hosts ?
  487. continue
  488. }
  489. if net.ParseIP(host) == nil {
  490. return fmt.Errorf("expected IP in URL for binding (%s)", url.String())
  491. }
  492. }
  493. return nil
  494. }