Skip to content

Commit 925dae8

Browse files
committed
Adds more unit tests
1 parent fc68763 commit 925dae8

13 files changed

Lines changed: 1227 additions & 98 deletions

File tree

internal/cleanup/cleanup.go

Lines changed: 25 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,11 @@ package cleanup
22

33
import (
44
"fmt"
5+
"os"
56
"path/filepath"
7+
"strconv"
68

9+
"github.com/!azure/azure-extension-platform/pkg/utils"
710
"github.com/Azure/run-command-handler-linux/internal/constants"
811
"github.com/Azure/run-command-handler-linux/internal/types"
912
"github.com/Azure/run-command-handler-linux/pkg/linuxutils"
@@ -38,28 +41,28 @@ func deleteAllScriptsAndSettings(ctx *log.Context, metadata types.RCMetadata, h
3841
}
3942

4043
func deleteScriptsAndSettingsExceptMostRecent(ctx *log.Context, metadata types.RCMetadata, h types.HandlerEnvironment, runAsUser string) {
41-
/* runtimeSettingsRegexFormat := metadata.ExtName + ".\\d+.settings"
42-
runtimeSettingsLastSeqNumFormat := metadata.ExtName + ".%d.settings"
44+
runtimeSettingsRegexFormat := metadata.ExtName + ".\\d+.settings"
45+
runtimeSettingsLastSeqNumFormat := metadata.ExtName + ".%d.settings"
4346

44-
// check if directory exists
45-
_, err := os.Open(metadata.DownloadPath)
46-
if err == nil {
47-
err := utils.TryClearExtensionScriptsDirectoriesAndSettingsFilesExceptMostRecent(metadata.DownloadPath, h.HandlerEnvironment.ConfigFolder, "",
48-
uint64(metadata.SeqNum), runtimeSettingsRegexFormat, runtimeSettingsLastSeqNumFormat)
49-
if err != nil {
50-
ctx.Log("event", "could not clear settings and script files", "error", err)
51-
}
52-
} else {
53-
ctx.Log("message", "directory does not exist. Skipping cleanup")
54-
}
47+
// check if directory exists
48+
_, err := os.Open(metadata.DownloadPath)
49+
if err == nil {
50+
err := utils.TryClearExtensionScriptsDirectoriesAndSettingsFilesExceptMostRecent(metadata.DownloadPath, h.HandlerEnvironment.ConfigFolder, "",
51+
uint64(metadata.SeqNum), runtimeSettingsRegexFormat, runtimeSettingsLastSeqNumFormat)
52+
if err != nil {
53+
ctx.Log("event", "could not clear settings and script files", "error", err)
54+
}
55+
} else {
56+
ctx.Log("message", "directory does not exist. Skipping cleanup")
57+
}
5558

56-
if runAsUser != "" {
57-
runAsDownloadParent := filepath.Join(fmt.Sprintf(constants.RunAsDir, runAsUser), metadata.DownloadDir)
58-
seqNumString := strconv.Itoa(metadata.SeqNum)
59-
ctx.Log("message", "removing all files from the download 'runas' directory "+runAsDownloadParent)
60-
err = utils.TryDeleteDirectoriesExcept(runAsDownloadParent, seqNumString)
61-
if err != nil {
62-
ctx.Log("event", "could not clear runas script")
63-
}
64-
} */
59+
if runAsUser != "" {
60+
runAsDownloadParent := filepath.Join(fmt.Sprintf(constants.RunAsDir, runAsUser), metadata.DownloadDir)
61+
seqNumString := strconv.Itoa(metadata.SeqNum)
62+
ctx.Log("message", "removing all files from the download 'runas' directory "+runAsDownloadParent)
63+
err = utils.TryDeleteDirectoriesExcept(runAsDownloadParent, seqNumString)
64+
if err != nil {
65+
ctx.Log("event", "could not clear runas script")
66+
}
67+
}
6568
}

internal/cmds/cmds.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -828,7 +828,7 @@ func downloadArtifacts(ctx *log.Context, dir string, cfg *handlersettings.Handle
828828
filePath, err := files.DownloadAndProcessArtifact(ctx, dir, &artifacts[i])
829829
if err != nil {
830830
ctx.Log("events", "Failed to download artifact", err, "artifact", artifacts[i].ArtifactUri)
831-
return err
831+
return handlersettings.InternalWrapErrorWithClarification(err, "Failed to download artifact")
832832
}
833833

834834
ctx.Log("event", "Downloaded artifact complete", "file", filePath)

internal/cmds/cmds_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -582,7 +582,7 @@ func Test_downloadArtifactsFail(t *testing.T) {
582582
})
583583

584584
require.NotNil(t, err)
585-
require.Contains(t, err.Error(), "failed to download artifact")
585+
require.Contains(t, err.Error(), "Failed to download artifact")
586586
}
587587

