Adds check for tmp dir and create if missing

also test for function
This commit is contained in:
Tom Whiston 2018-02-15 21:29:03 +01:00
parent 26ac51bacb
commit 8aeaf7507c
2 changed files with 87 additions and 0 deletions

View File

@ -59,6 +59,13 @@ func (t *task) prepareRun() {
}() }()
t.log("Preparing: " + strconv.Itoa(t.task.ID)) t.log("Preparing: " + strconv.Itoa(t.task.ID))
err := checkTmpDir(util.Config.TmpPath)
if err != nil {
t.log("Creating tmp dir failed: " + err.Error())
t.fail()
return
}
if err := t.populateDetails(); err != nil { if err := t.populateDetails(); err != nil {
t.log("Error: " + err.Error()) t.log("Error: " + err.Error())
@ -439,3 +446,15 @@ func (t *task) envVars(home string, pwd string, gitSSHCommand *string) []string
return env return env
} }
// checkTmpDir checks to see if the temporary directory exists
// and if it does not attempts to create it
func checkTmpDir(path string) error {
var err error = nil
if _, err := os.Stat(path); err != nil {
if os.IsNotExist(err) {
return os.MkdirAll(path, os.FileMode(int(0640)))
}
}
return err
}

68
api/tasks/runner_test.go Normal file
View File

@ -0,0 +1,68 @@
package tasks
import (
"testing"
"math/rand"
"time"
"os"
"log"
)
func TestCheckTmpDir(t *testing.T) {
//It should be able to create a random dir in /tmp
dirName := os.TempDir()+ "/" + randString(rand.Intn(10 - 4) + 4)
err := checkTmpDir(dirName)
if err != nil {
t.Fatal(err)
}
//checking again for this directory should return no error, as it exists
err = checkTmpDir(dirName)
if err != nil {
t.Fatal(err)
}
err = os.Chmod(dirName,os.FileMode(int(0550)))
if err != nil {
t.Fatal(err)
}
err = checkTmpDir(dirName+"/noway")
if err == nil {
t.Fatal("You should not be able to write in this folder, causing an error")
}
err = os.Remove(dirName)
if err != nil {
t.Log(err)
}
}
//HELPERS
//https://stackoverflow.com/questions/22892120/how-to-generate-a-random-string-of-a-fixed-length-in-golang
var src = rand.NewSource(time.Now().UnixNano())
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
const (
letterIdxBits = 6 // 6 bits to represent a letter index
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
)
func randString(n int) string {
b := make([]byte, n)
// A src.Int63() generates 63 random bits, enough for letterIdxMax characters!
for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = src.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
b[i] = letterBytes[idx]
i--
}
cache >>= letterIdxBits
remain--
}
return string(b)
}