Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrate system API group to library model #244

Merged
merged 1 commit into from
Oct 13, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 83 additions & 0 deletions integrationtests/system_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,12 @@ import (
"strings"
"testing"

system "github.com/kubernetes-csi/csi-proxy/pkg/system"
systemapi "github.com/kubernetes-csi/csi-proxy/pkg/system/api"

"github.com/kubernetes-csi/csi-proxy/client/api/system/v1alpha1"
v1alpha1client "github.com/kubernetes-csi/csi-proxy/client/groups/system/v1alpha1"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
Expand Down Expand Up @@ -99,6 +103,85 @@ func TestServiceCommands(t *testing.T) {

}

func TestSystem(t *testing.T) {
t.Run("GetBIOSSerialNumber", func(t *testing.T) {
client, err := system.New(systemapi.New())
require.Nil(t, err)

request := &system.GetBIOSSerialNumberRequest{}
response, err := client.GetBIOSSerialNumber(context.TODO(), request)
require.Nil(t, err)
require.NotNil(t, response)

result, err := exec.Command("wmic", "bios", "get", "serialnumber").Output()
require.Nil(t, err)

t.Logf("The serial number is %s", response.SerialNumber)

resultString := string(result)
require.True(t, strings.Contains(resultString, response.SerialNumber))
})

t.Run("GetService", func(t *testing.T) {
const ServiceName = "MSiSCSI"
client, err := system.New(systemapi.New())
require.Nil(t, err)

// Make sure service is stopped
_, err = runPowershellCmd(t, fmt.Sprintf(`Stop-Service -Name "%s"`, ServiceName))
require.NoError(t, err)
assertServiceStopped(t, ServiceName)

request := &system.GetServiceRequest{Name: ServiceName}
response, err := client.GetService(context.TODO(), request)
require.NoError(t, err)
require.NotNil(t, response)

out, err := runPowershellCmd(t, fmt.Sprintf(`Get-Service -Name "%s" `+
`| Select-Object DisplayName, Status, StartType | ConvertTo-Json`,
ServiceName))
require.NoError(t, err)

var serviceInfo = struct {
DisplayName string `json:"DisplayName"`
Status uint32 `json:"Status"`
StartType uint32 `json:"StartType"`
}{}

err = json.Unmarshal([]byte(out), &serviceInfo)
require.NoError(t, err, "failed unmarshalling json out=%v", out)

assert.Equal(t, serviceInfo.Status, uint32(response.Status))
assert.Equal(t, system.SERVICE_STATUS_STOPPED, response.Status)
assert.Equal(t, serviceInfo.StartType, uint32(response.StartType))
assert.Equal(t, serviceInfo.DisplayName, response.DisplayName)
})

t.Run("Stop/Start Service", func(t *testing.T) {
const ServiceName = "MSiSCSI"
client, err := system.New(systemapi.New())
require.Nil(t, err)

_, err = runPowershellCmd(t, fmt.Sprintf(`Stop-Service -Name "%s"`, ServiceName))
require.NoError(t, err)
assertServiceStopped(t, ServiceName)

startReq := &system.StartServiceRequest{Name: ServiceName}
startResp, err := client.StartService(context.TODO(), startReq)

assert.NoError(t, err)
assert.NotNil(t, startResp)
assertServiceStarted(t, ServiceName)

stopReq := &system.StopServiceRequest{Name: ServiceName}
stopResp, err := client.StopService(context.TODO(), stopReq)

assert.NoError(t, err)
assert.NotNil(t, stopResp)
assertServiceStopped(t, ServiceName)
})
}

func assertServiceStarted(t *testing.T, serviceName string) {
assertServiceStatus(t, serviceName, "Running")
}
Expand Down
88 changes: 88 additions & 0 deletions pkg/system/api/api.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package api

import (
"encoding/json"
"fmt"
"os/exec"
"strings"

"github.com/kubernetes-csi/csi-proxy/pkg/utils"
)

// Implements the System OS API calls. All code here should be very simple
// pass-through to the OS APIs. Any logic around the APIs should go in
// pkg/system/system.go so that logic can be easily unit-tested
// without requiring specific OS environments.

type API interface {
GetBIOSSerialNumber() (string, error)
GetService(name string) (*ServiceInfo, error)
StartService(name string) error
StopService(name string, force bool) error
}

type systemAPI struct{}

func New() API {
return systemAPI{}
}

func (systemAPI) GetBIOSSerialNumber() (string, error) {
// Taken from Kubernetes vSphere cloud provider
// https://github.com/kubernetes/kubernetes/blob/103e926604de6f79161b78af3e792d0ed282bc06/staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_util_windows.go#L28
result, err := exec.Command("wmic", "bios", "get", "serialnumber").Output()
if err != nil {
return "", err
}
lines := strings.FieldsFunc(string(result), func(r rune) bool {
switch r {
case '\n', '\r':
return true
default:
return false
}
})
if len(lines) != 2 {
return "", fmt.Errorf("received unexpected value retrieving host uuid: %q", string(result))
}
return lines[1], nil
}

func (systemAPI) GetService(name string) (*ServiceInfo, error) {
script := `Get-Service -Name $env:ServiceName | Select-Object DisplayName, Status, StartType | ` +
`ConvertTo-JSON`
cmdEnv := fmt.Sprintf("ServiceName=%s", name)
out, err := utils.RunPowershellCmd(script, cmdEnv)
if err != nil {
return nil, fmt.Errorf("error querying service name=%s. cmd: %s, output: %s, error: %v", name, script, string(out), err)
}

var serviceInfo ServiceInfo
err = json.Unmarshal(out, &serviceInfo)
if err != nil {
return nil, err
}

return &serviceInfo, nil
}

func (systemAPI) StartService(name string) error {
script := `Start-Service -Name $env:ServiceName`
cmdEnv := fmt.Sprintf("ServiceName=%s", name)
out, err := utils.RunPowershellCmd(script, cmdEnv)
if err != nil {
return fmt.Errorf("error starting service name=%s. cmd: %s, output: %s, error: %v", name, script, string(out), err)
}

return nil
}

func (systemAPI) StopService(name string, force bool) error {
script := `Stop-Service -Name $env:ServiceName -Force:$([System.Convert]::ToBoolean($env:Force))`
out, err := utils.RunPowershellCmd(script, fmt.Sprintf("ServiceName=%s", name), fmt.Sprintf("Force=%t", force))
if err != nil {
return fmt.Errorf("error stopping service name=%s. cmd: %s, output: %s, error: %v", name, script, string(out), err)
}

return nil
}
12 changes: 12 additions & 0 deletions pkg/system/api/types.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package api
mauriciopoppe marked this conversation as resolved.
Show resolved Hide resolved

type ServiceInfo struct {
// Service display name
DisplayName string `json:"DisplayName"`

// Service start type
StartType uint32 `json:"StartType"`

// Service status
Status uint32 `json:"Status"`
}
80 changes: 80 additions & 0 deletions pkg/system/system.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package system

import (
"context"

systemapi "github.com/kubernetes-csi/csi-proxy/pkg/system/api"
"k8s.io/klog/v2"
)

type System struct {
hostAPI systemapi.API
}

type Interface interface {
GetBIOSSerialNumber(context.Context, *GetBIOSSerialNumberRequest) (*GetBIOSSerialNumberResponse, error)
GetService(context.Context, *GetServiceRequest) (*GetServiceResponse, error)
StartService(context.Context, *StartServiceRequest) (*StartServiceResponse, error)
StopService(context.Context, *StopServiceRequest) (*StopServiceResponse, error)
}

// check that System implements Interface
var _ Interface = &System{}

func New(hostAPI systemapi.API) (*System, error) {
return &System{
hostAPI: hostAPI,
}, nil
}

func (s *System) GetBIOSSerialNumber(context context.Context, request *GetBIOSSerialNumberRequest) (*GetBIOSSerialNumberResponse, error) {
klog.V(4).Infof("calling GetBIOSSerialNumber")
response := &GetBIOSSerialNumberResponse{}
serialNumber, err := s.hostAPI.GetBIOSSerialNumber()
if err != nil {
klog.Errorf("failed GetBIOSSerialNumber: %v", err)
return response, err
}

response.SerialNumber = serialNumber
return response, nil
}

func (s *System) GetService(context context.Context, request *GetServiceRequest) (*GetServiceResponse, error) {
klog.V(4).Infof("calling GetService name=%s", request.Name)
response := &GetServiceResponse{}
info, err := s.hostAPI.GetService(request.Name)
if err != nil {
klog.Errorf("failed GetService: %v", err)
return response, err
}

response.DisplayName = info.DisplayName
response.StartType = Startype(info.StartType)
response.Status = ServiceStatus(info.Status)
return response, nil
}

func (s *System) StartService(context context.Context, request *StartServiceRequest) (*StartServiceResponse, error) {
klog.V(4).Infof("calling StartService name=%s", request.Name)
response := &StartServiceResponse{}
err := s.hostAPI.StartService(request.Name)
if err != nil {
klog.Errorf("failed StartService: %v", err)
return response, err
}

return response, nil
}

func (s *System) StopService(context context.Context, request *StopServiceRequest) (*StopServiceResponse, error) {
klog.V(4).Infof("calling StopService name=%s", request.Name)
response := &StopServiceResponse{}
err := s.hostAPI.StopService(request.Name, request.Force)
if err != nil {
klog.Errorf("failed StopService: %v", err)
return response, err
}

return response, nil
}
70 changes: 70 additions & 0 deletions pkg/system/types.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package system

type GetBIOSSerialNumberRequest struct {
}

type GetBIOSSerialNumberResponse struct {
SerialNumber string
}

type StartServiceRequest struct {
// Service name (as listed in System\CCS\Services keys)
Name string
}

type StartServiceResponse struct {
// Intentionally empty
}

type StopServiceRequest struct {
// Service name (as listed in System\CCS\Services keys)
Name string

// Forces stopping of services that has dependent services
Force bool
}

type StopServiceResponse struct {
// Intentionally empty
}

type ServiceStatus uint32

const (
SERVICE_STATUS_UNKNOWN ServiceStatus = iota
SERVICE_STATUS_STOPPED
SERVICE_STATUS_START_PENDING
SERVICE_STATUS_STOP_PENDING
SERVICE_STATUS_RUNNING
SERVICE_STATUS_CONTINUE_PENDING
SERVICE_STATUS_PAUSE_PENDING
SERVICE_STATUS_PAUSED
)

type Startype uint32

const (
START_TYPE_BOOT Startype = iota
START_TYPE_SYSTEM
START_TYPE_AUTOMATIC
START_TYPE_MANUAL
START_TYPE_DISABLED
)

type GetServiceRequest struct {
// Service name (as listed in System\CCS\Services keys)
Name string
}

type GetServiceResponse struct {
// Service display name
DisplayName string

// Service start type.
// Used to control whether a service will start on boot, and if so on which
// boot phase.
StartType Startype

// Service status, e.g. stopped, running, paused
Status ServiceStatus
}