types.go 15 KB

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