Skip to content

Commit

Permalink
feat: tests for status util funtions
Browse files Browse the repository at this point in the history
Signed-off-by: Bhoopesh <[email protected]>
  • Loading branch information
bhoopesh369 committed Oct 25, 2024
1 parent 9fd0b45 commit 5b861ce
Show file tree
Hide file tree
Showing 8 changed files with 221 additions and 71 deletions.
8 changes: 4 additions & 4 deletions sztp-agent/pkg/secureagent/configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
func (a *Agent) copyConfigurationFile() error {
log.Println("[INFO] Starting the Copy Configuration.")
_ = a.doReportProgress(ProgressTypeConfigInitiated, "Configuration Initiated")
_ = a.UpdateAndSaveStatus("config", true, "")
_ = a.updateAndSaveStatus("config", true, "")
// Copy the configuration file to the device
file, err := os.Create(ARTIFACTS_PATH + a.BootstrapServerOnboardingInfo.IetfSztpConveyedInfoOnboardingInformation.InfoTimestampReference + "-config")
if err != nil {
Expand All @@ -37,7 +37,7 @@ func (a *Agent) copyConfigurationFile() error {
}
log.Println("[INFO] Configuration file copied successfully")
_ = a.doReportProgress(ProgressTypeConfigComplete, "Configuration Complete")
_ = a.UpdateAndSaveStatus("config", false, "")
_ = a.updateAndSaveStatus("config", false, "")
return nil
}

Expand All @@ -58,7 +58,7 @@ func (a *Agent) launchScriptsConfiguration(typeOf string) error {
}
log.Println("[INFO] Starting the " + scriptName + "-configuration.")
_ = a.doReportProgress(reportStart, "Report starting")
_ = a.UpdateAndSaveStatus(scriptName+"-script", true, "")
_ = a.updateAndSaveStatus(scriptName+"-script", true, "")
// nolint:gosec
file, err := os.Create(ARTIFACTS_PATH + a.BootstrapServerOnboardingInfo.IetfSztpConveyedInfoOnboardingInformation.InfoTimestampReference + scriptName + "configuration.sh")
if err != nil {
Expand Down Expand Up @@ -92,7 +92,7 @@ func (a *Agent) launchScriptsConfiguration(typeOf string) error {
}
log.Println(string(out)) // remove it
_ = a.doReportProgress(reportEnd, "Report end")
_ = a.UpdateAndSaveStatus(scriptName+"-script", false, "")
_ = a.updateAndSaveStatus(scriptName+"-script", false, "")
log.Println("[INFO] " + scriptName + "-Configuration script executed successfully")
return nil
}
8 changes: 4 additions & 4 deletions sztp-agent/pkg/secureagent/daemon.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ const (

// RunCommandDaemon runs the command in the background
func (a *Agent) RunCommandDaemon() error {
if err := a.PrepareStatus(); err != nil {
if err := a.prepareStatus(); err != nil {
log.Println("failed to prepare status: ", err)
return err
}
Expand All @@ -50,7 +50,7 @@ func (a *Agent) RunCommandDaemon() error {
}

func (a *Agent) performBootstrapSequence() error {
_ = a.UpdateAndSaveStatus("bootstrap", true, "")
_ = a.updateAndSaveStatus("bootstrap", true, "")
var err error
err = a.discoverBootstrapURLs()
if err != nil {
Expand Down Expand Up @@ -81,7 +81,7 @@ func (a *Agent) performBootstrapSequence() error {
return err
}
_ = a.doReportProgress(ProgressTypeBootstrapComplete, "Bootstrap Complete")
_ = a.UpdateAndSaveStatus("bootstrap", false, "")
_ = a.updateAndSaveStatus("bootstrap", false, "")
return nil
}

Expand Down Expand Up @@ -148,7 +148,7 @@ func (a *Agent) doRequestBootstrapServerOnboardingInfo() error {
}
log.Println("[INFO] Response retrieved successfully")
_ = a.doReportProgress(ProgressTypeBootstrapInitiated, "Bootstrap Initiated")
_ = a.UpdateAndSaveStatus("bootstrap", true, "")
_ = a.updateAndSaveStatus("bootstrap", true, "")
crypto := res.IetfSztpBootstrapServerOutput.ConveyedInformation
newVal, err := base64.StdEncoding.DecodeString(crypto)
if err != nil {
Expand Down
4 changes: 2 additions & 2 deletions sztp-agent/pkg/secureagent/image.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import (
func (a *Agent) downloadAndValidateImage() error {
log.Printf("[INFO] Starting the Download Image: %v", a.BootstrapServerOnboardingInfo.IetfSztpConveyedInfoOnboardingInformation.BootImage.DownloadURI)
_ = a.doReportProgress(ProgressTypeBootImageInitiated, "BootImage Initiated")
_ = a.UpdateAndSaveStatus("boot-image", true, "")
_ = a.updateAndSaveStatus("boot-image", true, "")
// Download the image from DownloadURI and save it to a file
a.BootstrapServerOnboardingInfo.IetfSztpConveyedInfoOnboardingInformation.InfoTimestampReference = fmt.Sprintf("%8d", time.Now().Unix())
for i, item := range a.BootstrapServerOnboardingInfo.IetfSztpConveyedInfoOnboardingInformation.BootImage.DownloadURI {
Expand Down Expand Up @@ -79,7 +79,7 @@ func (a *Agent) downloadAndValidateImage() error {
}
log.Println("[INFO] Checksum verified successfully")
_ = a.doReportProgress(ProgressTypeBootImageComplete, "BootImage Complete")
_ = a.UpdateAndSaveStatus("boot-image", false, "")
_ = a.updateAndSaveStatus("boot-image", false, "")
return nil
default:
return errors.New("unsupported hash algorithm")
Expand Down
2 changes: 1 addition & 1 deletion sztp-agent/pkg/secureagent/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import "log"
// RunCommand runs the command in the background
func (a *Agent) RunCommand() error {
log.Println("runCommand started")
if err := a.PrepareStatus(); err != nil {
if err := a.prepareStatus(); err != nil {
log.Println("failed to prepare status: ", err)
return err
}
Expand Down
67 changes: 8 additions & 59 deletions sztp-agent/pkg/secureagent/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ func (a *Agent) loadStatusFile() (*Status, error) {
return &status, nil
}

func (a *Agent) UpdateAndSaveStatus(stage string, isStart bool, errMsg string) error {
func (a *Agent) updateAndSaveStatus(stage string, isStart bool, errMsg string) error {
status, err := a.loadStatusFile()
if err != nil {
fmt.Println("Creating a new status file.")
Expand Down Expand Up @@ -143,57 +143,6 @@ func (a *Agent) saveResult(result *Result) error {
return saveToFile(result, a.GetResultFilePath())
}

// EnsureDirExists checks if a directory exists, and creates it if it doesn't.
func EnsureDirExists(dir string) error {
if _, err := os.Stat(dir); os.IsNotExist(err) {
err := os.MkdirAll(dir, 0755) // Create the directory with appropriate permissions
if err != nil {
return fmt.Errorf("failed to create directory %s: %v", dir, err)
}
}
return nil
}

// EnsureFile ensures that a file exists; creates it if it does not.
func EnsureFileExists(filePath string) error {
// Ensure the directory exists
dir := filepath.Dir(filePath)
if err := EnsureDirExists(dir); err != nil {
return err
}

// Check if the file already exists
if _, err := os.Stat(filePath); os.IsNotExist(err) {
// File does not exist, create it
file, err := os.Create(filePath)
if err != nil {
return fmt.Errorf("failed to create file %s: %v", filePath, err)
}
defer file.Close()
fmt.Printf("File %s created successfully.\n", filePath)
} else {
fmt.Printf("File %s already exists.\n", filePath)
}
return nil
}

// CreateSymlink creates a symlink for a file from target to link location.
func CreateSymlink(targetFile, linkFile string) error {
// Ensure the directory for the symlink exists
linkDir := filepath.Dir(linkFile)
if err := EnsureDirExists(linkDir); err != nil {
return err
}

// Remove any existing symlink
if _, err := os.Lstat(linkFile); err == nil {
os.Remove(linkFile)
}

// Create a new symlink
return os.Symlink(targetFile, linkFile)
}

// RunCommandStatus runs the command in the background
func (a *Agent) RunCommandStatus() error {
log.Println("RunCommandStatus")
Expand All @@ -207,38 +156,38 @@ func (a *Agent) RunCommandStatus() error {
return nil
}

func (a *Agent) PrepareStatus() error {
func (a *Agent) prepareStatus() error {
log.Println("prepareStatus")

// Ensure /run/sztp directory exists
if err := EnsureDirExists(a.GetSymLinkDir()); err != nil {
if err := ensureDirExists(a.GetSymLinkDir()); err != nil {
fmt.Printf("Failed to create directory %s: %v\n", a.GetSymLinkDir(), err)
return err
}

if err := EnsureFileExists(a.GetStatusFilePath()); err != nil {
if err := ensureFileExists(a.GetStatusFilePath()); err != nil {
return err
}
if err := EnsureFileExists(a.GetResultFilePath()); err != nil {
if err := ensureFileExists(a.GetResultFilePath()); err != nil {
return err
}

statusSymlinkPath := filepath.Join(a.GetSymLinkDir(), "status.json")
resultSymlinkPath := filepath.Join(a.GetSymLinkDir(), "result.json")

// Create symlinks for status.json and result.json
if err := CreateSymlink(a.GetStatusFilePath(), statusSymlinkPath); err != nil {
if err := createSymlink(a.GetStatusFilePath(), statusSymlinkPath); err != nil {
fmt.Printf("Failed to create symlink for status.json: %v\n", err)
return err
}
if err := CreateSymlink(a.GetResultFilePath(), resultSymlinkPath); err != nil {
if err := createSymlink(a.GetResultFilePath(), resultSymlinkPath); err != nil {
fmt.Printf("Failed to create symlink for result.json: %v\n", err)
return err
}

fmt.Println("Symlinks created successfully.")

if err := a.UpdateAndSaveStatus("init", true, ""); err != nil {
if err := a.updateAndSaveStatus("init", true, ""); err != nil {
return err
}

Expand Down
2 changes: 1 addition & 1 deletion sztp-agent/pkg/secureagent/status_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ func TestAgent_RunCommandStatus(t *testing.T) {
ResultFilePath: tt.fields.ResultFilePath,
SymLinkDir: tt.fields.SymLinkDir,
}
a.PrepareStatus()
a.prepareStatus()
if err := a.RunCommandStatus(); (err != nil) != tt.wantErr {
t.Errorf("RunCommandStatus() error = %v, wantErr %v", err, tt.wantErr)
}
Expand Down
51 changes: 51 additions & 0 deletions sztp-agent/pkg/secureagent/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,3 +106,54 @@ func saveToFile(data interface{}, filePath string) error {
// Atomic move of temp file to replace the original.
return os.Rename(tempPath, filePath)
}

// EnsureDirExists checks if a directory exists, and creates it if it doesn't.
func ensureDirExists(dir string) error {
if _, err := os.Stat(dir); os.IsNotExist(err) {
err := os.MkdirAll(dir, 0755) // Create the directory with appropriate permissions
if err != nil {
return fmt.Errorf("failed to create directory %s: %v", dir, err)
}
}
return nil
}

// EnsureFile ensures that a file exists; creates it if it does not.
func ensureFileExists(filePath string) error {
// Ensure the directory exists
dir := filepath.Dir(filePath)
if err := ensureDirExists(dir); err != nil {
return err
}

// Check if the file already exists
if _, err := os.Stat(filePath); os.IsNotExist(err) {
// File does not exist, create it
file, err := os.Create(filePath)
if err != nil {
return fmt.Errorf("failed to create file %s: %v", filePath, err)
}
defer file.Close()
fmt.Printf("File %s created successfully.\n", filePath)
} else {
fmt.Printf("File %s already exists.\n", filePath)
}
return nil
}

// CreateSymlink creates a symlink for a file from target to link location.
func createSymlink(targetFile, linkFile string) error {
// Ensure the directory for the symlink exists
linkDir := filepath.Dir(linkFile)
if err := ensureDirExists(linkDir); err != nil {
return err
}

// Remove any existing symlink
if _, err := os.Lstat(linkFile); err == nil {
os.Remove(linkFile)
}

// Create a new symlink
return os.Symlink(targetFile, linkFile)
}
Loading

0 comments on commit 5b861ce

Please sign in to comment.