588588
func Test_downloadArtifacts(t *testing.T) {

internal/exec/exec.go

Lines changed: 27 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,18 @@ import (
2020
"github.com/pkg/errors"
2121
)
2222

23+
var (
24+
fnIoCopy = io.Copy
25+
fnOsChMod = os.Chmod
26+
fnOsChown = os.Chown
27+
fnOsCreate = os.Create
28+
fnOsMkDirAll = os.MkdirAll
29+
fnOsOpenFile = os.OpenFile
30+
fnOsSetEnv = os.Setenv
31+
fnRunCommand = runCommand
32+
fnUserLookup = user.Lookup
33+
)
34+
2335
// Exec runs the given cmd in /bin/sh, saves its stdout/stderr streams to
2436
// the specified files. It waits until the execution terminates.
2537
//
@@ -54,24 +66,24 @@ func Exec(ctx *log.Context, cmd, workdir string, stdout, stderr io.WriteCloser,
5466
runAsScriptDirectoryPath := filepath.Dir(runAsScriptFilePath) // Get directory of runAsScript that doesn't exist yet
5567

5668
// Create runAsScriptDirectoryPath and its intermediate directories if they do not exist
57-
os.MkdirAll(runAsScriptDirectoryPath, 0777)
69+
fnOsMkDirAll(runAsScriptDirectoryPath, 0777)
5870

5971
/// Copy source script at scriptPath to runAsScriptDirectoryPath
6072
// Get reference to source script by opening it
61-
sourceScriptFile, sourceScriptFileOpenError := os.OpenFile(scriptPath, os.O_RDONLY, 0400)
73+
sourceScriptFile, sourceScriptFileOpenError := fnOsOpenFile(scriptPath, os.O_RDONLY, 0400)
6274
if sourceScriptFileOpenError != nil {
6375
errMessage := fmt.Sprintf("Failed to open source script. Contact ICM team AzureRT\\Extensions for this service error. Source script file is '%s'", scriptPath)
6476
ctx.Log("message", errMessage)
6577
return constants.Internal_RunAsOpenSourceScriptFileFailed, vmextension.NewErrorWithClarification(constants.Internal_RunAsOpenSourceScriptFileFailed, sourceScriptFileOpenError)
6678
}
6779

68-
destScriptFile, destScriptCreateError := os.Create(runAsScriptFilePath)
80+
destScriptFile, destScriptCreateError := fnOsCreate(runAsScriptFilePath)
6981
if destScriptCreateError != nil {
7082
errMessage := fmt.Sprintf("Failed to create script for Run As in Run As directory. Contact ICM team AzureRT\\Extensions for this service error. Destination runAs script file is '%s'", runAsScriptFilePath)
7183
ctx.Log("message", errMessage)
7284
return constants.Internal_RunAsOpenSourceScriptFileFailed, vmextension.NewErrorWithClarification(constants.Internal_RunAsOpenSourceScriptFileFailed, destScriptCreateError)
7385
}
74-
_, runAsScriptCopyError := io.Copy(destScriptFile, sourceScriptFile)
86+
_, runAsScriptCopyError := fnIoCopy(destScriptFile, sourceScriptFile)
7587
if runAsScriptCopyError != nil {
7688
errMessage := fmt.Sprintf("Failed to copy script file '%s' to Run As path '%s'. Contact ICM team AzureRT\\Extensions for this service error.", scriptPath, runAsScriptFilePath)
7789
ctx.Log("message", errMessage)
@@ -81,7 +93,7 @@ func Exec(ctx *log.Context, cmd, workdir string, stdout, stderr io.WriteCloser,
8193
destScriptFile.Close()
8294

8395
// Provide read and execute permissions to RunAsUser on .sh file at runAsScriptFilePath
84-
lookedUpUser, lookupUserError := user.Lookup(cfg.PublicSettings.RunAsUser)
96+
lookedUpUser, lookupUserError := fnUserLookup(cfg.PublicSettings.RunAsUser)
8597
if lookupUserError != nil {
8698
errMessage := fmt.Sprintf("Failed to lookup RunAs user '%s'. Looks like user does not exist. For RunAs to work properly, contact admin of VM and make sure RunAs user is added on the VM and user has access to resources accessed by the Run Command (Directories, Files, Network etc.). Refer: https://aka.ms/RunCommandManagedLinux", cfg.PublicSettings.RunAsUser)
8799
ctx.Log("message", errMessage)
@@ -95,14 +107,14 @@ func Exec(ctx *log.Context, cmd, workdir string, stdout, stderr io.WriteCloser,
95107
return constants.Internal_RunAsLookupUserUidFailed, vmextension.NewErrorWithClarification(constants.Internal_RunAsLookupUserUidFailed, lookedUpUserUidErr)
96108
}
97109

98-
runAsScriptChownError := os.Chown(runAsScriptFilePath, lookedUpUserUid, os.Getegid())
110+
runAsScriptChownError := fnOsChown(runAsScriptFilePath, lookedUpUserUid, os.Getegid())
99111
if runAsScriptChownError != nil {
100112
errMessage := fmt.Sprintf("Failed to change owner of file '%s' to RunAs user '%s'. Contact ICM team AzureRT\\Extensions for this service error.", runAsScriptFilePath, cfg.PublicSettings.RunAsUser)
101113
ctx.Log("message", errMessage)
102114
return constants.Internal_RunAsScriptFileChangeOwnerFailed, vmextension.NewErrorWithClarification(constants.Internal_RunAsScriptFileChangeOwnerFailed, runAsScriptChownError)
103115
}
104116

105-
runAsScriptChmodError := os.Chmod(runAsScriptFilePath, 0550)
117+
runAsScriptChmodError := fnOsChMod(runAsScriptFilePath, 0550)
106118
if runAsScriptChmodError != nil {
107119
errMessage := fmt.Sprintf("Failed to change permissions to execute for file '%s' for RunAs user '%s'. Contact ICM team AzureRT\\Extensions for this service error.", runAsScriptFilePath, cfg.PublicSettings.RunAsUser)
108120
ctx.Log("message", errMessage)
@@ -128,7 +140,7 @@ func Exec(ctx *log.Context, cmd, workdir string, stdout, stderr io.WriteCloser,
128140
command.Dir = workdir
129141
command.Stdout = stdout
130142
command.Stderr = stderr
131-
err = command.Run()
143+
err = fnRunCommand(command)
132144
if err != nil {
133145
exitErr, ok := err.(*exec.ExitError)
134146
if ok {
@@ -152,6 +164,10 @@ func Exec(ctx *log.Context, cmd, workdir string, stdout, stderr io.WriteCloser,
152164
return exitCode, nil
153165
}
154166

167+
func runCommand(command *exec.Cmd) error {
168+
return command.Run()
169+
}
170+
155171
func SetEnvironmentVariables(cfg *handlersettings.HandlerSettings) (string, error) {
156172
var err error
157173
commandArgs := ""
@@ -168,7 +184,7 @@ func SetEnvironmentVariables(cfg *handlersettings.HandlerSettings) (string, erro
168184
value := parameters[i].Value
169185
if value != "" {
170186
if name != "" { // Named parameters are set as environmental setting
171-
err = os.Setenv(name, value)
187+
err = fnOsSetEnv(name, value)
172188
} else { // Unnamed parameters go to command args
173189
commandArgs += " " + value
174190
}
@@ -188,11 +204,11 @@ func ExecCmdInDir(ctx *log.Context, scriptFilePath, workdir string, cfg *handler
188204

189205
stdoutFileName, stderrFileName := LogPaths(workdir)
190206

191-
outF, err := os.OpenFile(stdoutFileName, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600)
207+
outF, err := fnOsOpenFile(stdoutFileName, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600)
192208
if err != nil {
193209
return vmextension.NewErrorWithClarification(constants.FileSystem_OpenStandardOutFailed, fmt.Errorf("failed to open stdout file: %v", err)), constants.FileSystem_OpenStandardOutFailed
194210
}
195-
errF, err := os.OpenFile(stderrFileName, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600)
211+
errF, err := fnOsOpenFile(stderrFileName, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600)
196212
if err != nil {
197213
return vmextension.NewErrorWithClarification(constants.FileSystem_OpenStandardErrorFailed, fmt.Errorf("failed to open stderr file: %v", err)), constants.FileSystem_OpenStandardErrorFailed
198214
}

0 commit comments

Comments
 (0)