netsh.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. /*
  2. Copyright 2016 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 netsh
  14. import (
  15. "fmt"
  16. "net"
  17. "os"
  18. "strings"
  19. "time"
  20. "k8s.io/klog"
  21. utilexec "k8s.io/utils/exec"
  22. )
  23. // Interface is an injectable interface for running netsh commands. Implementations must be goroutine-safe.
  24. type Interface interface {
  25. // EnsurePortProxyRule checks if the specified redirect exists, if not creates it
  26. EnsurePortProxyRule(args []string) (bool, error)
  27. // DeletePortProxyRule deletes the specified portproxy rule. If the rule did not exist, return error.
  28. DeletePortProxyRule(args []string) error
  29. // EnsureIPAddress checks if the specified IP Address is added to vEthernet (HNSTransparent) interface, if not, add it. If the address existed, return true.
  30. EnsureIPAddress(args []string, ip net.IP) (bool, error)
  31. // DeleteIPAddress checks if the specified IP address is present and, if so, deletes it.
  32. DeleteIPAddress(args []string) error
  33. // Restore runs `netsh exec` to restore portproxy or addresses using a file.
  34. // TODO Check if this is required, most likely not
  35. Restore(args []string) error
  36. // GetInterfaceToAddIP returns the interface name where Service IP needs to be added
  37. // IP Address needs to be added for netsh portproxy to redirect traffic
  38. // Reads Environment variable INTERFACE_TO_ADD_SERVICE_IP, if it is not defined then "vEthernet (HNSTransparent)" is returned
  39. GetInterfaceToAddIP() string
  40. }
  41. const (
  42. cmdNetsh string = "netsh"
  43. )
  44. // runner implements Interface in terms of exec("netsh").
  45. type runner struct {
  46. exec utilexec.Interface
  47. }
  48. // New returns a new Interface which will exec netsh.
  49. func New(exec utilexec.Interface) Interface {
  50. runner := &runner{
  51. exec: exec,
  52. }
  53. return runner
  54. }
  55. // EnsurePortProxyRule checks if the specified redirect exists, if not creates it.
  56. func (runner *runner) EnsurePortProxyRule(args []string) (bool, error) {
  57. klog.V(4).Infof("running netsh interface portproxy add v4tov4 %v", args)
  58. out, err := runner.exec.Command(cmdNetsh, args...).CombinedOutput()
  59. if err == nil {
  60. return true, nil
  61. }
  62. if ee, ok := err.(utilexec.ExitError); ok {
  63. // netsh uses exit(0) to indicate a success of the operation,
  64. // as compared to a malformed commandline, for example.
  65. if ee.Exited() && ee.ExitStatus() != 0 {
  66. return false, nil
  67. }
  68. }
  69. return false, fmt.Errorf("error checking portproxy rule: %v: %s", err, out)
  70. }
  71. // DeletePortProxyRule deletes the specified portproxy rule. If the rule did not exist, return error.
  72. func (runner *runner) DeletePortProxyRule(args []string) error {
  73. klog.V(4).Infof("running netsh interface portproxy delete v4tov4 %v", args)
  74. out, err := runner.exec.Command(cmdNetsh, args...).CombinedOutput()
  75. if err == nil {
  76. return nil
  77. }
  78. if ee, ok := err.(utilexec.ExitError); ok {
  79. // netsh uses exit(0) to indicate a success of the operation,
  80. // as compared to a malformed commandline, for example.
  81. if ee.Exited() && ee.ExitStatus() == 0 {
  82. return nil
  83. }
  84. }
  85. return fmt.Errorf("error deleting portproxy rule: %v: %s", err, out)
  86. }
  87. // EnsureIPAddress checks if the specified IP Address is added to interface identified by Environment variable INTERFACE_TO_ADD_SERVICE_IP, if not, add it. If the address existed, return true.
  88. func (runner *runner) EnsureIPAddress(args []string, ip net.IP) (bool, error) {
  89. // Check if the ip address exists
  90. intName := runner.GetInterfaceToAddIP()
  91. argsShowAddress := []string{
  92. "interface", "ipv4", "show", "address",
  93. "name=" + intName,
  94. }
  95. ipToCheck := ip.String()
  96. exists, _ := checkIPExists(ipToCheck, argsShowAddress, runner)
  97. if exists == true {
  98. klog.V(4).Infof("not adding IP address %q as it already exists", ipToCheck)
  99. return true, nil
  100. }
  101. // IP Address is not already added, add it now
  102. klog.V(4).Infof("running netsh interface ipv4 add address %v", args)
  103. out, err := runner.exec.Command(cmdNetsh, args...).CombinedOutput()
  104. if err == nil {
  105. // Once the IP Address is added, it takes a bit to initialize and show up when querying for it
  106. // Query all the IP addresses and see if the one we added is present
  107. // PS: We are using netsh interface ipv4 show address here to query all the IP addresses, instead of
  108. // querying net.InterfaceAddrs() as it returns the IP address as soon as it is added even though it is uninitialized
  109. klog.V(3).Infof("Waiting until IP: %v is added to the network adapter", ipToCheck)
  110. for {
  111. if exists, _ := checkIPExists(ipToCheck, argsShowAddress, runner); exists {
  112. return true, nil
  113. }
  114. time.Sleep(500 * time.Millisecond)
  115. }
  116. }
  117. if ee, ok := err.(utilexec.ExitError); ok {
  118. // netsh uses exit(0) to indicate a success of the operation,
  119. // as compared to a malformed commandline, for example.
  120. if ee.Exited() && ee.ExitStatus() != 0 {
  121. return false, nil
  122. }
  123. }
  124. return false, fmt.Errorf("error adding ipv4 address: %v: %s", err, out)
  125. }
  126. // DeleteIPAddress checks if the specified IP address is present and, if so, deletes it.
  127. func (runner *runner) DeleteIPAddress(args []string) error {
  128. klog.V(4).Infof("running netsh interface ipv4 delete address %v", args)
  129. out, err := runner.exec.Command(cmdNetsh, args...).CombinedOutput()
  130. if err == nil {
  131. return nil
  132. }
  133. if ee, ok := err.(utilexec.ExitError); ok {
  134. // netsh uses exit(0) to indicate a success of the operation,
  135. // as compared to a malformed commandline, for example.
  136. if ee.Exited() && ee.ExitStatus() == 0 {
  137. return nil
  138. }
  139. }
  140. return fmt.Errorf("error deleting ipv4 address: %v: %s", err, out)
  141. }
  142. // GetInterfaceToAddIP returns the interface name where Service IP needs to be added
  143. // IP Address needs to be added for netsh portproxy to redirect traffic
  144. // Reads Environment variable INTERFACE_TO_ADD_SERVICE_IP, if it is not defined then "vEthernet (HNS Internal NIC)" is returned
  145. func (runner *runner) GetInterfaceToAddIP() string {
  146. if iface := os.Getenv("INTERFACE_TO_ADD_SERVICE_IP"); len(iface) > 0 {
  147. return iface
  148. }
  149. return "vEthernet (HNS Internal NIC)"
  150. }
  151. // Restore is part of Interface.
  152. func (runner *runner) Restore(args []string) error {
  153. return nil
  154. }
  155. // checkIPExists checks if an IP address exists in 'netsh interface ipv4 show address' output
  156. func checkIPExists(ipToCheck string, args []string, runner *runner) (bool, error) {
  157. ipAddress, err := runner.exec.Command(cmdNetsh, args...).CombinedOutput()
  158. if err != nil {
  159. return false, err
  160. }
  161. ipAddressString := string(ipAddress[:])
  162. klog.V(3).Infof("Searching for IP: %v in IP dump: %v", ipToCheck, ipAddressString)
  163. showAddressArray := strings.Split(ipAddressString, "\n")
  164. for _, showAddress := range showAddressArray {
  165. if strings.Contains(showAddress, "IP") {
  166. ipFromNetsh := getIP(showAddress)
  167. if ipFromNetsh == ipToCheck {
  168. return true, nil
  169. }
  170. }
  171. }
  172. return false, nil
  173. }
  174. // getIP gets ip from showAddress (e.g. "IP Address: 10.96.0.4").
  175. func getIP(showAddress string) string {
  176. list := strings.SplitN(showAddress, ":", 2)
  177. if len(list) != 2 {
  178. return ""
  179. }
  180. return strings.TrimSpace(list[1])
  181. }