1 // Package types contains types that are common across libnetwork project
12 // constants for the IP address type
14 IP = iota // IPv4 and IPv6
19 // EncryptionKey is the libnetwork representation of the key distributed by the lead
21 type EncryptionKey struct {
28 // UUID represents a globally unique ID of various resources like network and endpoint
31 // QosPolicy represents a quality of service policy on an endpoint
32 type QosPolicy struct {
33 MaxEgressBandwidth uint64
36 // TransportPort represents a local Layer 4 endpoint
37 type TransportPort struct {
42 // Equal checks if this instance of Transportport is equal to the passed one
43 func (t *TransportPort) Equal(o *TransportPort) bool {
52 if t.Proto != o.Proto || t.Port != o.Port {
59 // GetCopy returns a copy of this TransportPort structure instance
60 func (t *TransportPort) GetCopy() TransportPort {
61 return TransportPort{Proto: t.Proto, Port: t.Port}
64 // String returns the TransportPort structure in string form
65 func (t *TransportPort) String() string {
66 return fmt.Sprintf("%s/%d", t.Proto.String(), t.Port)
69 // FromString reads the TransportPort structure from string
70 func (t *TransportPort) FromString(s string) error {
71 ps := strings.Split(s, "/")
73 t.Proto = ParseProtocol(ps[0])
74 if p, err := strconv.ParseUint(ps[1], 10, 16); err == nil {
79 return BadRequestErrorf("invalid format for transport port: %s", s)
82 // PortBinding represents a port binding between the container and the host
83 type PortBinding struct {
92 // HostAddr returns the host side transport address
93 func (p PortBinding) HostAddr() (net.Addr, error) {
96 return &net.UDPAddr{IP: p.HostIP, Port: int(p.HostPort)}, nil
98 return &net.TCPAddr{IP: p.HostIP, Port: int(p.HostPort)}, nil
100 return nil, ErrInvalidProtocolBinding(p.Proto.String())
104 // ContainerAddr returns the container side transport address
105 func (p PortBinding) ContainerAddr() (net.Addr, error) {
108 return &net.UDPAddr{IP: p.IP, Port: int(p.Port)}, nil
110 return &net.TCPAddr{IP: p.IP, Port: int(p.Port)}, nil
112 return nil, ErrInvalidProtocolBinding(p.Proto.String())
116 // GetCopy returns a copy of this PortBinding structure instance
117 func (p *PortBinding) GetCopy() PortBinding {
122 HostIP: GetIPCopy(p.HostIP),
123 HostPort: p.HostPort,
124 HostPortEnd: p.HostPortEnd,
128 // String returns the PortBinding structure in string form
129 func (p *PortBinding) String() string {
130 ret := fmt.Sprintf("%s/", p.Proto)
132 ret = fmt.Sprintf("%s%s", ret, p.IP.String())
134 ret = fmt.Sprintf("%s:%d/", ret, p.Port)
136 ret = fmt.Sprintf("%s%s", ret, p.HostIP.String())
138 ret = fmt.Sprintf("%s:%d", ret, p.HostPort)
142 // FromString reads the TransportPort structure from string
143 func (p *PortBinding) FromString(s string) error {
144 ps := strings.Split(s, "/")
146 return BadRequestErrorf("invalid format for port binding: %s", s)
149 p.Proto = ParseProtocol(ps[0])
152 if p.IP, p.Port, err = parseIPPort(ps[1]); err != nil {
153 return BadRequestErrorf("failed to parse Container IP/Port in port binding: %s", err.Error())
156 if p.HostIP, p.HostPort, err = parseIPPort(ps[2]); err != nil {
157 return BadRequestErrorf("failed to parse Host IP/Port in port binding: %s", err.Error())
163 func parseIPPort(s string) (net.IP, uint16, error) {
164 pp := strings.Split(s, ":")
166 return nil, 0, BadRequestErrorf("invalid format: %s", s)
171 if ip = net.ParseIP(pp[0]); ip == nil {
172 return nil, 0, BadRequestErrorf("invalid ip: %s", pp[0])
176 port, err := strconv.ParseUint(pp[1], 10, 16)
178 return nil, 0, BadRequestErrorf("invalid port: %s", pp[1])
181 return ip, uint16(port), nil
184 // Equal checks if this instance of PortBinding is equal to the passed one
185 func (p *PortBinding) Equal(o *PortBinding) bool {
194 if p.Proto != o.Proto || p.Port != o.Port ||
195 p.HostPort != o.HostPort || p.HostPortEnd != o.HostPortEnd {
200 if !p.IP.Equal(o.IP) {
210 if !p.HostIP.Equal(o.HostIP) {
222 // ErrInvalidProtocolBinding is returned when the port binding protocol is not valid.
223 type ErrInvalidProtocolBinding string
225 func (ipb ErrInvalidProtocolBinding) Error() string {
226 return fmt.Sprintf("invalid transport protocol: %s", string(ipb))
230 // ICMP is for the ICMP ip protocol
232 // TCP is for the TCP ip protocol
234 // UDP is for the UDP ip protocol
238 // Protocol represents an IP protocol number
241 func (p Protocol) String() string {
250 return fmt.Sprintf("%d", p)
254 // ParseProtocol returns the respective Protocol type for the passed string
255 func ParseProtocol(s string) Protocol {
256 switch strings.ToLower(s) {
268 // GetMacCopy returns a copy of the passed MAC address
269 func GetMacCopy(from net.HardwareAddr) net.HardwareAddr {
273 to := make(net.HardwareAddr, len(from))
278 // GetIPCopy returns a copy of the passed IP address
279 func GetIPCopy(from net.IP) net.IP {
283 to := make(net.IP, len(from))
288 // GetIPNetCopy returns a copy of the passed IP Network
289 func GetIPNetCopy(from *net.IPNet) *net.IPNet {
293 bm := make(net.IPMask, len(from.Mask))
295 return &net.IPNet{IP: GetIPCopy(from.IP), Mask: bm}
298 // GetIPNetCanonical returns the canonical form for the passed network
299 func GetIPNetCanonical(nw *net.IPNet) *net.IPNet {
303 c := GetIPNetCopy(nw)
304 c.IP = c.IP.Mask(nw.Mask)
308 // CompareIPNet returns equal if the two IP Networks are equal
309 func CompareIPNet(a, b *net.IPNet) bool {
313 if a == nil || b == nil {
316 return a.IP.Equal(b.IP) && bytes.Equal(a.Mask, b.Mask)
319 // GetMinimalIP returns the address in its shortest form
320 func GetMinimalIP(ip net.IP) net.IP {
321 if ip != nil && ip.To4() != nil {
327 // GetMinimalIPNet returns a copy of the passed IP Network with congruent ip and mask notation
328 func GetMinimalIPNet(nw *net.IPNet) *net.IPNet {
332 if len(nw.IP) == 16 && nw.IP.To4() != nil {
337 return &net.IPNet{IP: nw.IP.To4(), Mask: m}
342 // IsIPNetValid returns true if the ipnet is a valid network/mask
343 // combination. Otherwise returns false.
344 func IsIPNetValid(nw *net.IPNet) bool {
345 return nw.String() != "0.0.0.0/0"
348 var v4inV6MaskPrefix = []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
350 // compareIPMask checks if the passed ip and mask are semantically compatible.
351 // It returns the byte indexes for the address and mask so that caller can
352 // do bitwise operations without modifying address representation.
353 func compareIPMask(ip net.IP, mask net.IPMask) (is int, ms int, err error) {
354 // Find the effective starting of address and mask
355 if len(ip) == net.IPv6len && ip.To4() != nil {
358 if len(ip[is:]) == net.IPv4len && len(mask) == net.IPv6len && bytes.Equal(mask[:12], v4inV6MaskPrefix) {
361 // Check if address and mask are semantically compatible
362 if len(ip[is:]) != len(mask[ms:]) {
363 err = fmt.Errorf("ip and mask are not compatible: (%#v, %#v)", ip, mask)
368 // GetHostPartIP returns the host portion of the ip address identified by the mask.
369 // IP address representation is not modified. If address and mask are not compatible
370 // an error is returned.
371 func GetHostPartIP(ip net.IP, mask net.IPMask) (net.IP, error) {
372 // Find the effective starting of address and mask
373 is, ms, err := compareIPMask(ip, mask)
375 return nil, fmt.Errorf("cannot compute host portion ip address because %s", err)
378 // Compute host portion
380 for i := 0; i < len(mask[ms:]); i++ {
381 out[is+i] &= ^mask[ms+i]
387 // GetBroadcastIP returns the broadcast ip address for the passed network (ip and mask).
388 // IP address representation is not modified. If address and mask are not compatible
389 // an error is returned.
390 func GetBroadcastIP(ip net.IP, mask net.IPMask) (net.IP, error) {
391 // Find the effective starting of address and mask
392 is, ms, err := compareIPMask(ip, mask)
394 return nil, fmt.Errorf("cannot compute broadcast ip address because %s", err)
397 // Compute broadcast address
399 for i := 0; i < len(mask[ms:]); i++ {
400 out[is+i] |= ^mask[ms+i]
406 // ParseCIDR returns the *net.IPNet represented by the passed CIDR notation
407 func ParseCIDR(cidr string) (n *net.IPNet, e error) {
409 if i, n, e = net.ParseCIDR(cidr); e == nil {
416 // NEXTHOP indicates a StaticRoute with an IP next hop.
419 // CONNECTED indicates a StaticRoute with an interface for directly connected peers.
423 // StaticRoute is a statically-provisioned IP route.
424 type StaticRoute struct {
425 Destination *net.IPNet
427 RouteType int // NEXT_HOP or CONNECTED
429 // NextHop will be resolved by the kernel (i.e. as a loose hop).
433 // GetCopy returns a copy of this StaticRoute structure
434 func (r *StaticRoute) GetCopy() *StaticRoute {
435 d := GetIPNetCopy(r.Destination)
436 nh := GetIPCopy(r.NextHop)
437 return &StaticRoute{Destination: d,
438 RouteType: r.RouteType,
443 // InterfaceStatistics represents the interface's statistics
444 type InterfaceStatistics struct {
455 func (is *InterfaceStatistics) String() string {
456 return fmt.Sprintf("\nRxBytes: %d, RxPackets: %d, RxErrors: %d, RxDropped: %d, TxBytes: %d, TxPackets: %d, TxErrors: %d, TxDropped: %d",
457 is.RxBytes, is.RxPackets, is.RxErrors, is.RxDropped, is.TxBytes, is.TxPackets, is.TxErrors, is.TxDropped)
460 /******************************
461 * Well-known Error Interfaces
462 ******************************/
464 // MaskableError is an interface for errors which can be ignored by caller
465 type MaskableError interface {
466 // Maskable makes implementer into MaskableError type
470 // RetryError is an interface for errors which might get resolved through retry
471 type RetryError interface {
472 // Retry makes implementer into RetryError type
476 // BadRequestError is an interface for errors originated by a bad request
477 type BadRequestError interface {
478 // BadRequest makes implementer into BadRequestError type
482 // NotFoundError is an interface for errors raised because a needed resource is not available
483 type NotFoundError interface {
484 // NotFound makes implementer into NotFoundError type
488 // ForbiddenError is an interface for errors which denote a valid request that cannot be honored
489 type ForbiddenError interface {
490 // Forbidden makes implementer into ForbiddenError type
494 // NoServiceError is an interface for errors returned when the required service is not available
495 type NoServiceError interface {
496 // NoService makes implementer into NoServiceError type
500 // TimeoutError is an interface for errors raised because of timeout
501 type TimeoutError interface {
502 // Timeout makes implementer into TimeoutError type
506 // NotImplementedError is an interface for errors raised because of requested functionality is not yet implemented
507 type NotImplementedError interface {
508 // NotImplemented makes implementer into NotImplementedError type
512 // InternalError is an interface for errors raised because of an internal error
513 type InternalError interface {
514 // Internal makes implementer into InternalError type
518 /******************************
519 * Well-known Error Formatters
520 ******************************/
522 // BadRequestErrorf creates an instance of BadRequestError
523 func BadRequestErrorf(format string, params ...interface{}) error {
524 return badRequest(fmt.Sprintf(format, params...))
527 // NotFoundErrorf creates an instance of NotFoundError
528 func NotFoundErrorf(format string, params ...interface{}) error {
529 return notFound(fmt.Sprintf(format, params...))
532 // ForbiddenErrorf creates an instance of ForbiddenError
533 func ForbiddenErrorf(format string, params ...interface{}) error {
534 return forbidden(fmt.Sprintf(format, params...))
537 // NoServiceErrorf creates an instance of NoServiceError
538 func NoServiceErrorf(format string, params ...interface{}) error {
539 return noService(fmt.Sprintf(format, params...))
542 // NotImplementedErrorf creates an instance of NotImplementedError
543 func NotImplementedErrorf(format string, params ...interface{}) error {
544 return notImpl(fmt.Sprintf(format, params...))
547 // TimeoutErrorf creates an instance of TimeoutError
548 func TimeoutErrorf(format string, params ...interface{}) error {
549 return timeout(fmt.Sprintf(format, params...))
552 // InternalErrorf creates an instance of InternalError
553 func InternalErrorf(format string, params ...interface{}) error {
554 return internal(fmt.Sprintf(format, params...))
557 // InternalMaskableErrorf creates an instance of InternalError and MaskableError
558 func InternalMaskableErrorf(format string, params ...interface{}) error {
559 return maskInternal(fmt.Sprintf(format, params...))
562 // RetryErrorf creates an instance of RetryError
563 func RetryErrorf(format string, params ...interface{}) error {
564 return retry(fmt.Sprintf(format, params...))
567 /***********************
568 * Internal Error Types
569 ***********************/
570 type badRequest string
572 func (br badRequest) Error() string {
575 func (br badRequest) BadRequest() {}
577 type maskBadRequest string
581 func (nf notFound) Error() string {
584 func (nf notFound) NotFound() {}
586 type forbidden string
588 func (frb forbidden) Error() string {
591 func (frb forbidden) Forbidden() {}
593 type noService string
595 func (ns noService) Error() string {
598 func (ns noService) NoService() {}
600 type maskNoService string
604 func (to timeout) Error() string {
607 func (to timeout) Timeout() {}
611 func (ni notImpl) Error() string {
614 func (ni notImpl) NotImplemented() {}
618 func (nt internal) Error() string {
621 func (nt internal) Internal() {}
623 type maskInternal string
625 func (mnt maskInternal) Error() string {
628 func (mnt maskInternal) Internal() {}
629 func (mnt maskInternal) Maskable() {}
633 func (r retry) Error() string {
636 func (r retry) Retry() {}