types.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. // Package types contains types that are common across libnetwork project
  2. package types
  3. import (
  4. "bytes"
  5. "fmt"
  6. "net"
  7. "strings"
  8. "github.com/ishidawataru/sctp"
  9. )
  10. // constants for the IP address type
  11. // Deprecated: use the consts defined in github.com/docker/docker/libnetwork/resolvconf
  12. const (
  13. IP = iota // IPv4 and IPv6
  14. IPv4
  15. IPv6
  16. )
  17. // EncryptionKey is the libnetwork representation of the key distributed by the lead
  18. // manager.
  19. type EncryptionKey struct {
  20. Subsystem string
  21. Algorithm int32
  22. Key []byte
  23. LamportTime uint64
  24. }
  25. // UUID represents a globally unique ID of various resources like network and endpoint
  26. type UUID string
  27. // QosPolicy represents a quality of service policy on an endpoint
  28. type QosPolicy struct {
  29. MaxEgressBandwidth uint64
  30. }
  31. // TransportPort represents a local Layer 4 endpoint
  32. type TransportPort struct {
  33. Proto Protocol
  34. Port uint16
  35. }
  36. // Equal checks if this instance of Transportport is equal to the passed one
  37. func (t *TransportPort) Equal(o *TransportPort) bool {
  38. if t == o {
  39. return true
  40. }
  41. if o == nil {
  42. return false
  43. }
  44. if t.Proto != o.Proto || t.Port != o.Port {
  45. return false
  46. }
  47. return true
  48. }
  49. // GetCopy returns a copy of this TransportPort structure instance
  50. func (t *TransportPort) GetCopy() TransportPort {
  51. return TransportPort{Proto: t.Proto, Port: t.Port}
  52. }
  53. // String returns the TransportPort structure in string form
  54. func (t *TransportPort) String() string {
  55. return fmt.Sprintf("%s/%d", t.Proto.String(), t.Port)
  56. }
  57. // PortBinding represents a port binding between the container and the host
  58. type PortBinding struct {
  59. Proto Protocol
  60. IP net.IP
  61. Port uint16
  62. HostIP net.IP
  63. HostPort uint16
  64. HostPortEnd uint16
  65. }
  66. // HostAddr returns the host side transport address
  67. func (p PortBinding) HostAddr() (net.Addr, error) {
  68. switch p.Proto {
  69. case UDP:
  70. return &net.UDPAddr{IP: p.HostIP, Port: int(p.HostPort)}, nil
  71. case TCP:
  72. return &net.TCPAddr{IP: p.HostIP, Port: int(p.HostPort)}, nil
  73. case SCTP:
  74. return &sctp.SCTPAddr{IPAddrs: []net.IPAddr{{IP: p.HostIP}}, Port: int(p.HostPort)}, nil
  75. default:
  76. return nil, ErrInvalidProtocolBinding(p.Proto.String())
  77. }
  78. }
  79. // ContainerAddr returns the container side transport address
  80. func (p PortBinding) ContainerAddr() (net.Addr, error) {
  81. switch p.Proto {
  82. case UDP:
  83. return &net.UDPAddr{IP: p.IP, Port: int(p.Port)}, nil
  84. case TCP:
  85. return &net.TCPAddr{IP: p.IP, Port: int(p.Port)}, nil
  86. case SCTP:
  87. return &sctp.SCTPAddr{IPAddrs: []net.IPAddr{{IP: p.IP}}, Port: int(p.Port)}, nil
  88. default:
  89. return nil, ErrInvalidProtocolBinding(p.Proto.String())
  90. }
  91. }
  92. // GetCopy returns a copy of this PortBinding structure instance
  93. func (p *PortBinding) GetCopy() PortBinding {
  94. return PortBinding{
  95. Proto: p.Proto,
  96. IP: GetIPCopy(p.IP),
  97. Port: p.Port,
  98. HostIP: GetIPCopy(p.HostIP),
  99. HostPort: p.HostPort,
  100. HostPortEnd: p.HostPortEnd,
  101. }
  102. }
  103. // String returns the PortBinding structure in string form
  104. func (p *PortBinding) String() string {
  105. ret := fmt.Sprintf("%s/", p.Proto)
  106. if p.IP != nil {
  107. ret += p.IP.String()
  108. }
  109. ret = fmt.Sprintf("%s:%d/", ret, p.Port)
  110. if p.HostIP != nil {
  111. ret += p.HostIP.String()
  112. }
  113. ret = fmt.Sprintf("%s:%d", ret, p.HostPort)
  114. return ret
  115. }
  116. // Equal checks if this instance of PortBinding is equal to the passed one
  117. func (p *PortBinding) Equal(o *PortBinding) bool {
  118. if p == o {
  119. return true
  120. }
  121. if o == nil {
  122. return false
  123. }
  124. if p.Proto != o.Proto || p.Port != o.Port ||
  125. p.HostPort != o.HostPort || p.HostPortEnd != o.HostPortEnd {
  126. return false
  127. }
  128. if p.IP != nil {
  129. if !p.IP.Equal(o.IP) {
  130. return false
  131. }
  132. } else {
  133. if o.IP != nil {
  134. return false
  135. }
  136. }
  137. if p.HostIP != nil {
  138. if !p.HostIP.Equal(o.HostIP) {
  139. return false
  140. }
  141. } else {
  142. if o.HostIP != nil {
  143. return false
  144. }
  145. }
  146. return true
  147. }
  148. // ErrInvalidProtocolBinding is returned when the port binding protocol is not valid.
  149. type ErrInvalidProtocolBinding string
  150. func (ipb ErrInvalidProtocolBinding) Error() string {
  151. return fmt.Sprintf("invalid transport protocol: %s", string(ipb))
  152. }
  153. const (
  154. // ICMP is for the ICMP ip protocol
  155. ICMP = 1
  156. // TCP is for the TCP ip protocol
  157. TCP = 6
  158. // UDP is for the UDP ip protocol
  159. UDP = 17
  160. // SCTP is for the SCTP ip protocol
  161. SCTP = 132
  162. )
  163. // Protocol represents an IP protocol number
  164. type Protocol uint8
  165. func (p Protocol) String() string {
  166. switch p {
  167. case ICMP:
  168. return "icmp"
  169. case TCP:
  170. return "tcp"
  171. case UDP:
  172. return "udp"
  173. case SCTP:
  174. return "sctp"
  175. default:
  176. return fmt.Sprintf("%d", p)
  177. }
  178. }
  179. // ParseProtocol returns the respective Protocol type for the passed string
  180. func ParseProtocol(s string) Protocol {
  181. switch strings.ToLower(s) {
  182. case "icmp":
  183. return ICMP
  184. case "udp":
  185. return UDP
  186. case "tcp":
  187. return TCP
  188. case "sctp":
  189. return SCTP
  190. default:
  191. return 0
  192. }
  193. }
  194. // GetMacCopy returns a copy of the passed MAC address
  195. func GetMacCopy(from net.HardwareAddr) net.HardwareAddr {
  196. if from == nil {
  197. return nil
  198. }
  199. to := make(net.HardwareAddr, len(from))
  200. copy(to, from)
  201. return to
  202. }
  203. // GetIPCopy returns a copy of the passed IP address
  204. func GetIPCopy(from net.IP) net.IP {
  205. if from == nil {
  206. return nil
  207. }
  208. to := make(net.IP, len(from))
  209. copy(to, from)
  210. return to
  211. }
  212. // GetIPNetCopy returns a copy of the passed IP Network
  213. func GetIPNetCopy(from *net.IPNet) *net.IPNet {
  214. if from == nil {
  215. return nil
  216. }
  217. bm := make(net.IPMask, len(from.Mask))
  218. copy(bm, from.Mask)
  219. return &net.IPNet{IP: GetIPCopy(from.IP), Mask: bm}
  220. }
  221. // GetIPNetCanonical returns the canonical form for the passed network
  222. func GetIPNetCanonical(nw *net.IPNet) *net.IPNet {
  223. if nw == nil {
  224. return nil
  225. }
  226. c := GetIPNetCopy(nw)
  227. c.IP = c.IP.Mask(nw.Mask)
  228. return c
  229. }
  230. // CompareIPNet returns equal if the two IP Networks are equal
  231. func CompareIPNet(a, b *net.IPNet) bool {
  232. if a == b {
  233. return true
  234. }
  235. if a == nil || b == nil {
  236. return false
  237. }
  238. return a.IP.Equal(b.IP) && bytes.Equal(a.Mask, b.Mask)
  239. }
  240. // GetMinimalIP returns the address in its shortest form
  241. // If ip contains an IPv4-mapped IPv6 address, the 4-octet form of the IPv4 address will be returned.
  242. // Otherwise ip is returned unchanged.
  243. func GetMinimalIP(ip net.IP) net.IP {
  244. if ip != nil && ip.To4() != nil {
  245. return ip.To4()
  246. }
  247. return ip
  248. }
  249. // IsIPNetValid returns true if the ipnet is a valid network/mask
  250. // combination. Otherwise returns false.
  251. func IsIPNetValid(nw *net.IPNet) bool {
  252. return nw.String() != "0.0.0.0/0"
  253. }
  254. var v4inV6MaskPrefix = []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
  255. // compareIPMask checks if the passed ip and mask are semantically compatible.
  256. // It returns the byte indexes for the address and mask so that caller can
  257. // do bitwise operations without modifying address representation.
  258. func compareIPMask(ip net.IP, mask net.IPMask) (is int, ms int, err error) {
  259. // Find the effective starting of address and mask
  260. if len(ip) == net.IPv6len && ip.To4() != nil {
  261. is = 12
  262. }
  263. if len(ip[is:]) == net.IPv4len && len(mask) == net.IPv6len && bytes.Equal(mask[:12], v4inV6MaskPrefix) {
  264. ms = 12
  265. }
  266. // Check if address and mask are semantically compatible
  267. if len(ip[is:]) != len(mask[ms:]) {
  268. err = fmt.Errorf("ip and mask are not compatible: (%#v, %#v)", ip, mask)
  269. }
  270. return
  271. }
  272. // GetHostPartIP returns the host portion of the ip address identified by the mask.
  273. // IP address representation is not modified. If address and mask are not compatible
  274. // an error is returned.
  275. func GetHostPartIP(ip net.IP, mask net.IPMask) (net.IP, error) {
  276. // Find the effective starting of address and mask
  277. is, ms, err := compareIPMask(ip, mask)
  278. if err != nil {
  279. return nil, fmt.Errorf("cannot compute host portion ip address because %s", err)
  280. }
  281. // Compute host portion
  282. out := GetIPCopy(ip)
  283. for i := 0; i < len(mask[ms:]); i++ {
  284. out[is+i] &= ^mask[ms+i]
  285. }
  286. return out, nil
  287. }
  288. // GetBroadcastIP returns the broadcast ip address for the passed network (ip and mask).
  289. // IP address representation is not modified. If address and mask are not compatible
  290. // an error is returned.
  291. func GetBroadcastIP(ip net.IP, mask net.IPMask) (net.IP, error) {
  292. // Find the effective starting of address and mask
  293. is, ms, err := compareIPMask(ip, mask)
  294. if err != nil {
  295. return nil, fmt.Errorf("cannot compute broadcast ip address because %s", err)
  296. }
  297. // Compute broadcast address
  298. out := GetIPCopy(ip)
  299. for i := 0; i < len(mask[ms:]); i++ {
  300. out[is+i] |= ^mask[ms+i]
  301. }
  302. return out, nil
  303. }
  304. // ParseCIDR returns the *net.IPNet represented by the passed CIDR notation
  305. func ParseCIDR(cidr string) (n *net.IPNet, e error) {
  306. var i net.IP
  307. if i, n, e = net.ParseCIDR(cidr); e == nil {
  308. n.IP = i
  309. }
  310. return
  311. }
  312. const (
  313. // NEXTHOP indicates a StaticRoute with an IP next hop.
  314. NEXTHOP = iota
  315. // CONNECTED indicates a StaticRoute with an interface for directly connected peers.
  316. CONNECTED
  317. )
  318. // StaticRoute is a statically-provisioned IP route.
  319. type StaticRoute struct {
  320. Destination *net.IPNet
  321. RouteType int // NEXT_HOP or CONNECTED
  322. // NextHop will be resolved by the kernel (i.e. as a loose hop).
  323. NextHop net.IP
  324. }
  325. // GetCopy returns a copy of this StaticRoute structure
  326. func (r *StaticRoute) GetCopy() *StaticRoute {
  327. d := GetIPNetCopy(r.Destination)
  328. nh := GetIPCopy(r.NextHop)
  329. return &StaticRoute{Destination: d,
  330. RouteType: r.RouteType,
  331. NextHop: nh,
  332. }
  333. }
  334. // InterfaceStatistics represents the interface's statistics
  335. type InterfaceStatistics struct {
  336. RxBytes uint64
  337. RxPackets uint64
  338. RxErrors uint64
  339. RxDropped uint64
  340. TxBytes uint64
  341. TxPackets uint64
  342. TxErrors uint64
  343. TxDropped uint64
  344. }
  345. func (is *InterfaceStatistics) String() string {
  346. return fmt.Sprintf("\nRxBytes: %d, RxPackets: %d, RxErrors: %d, RxDropped: %d, TxBytes: %d, TxPackets: %d, TxErrors: %d, TxDropped: %d",
  347. is.RxBytes, is.RxPackets, is.RxErrors, is.RxDropped, is.TxBytes, is.TxPackets, is.TxErrors, is.TxDropped)
  348. }
  349. /******************************
  350. * Well-known Error Interfaces
  351. ******************************/
  352. // MaskableError is an interface for errors which can be ignored by caller
  353. type MaskableError interface {
  354. // Maskable makes implementer into MaskableError type
  355. Maskable()
  356. }
  357. // RetryError is an interface for errors which might get resolved through retry
  358. type RetryError interface {
  359. // Retry makes implementer into RetryError type
  360. Retry()
  361. }
  362. // BadRequestError is an interface for errors originated by a bad request
  363. type BadRequestError interface {
  364. // BadRequest makes implementer into BadRequestError type
  365. BadRequest()
  366. }
  367. // NotFoundError is an interface for errors raised because a needed resource is not available
  368. type NotFoundError interface {
  369. // NotFound makes implementer into NotFoundError type
  370. NotFound()
  371. }
  372. // ForbiddenError is an interface for errors which denote a valid request that cannot be honored
  373. type ForbiddenError interface {
  374. // Forbidden makes implementer into ForbiddenError type
  375. Forbidden()
  376. }
  377. // NoServiceError is an interface for errors returned when the required service is not available
  378. type NoServiceError interface {
  379. // NoService makes implementer into NoServiceError type
  380. NoService()
  381. }
  382. // TimeoutError is an interface for errors raised because of timeout
  383. type TimeoutError interface {
  384. // Timeout makes implementer into TimeoutError type
  385. Timeout()
  386. }
  387. // NotImplementedError is an interface for errors raised because of requested functionality is not yet implemented
  388. type NotImplementedError interface {
  389. // NotImplemented makes implementer into NotImplementedError type
  390. NotImplemented()
  391. }
  392. // InternalError is an interface for errors raised because of an internal error
  393. type InternalError interface {
  394. // Internal makes implementer into InternalError type
  395. Internal()
  396. }
  397. /******************************
  398. * Well-known Error Formatters
  399. ******************************/
  400. // BadRequestErrorf creates an instance of BadRequestError
  401. func BadRequestErrorf(format string, params ...interface{}) error {
  402. return badRequest(fmt.Sprintf(format, params...))
  403. }
  404. // NotFoundErrorf creates an instance of NotFoundError
  405. func NotFoundErrorf(format string, params ...interface{}) error {
  406. return notFound(fmt.Sprintf(format, params...))
  407. }
  408. // ForbiddenErrorf creates an instance of ForbiddenError
  409. func ForbiddenErrorf(format string, params ...interface{}) error {
  410. return forbidden(fmt.Sprintf(format, params...))
  411. }
  412. // NoServiceErrorf creates an instance of NoServiceError
  413. func NoServiceErrorf(format string, params ...interface{}) error {
  414. return noService(fmt.Sprintf(format, params...))
  415. }
  416. // NotImplementedErrorf creates an instance of NotImplementedError
  417. func NotImplementedErrorf(format string, params ...interface{}) error {
  418. return notImpl(fmt.Sprintf(format, params...))
  419. }
  420. // TimeoutErrorf creates an instance of TimeoutError
  421. func TimeoutErrorf(format string, params ...interface{}) error {
  422. return timeout(fmt.Sprintf(format, params...))
  423. }
  424. // InternalErrorf creates an instance of InternalError
  425. func InternalErrorf(format string, params ...interface{}) error {
  426. return internal(fmt.Sprintf(format, params...))
  427. }
  428. // InternalMaskableErrorf creates an instance of InternalError and MaskableError
  429. func InternalMaskableErrorf(format string, params ...interface{}) error {
  430. return maskInternal(fmt.Sprintf(format, params...))
  431. }
  432. // RetryErrorf creates an instance of RetryError
  433. func RetryErrorf(format string, params ...interface{}) error {
  434. return retry(fmt.Sprintf(format, params...))
  435. }
  436. /***********************
  437. * Internal Error Types
  438. ***********************/
  439. type badRequest string
  440. func (br badRequest) Error() string {
  441. return string(br)
  442. }
  443. func (br badRequest) BadRequest() {}
  444. type notFound string
  445. func (nf notFound) Error() string {
  446. return string(nf)
  447. }
  448. func (nf notFound) NotFound() {}
  449. type forbidden string
  450. func (frb forbidden) Error() string {
  451. return string(frb)
  452. }
  453. func (frb forbidden) Forbidden() {}
  454. type noService string
  455. func (ns noService) Error() string {
  456. return string(ns)
  457. }
  458. func (ns noService) NoService() {}
  459. type timeout string
  460. func (to timeout) Error() string {
  461. return string(to)
  462. }
  463. func (to timeout) Timeout() {}
  464. type notImpl string
  465. func (ni notImpl) Error() string {
  466. return string(ni)
  467. }
  468. func (ni notImpl) NotImplemented() {}
  469. type internal string
  470. func (nt internal) Error() string {
  471. return string(nt)
  472. }
  473. func (nt internal) Internal() {}
  474. type maskInternal string
  475. func (mnt maskInternal) Error() string {
  476. return string(mnt)
  477. }
  478. func (mnt maskInternal) Internal() {}
  479. func (mnt maskInternal) Maskable() {}
  480. type retry string
  481. func (r retry) Error() string {
  482. return string(r)
  483. }
  484. func (r retry) Retry() {}