types.go 12 KB

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