port.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. Copyright 2017 The Kubernetes Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package util
  14. import (
  15. "fmt"
  16. "net"
  17. "strconv"
  18. "k8s.io/klog"
  19. )
  20. // LocalPort describes a port on specific IP address and protocol
  21. type LocalPort struct {
  22. // Description is the identity message of a given local port.
  23. Description string
  24. // IP is the IP address part of a given local port.
  25. // If this string is empty, the port binds to all local IP addresses.
  26. IP string
  27. // Port is the port part of a given local port.
  28. Port int
  29. // Protocol is the protocol part of a given local port.
  30. // The value is assumed to be lower-case. For example, "udp" not "UDP", "tcp" not "TCP".
  31. Protocol string
  32. }
  33. func (lp *LocalPort) String() string {
  34. ipPort := net.JoinHostPort(lp.IP, strconv.Itoa(lp.Port))
  35. return fmt.Sprintf("%q (%s/%s)", lp.Description, ipPort, lp.Protocol)
  36. }
  37. // Closeable is an interface around closing a port.
  38. type Closeable interface {
  39. Close() error
  40. }
  41. // PortOpener is an interface around port opening/closing.
  42. // Abstracted out for testing.
  43. type PortOpener interface {
  44. OpenLocalPort(lp *LocalPort) (Closeable, error)
  45. }
  46. // RevertPorts is closing ports in replacementPortsMap but not in originalPortsMap. In other words, it only
  47. // closes the ports opened in this sync.
  48. func RevertPorts(replacementPortsMap, originalPortsMap map[LocalPort]Closeable) {
  49. for k, v := range replacementPortsMap {
  50. // Only close newly opened local ports - leave ones that were open before this update
  51. if originalPortsMap[k] == nil {
  52. klog.V(2).Infof("Closing local port %s", k.String())
  53. v.Close()
  54. }
  55. }
  56. }