Skip to content

Commit c3f1a6e

Browse files
authored
fix: remove PowerShell from Windows registry interactions (#2993)
remove powershell from windows registry txs Signed-off-by: Evan Baker <[email protected]>
1 parent 21708a1 commit c3f1a6e

File tree

5 files changed

+67
-82
lines changed

5 files changed

+67
-82
lines changed

cns/service/main.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -788,8 +788,7 @@ func main() {
788788
}
789789

790790
// Setting the remote ARP MAC address to 12-34-56-78-9a-bc on windows for external traffic if HNS is enabled
791-
execClient := platform.NewExecClient(nil)
792-
err = platform.SetSdnRemoteArpMacAddress(execClient)
791+
err = platform.SetSdnRemoteArpMacAddress(rootCtx)
793792
if err != nil {
794793
logger.Errorf("Failed to set remote ARP MAC address: %v", err)
795794
return

platform/os_linux.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,7 @@ func (p *execClient) KillProcessByName(processName string) error {
179179

180180
// SetSdnRemoteArpMacAddress sets the regkey for SDNRemoteArpMacAddress needed for multitenancy
181181
// This operation is specific to windows OS
182-
func SetSdnRemoteArpMacAddress(_ ExecClient) error {
182+
func SetSdnRemoteArpMacAddress(context.Context) error {
183183
return nil
184184
}
185185

platform/os_windows.go

Lines changed: 64 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@ import (
2020
"github.com/pkg/errors"
2121
"go.uber.org/zap"
2222
"golang.org/x/sys/windows"
23+
"golang.org/x/sys/windows/registry"
24+
"golang.org/x/sys/windows/svc"
25+
"golang.org/x/sys/windows/svc/mgr"
2326
)
2427

2528
const (
@@ -61,24 +64,10 @@ const (
6164
// for vlan tagged arp requests
6265
SDNRemoteArpMacAddress = "12-34-56-78-9a-bc"
6366

64-
// Command to get SDNRemoteArpMacAddress registry key
65-
GetSdnRemoteArpMacAddressCommand = "(Get-ItemProperty " +
66-
"-Path HKLM:\\SYSTEM\\CurrentControlSet\\Services\\hns\\State -Name SDNRemoteArpMacAddress).SDNRemoteArpMacAddress"
67-
68-
// Command to set SDNRemoteArpMacAddress registry key
69-
SetSdnRemoteArpMacAddressCommand = "Set-ItemProperty " +
70-
"-Path HKLM:\\SYSTEM\\CurrentControlSet\\Services\\hns\\State -Name SDNRemoteArpMacAddress -Value \"12-34-56-78-9a-bc\""
71-
72-
// Command to check if system has hns state path or not
73-
CheckIfHNSStatePathExistsCommand = "Test-Path " +
74-
"-Path HKLM:\\SYSTEM\\CurrentControlSet\\Services\\hns\\State"
75-
7667
// Command to fetch netadapter and pnp id
68+
// TODO: can we replace this (and things in endpoint_windows) with other utils from "golang.org/x/sys/windows"?
7769
GetMacAddressVFPPnpIDMapping = "Get-NetAdapter | Select-Object MacAddress, PnpDeviceID| Format-Table -HideTableHeaders"
7870

79-
// Command to restart HNS service
80-
RestartHnsServiceCommand = "Restart-Service -Name hns"
81-
8271
// Interval between successive checks for mellanox adapter's PriorityVLANTag value
8372
defaultMellanoxMonitorInterval = 30 * time.Second
8473

@@ -257,40 +246,73 @@ func (p *execClient) ExecutePowershellCommandWithContext(ctx context.Context, co
257246
}
258247

259248
// SetSdnRemoteArpMacAddress sets the regkey for SDNRemoteArpMacAddress needed for multitenancy if hns is enabled
260-
func SetSdnRemoteArpMacAddress(execClient ExecClient) error {
261-
exists, err := execClient.ExecutePowershellCommand(CheckIfHNSStatePathExistsCommand)
249+
func SetSdnRemoteArpMacAddress(ctx context.Context) error {
250+
log.Printf("Setting SDNRemoteArpMacAddress regKey")
251+
// open the registry key
252+
k, err := registry.OpenKey(registry.LOCAL_MACHINE, `SYSTEM\CurrentControlSet\Services\hns\State`, registry.READ|registry.SET_VALUE)
262253
if err != nil {
263-
errMsg := fmt.Sprintf("Failed to check the existent of hns state path due to error %s", err.Error())
264-
log.Printf(errMsg)
265-
return errors.Errorf(errMsg)
254+
if errors.Is(err, registry.ErrNotExist) {
255+
return nil
256+
}
257+
return errors.Wrap(err, "could not open registry key")
266258
}
267-
if strings.EqualFold(exists, "false") {
268-
log.Printf("hns state path does not exist, skip setting SdnRemoteArpMacAddress")
269-
return nil
259+
defer k.Close()
260+
// check the key value
261+
if v, _, _ := k.GetStringValue("SDNRemoteArpMacAddress"); v == SDNRemoteArpMacAddress {
262+
log.Printf("SDNRemoteArpMacAddress regKey already set")
263+
return nil // already set
270264
}
271-
if sdnRemoteArpMacAddressSet == false {
272-
result, err := execClient.ExecutePowershellCommand(GetSdnRemoteArpMacAddressCommand)
265+
if err = k.SetStringValue("SDNRemoteArpMacAddress", SDNRemoteArpMacAddress); err != nil {
266+
return errors.Wrap(err, "could not set registry key")
267+
}
268+
log.Printf("SDNRemoteArpMacAddress regKey set successfully")
269+
log.Printf("Restarting HNS service")
270+
// connect to the service manager
271+
m, err := mgr.Connect()
272+
if err != nil {
273+
return errors.Wrap(err, "could not connect to service manager")
274+
}
275+
defer m.Disconnect() //nolint:errcheck // ignore error
276+
// open the HNS service
277+
service, err := m.OpenService("hns")
278+
if err != nil {
279+
return errors.Wrap(err, "could not access service")
280+
}
281+
defer service.Close()
282+
if err := restartService(ctx, service); err != nil {
283+
return errors.Wrap(err, "could not restart service")
284+
}
285+
log.Printf("HNS service restarted successfully")
286+
return nil
287+
}
288+
289+
func restartService(ctx context.Context, s *mgr.Service) error {
290+
// Stop the service
291+
_, err := s.Control(svc.Stop)
292+
if err != nil {
293+
return errors.Wrap(err, "could not stop service")
294+
}
295+
// Wait for the service to stop
296+
ticker := time.NewTicker(500 * time.Millisecond) //nolint:gomnd // 500ms
297+
defer ticker.Stop()
298+
for { // hacky cancellable do-while
299+
status, err := s.Query()
273300
if err != nil {
274-
return err
301+
return errors.Wrap(err, "could not query service status")
275302
}
276-
277-
// Set the reg key if not already set or has incorrect value
278-
if result != SDNRemoteArpMacAddress {
279-
if _, err = execClient.ExecutePowershellCommand(SetSdnRemoteArpMacAddressCommand); err != nil {
280-
log.Printf("Failed to set SDNRemoteArpMacAddress due to error %s", err.Error())
281-
return err
282-
}
283-
284-
log.Printf("[Azure CNS] SDNRemoteArpMacAddress regKey set successfully. Restarting hns service.")
285-
if _, err := execClient.ExecutePowershellCommand(RestartHnsServiceCommand); err != nil {
286-
log.Printf("Failed to Restart HNS Service due to error %s", err.Error())
287-
return err
288-
}
303+
if status.State == svc.Stopped {
304+
break
305+
}
306+
select {
307+
case <-ctx.Done():
308+
return errors.New("context cancelled")
309+
case <-ticker.C:
289310
}
290-
291-
sdnRemoteArpMacAddressSet = true
292311
}
293-
312+
// Start the service again
313+
if err := s.Start(); err != nil {
314+
return errors.Wrap(err, "could not start service")
315+
}
294316
return nil
295317
}
296318

platform/os_windows_test.go

Lines changed: 0 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import (
44
"context"
55
"errors"
66
"os/exec"
7-
"strings"
87
"testing"
98
"time"
109

@@ -115,41 +114,6 @@ func TestExecuteCommandError(t *testing.T) {
115114
require.ErrorIs(t, err, exec.ErrNotFound)
116115
}
117116

118-
func TestSetSdnRemoteArpMacAddress_hnsNotEnabled(t *testing.T) {
119-
mockExecClient := NewMockExecClient(false)
120-
// testing skip setting SdnRemoteArpMacAddress when hns not enabled
121-
mockExecClient.SetPowershellCommandResponder(func(_ string) (string, error) {
122-
return "False", nil
123-
})
124-
err := SetSdnRemoteArpMacAddress(mockExecClient)
125-
assert.NoError(t, err)
126-
assert.Equal(t, false, sdnRemoteArpMacAddressSet)
127-
128-
// testing the scenario when there is an error in checking if hns is enabled or not
129-
mockExecClient.SetPowershellCommandResponder(func(_ string) (string, error) {
130-
return "", errTestFailure
131-
})
132-
err = SetSdnRemoteArpMacAddress(mockExecClient)
133-
assert.ErrorAs(t, err, &errTestFailure)
134-
assert.Equal(t, false, sdnRemoteArpMacAddressSet)
135-
}
136-
137-
func TestSetSdnRemoteArpMacAddress_hnsEnabled(t *testing.T) {
138-
mockExecClient := NewMockExecClient(false)
139-
// happy path
140-
mockExecClient.SetPowershellCommandResponder(func(cmd string) (string, error) {
141-
if strings.Contains(cmd, "Test-Path") {
142-
return "True", nil
143-
}
144-
return "", nil
145-
})
146-
err := SetSdnRemoteArpMacAddress(mockExecClient)
147-
assert.NoError(t, err)
148-
assert.Equal(t, true, sdnRemoteArpMacAddressSet)
149-
// reset sdnRemoteArpMacAddressSet
150-
sdnRemoteArpMacAddressSet = false
151-
}
152-
153117
func TestFetchPnpIDMapping(t *testing.T) {
154118
mockExecClient := NewMockExecClient(false)
155119
// happy path

test/validate/validate.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ func (v *Validator) ValidateStateFile(ctx context.Context) error {
124124
}
125125

126126
func (v *Validator) validateIPs(ctx context.Context, stateFileIps stateFileIpsFunc, cmd []string, checkType, namespace, labelSelector, containerName string) error {
127-
log.Printf("Validating %s state file", checkType)
127+
log.Printf("Validating %s state file for %s on %s", checkType, v.cni, v.os)
128128
nodes, err := acnk8s.GetNodeListByLabelSelector(ctx, v.clientset, nodeSelectorMap[v.os])
129129
if err != nil {
130130
return errors.Wrapf(err, "failed to get node list")

0 commit comments

Comments
 (0)