Merge branch 'master' into feature-config-golang

This commit is contained in:
Jose Diaz-Gonzalez
2017-10-04 19:04:31 -04:00
committed by GitHub
143 changed files with 4954 additions and 302 deletions

View File

@@ -1,11 +1,14 @@
package common
import (
"bufio"
"fmt"
"io/ioutil"
"os"
"os/exec"
"regexp"
"strings"
"unicode"
sh "github.com/codeskyblue/go-sh"
)
@@ -48,42 +51,24 @@ func (sc *ShellCmd) Execute() bool {
sc.Command.Stdout = os.Stdout
sc.Command.Stderr = os.Stderr
}
err := sc.Command.Run()
if err != nil {
if err := sc.Command.Run(); err != nil {
return false
}
return true
}
// VerifyAppName verifies app name format and app existence"
func VerifyAppName(appName string) (err error) {
dokkuRoot := MustGetEnv("DOKKU_ROOT")
appRoot := strings.Join([]string{dokkuRoot, appName}, "/")
_, err = os.Stat(appRoot)
if os.IsNotExist(err) {
return fmt.Errorf("App %s does not exist: %v\n", appName, err)
// Output is a lightweight wrapper around exec.Command.Output()
func (sc *ShellCmd) Output() ([]byte, error) {
env := os.Environ()
for k, v := range sc.Env {
env = append(env, fmt.Sprintf("%s=%s", k, v))
}
r, _ := regexp.Compile("^[a-z].*")
if !r.MatchString(appName) {
return fmt.Errorf("App name (%s) must begin with lowercase alphanumeric character\n", appName)
sc.Command.Env = env
if sc.ShowOutput {
sc.Command.Stdout = os.Stdout
sc.Command.Stderr = os.Stderr
}
return err
}
// MustGetEnv returns env variable or fails if it's not set
func MustGetEnv(key string) string {
value := os.Getenv(key)
if value == "" {
LogFail(fmt.Sprintf("%s not set!", key))
}
return value
}
// LogFail is the failure log formatter
// prints text to stderr and exits with status 1
func LogFail(text string) {
fmt.Fprintln(os.Stderr, fmt.Sprintf("FAILED: %s", text))
os.Exit(1)
return sc.Command.Output()
}
// GetDeployingAppImageName returns deploying image identifier for a given app, tag tuple. validate if tag is presented
@@ -135,14 +120,233 @@ func GetAppImageRepo(appName string) string {
return strings.Join([]string{"dokku", appName}, "/")
}
// ContainerIsRunning checks to see if a container is running
func ContainerIsRunning(containerID string) bool {
b, err := DockerInspect(containerID, "'{{.State.Running}}'")
if err != nil {
return false
}
return strings.TrimSpace(string(b[:])) == "true"
}
// DirectoryExists returns if a path exists and is a directory
func DirectoryExists(filePath string) bool {
fi, err := os.Stat(filePath)
if err != nil {
return false
}
return fi.IsDir()
}
// DockerInspect runs an inspect command with a given format against a container id
func DockerInspect(containerID, format string) (output string, err error) {
b, err := sh.Command("docker", "inspect", "--format", format, containerID).Output()
if err != nil {
return "", err
}
output = strings.TrimSpace(string(b[:]))
if strings.HasPrefix(output, "'") && strings.HasSuffix(output, "'") {
output = strings.TrimSuffix(strings.TrimPrefix(output, "'"), "'")
}
return
}
// DokkuApps returns a list of all local apps
func DokkuApps() (apps []string, err error) {
dokkuRoot := MustGetEnv("DOKKU_ROOT")
files, err := ioutil.ReadDir(dokkuRoot)
if err != nil {
err = fmt.Errorf("You haven't deployed any applications yet")
return
}
for _, f := range files {
appRoot := strings.Join([]string{dokkuRoot, f.Name()}, "/")
if !DirectoryExists(appRoot) {
continue
}
if f.Name() == "tls" || strings.HasPrefix(f.Name(), ".") {
continue
}
apps = append(apps, f.Name())
}
if len(apps) == 0 {
err = fmt.Errorf("You haven't deployed any applications yet")
return
}
return
}
// FileToSlice reads in all the lines from a file into a string slice
func FileToSlice(filePath string) (lines []string, err error) {
f, err := os.Open(filePath)
if err != nil {
return
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
text := strings.TrimSpace(scanner.Text())
if text == "" {
continue
}
lines = append(lines, text)
}
err = scanner.Err()
return
}
// FileExists returns if a path exists and is a file
func FileExists(filePath string) bool {
fi, err := os.Stat(filePath)
if err != nil {
return false
}
return fi.Mode().IsRegular()
}
// GetAppImageName returns image identifier for a given app, tag tuple. validate if tag is presented
func GetAppImageName(appName, imageTag, imageRepo string) (imageName string) {
err := VerifyAppName(appName)
if err != nil {
LogFail(err.Error())
}
if imageRepo == "" {
imageRepo = GetAppImageRepo(appName)
}
if imageTag == "" {
imageName = fmt.Sprintf("%v:latest", imageRepo)
} else {
imageName = fmt.Sprintf("%v:%v", imageRepo, imageTag)
if !VerifyImage(imageName) {
LogFail(fmt.Sprintf("app image (%s) not found", imageName))
}
}
return
}
// IsDeployed returns true if given app has a running container
func IsDeployed(appName string) bool {
dokkuRoot := MustGetEnv("DOKKU_ROOT")
appRoot := strings.Join([]string{dokkuRoot, appName}, "/")
files, err := ioutil.ReadDir(appRoot)
if err != nil {
return false
}
for _, f := range files {
if f.Name() == "CONTAINER" || strings.HasPrefix(f.Name(), "CONTAINER.") {
return true
}
}
return false
}
// IsImageHerokuishBased returns true if app image is based on herokuish
func IsImageHerokuishBased(image string) bool {
// circleci can't support --rm as they run lxc in lxc
dockerArgs := ""
if !FileExists("/home/ubuntu/.circlerc") {
dockerArgs = "--rm"
}
dockerGlobalArgs := os.Getenv("DOKKU_GLOBAL_RUN_ARGS")
parts := []string{"docker", "run", dockerGlobalArgs, "--entrypoint=\"/bin/sh\"", dockerArgs, image, "-c", "\"test -f /exec\""}
var dockerCmdParts []string
for _, str := range parts {
if str != "" {
dockerCmdParts = append(dockerCmdParts, str)
}
}
dockerCmd := NewShellCmd(strings.Join(dockerCmdParts, " "))
dockerCmd.ShowOutput = false
return dockerCmd.Execute()
}
// MustGetEnv returns env variable or fails if it's not set
func MustGetEnv(key string) (val string) {
val = os.Getenv(key)
if val == "" {
LogFail(fmt.Sprintf("%s not set!", key))
}
return
}
// ReadFirstLine gets the first line of a file that has contents and returns it
// if there are no contents, an empty string is returned
// will also return an empty string if the file does not exist
func ReadFirstLine(filename string) (text string) {
if !FileExists(filename) {
return
}
f, err := os.Open(filename)
if err != nil {
return
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
if text = strings.TrimSpace(scanner.Text()); text == "" {
continue
}
return
}
return
}
// StripInlineComments removes bash-style comment from input line
func StripInlineComments(text string) string {
bytes := []byte(text)
re := regexp.MustCompile("(?s)#.*")
bytes = re.ReplaceAll(bytes, nil)
return strings.TrimSpace(string(bytes))
}
// ToBool returns a bool value for a given string
func ToBool(s string) bool {
return s == "true"
}
// UcFirst uppercases the first character in a string
func UcFirst(str string) string {
for i, v := range str {
return string(unicode.ToUpper(v)) + str[i+1:]
}
return ""
}
// VerifyAppName verifies app name format and app existence"
func VerifyAppName(appName string) (err error) {
if appName == "" {
return fmt.Errorf("App name must not be null")
}
dokkuRoot := MustGetEnv("DOKKU_ROOT")
appRoot := strings.Join([]string{dokkuRoot, appName}, "/")
if !DirectoryExists(appRoot) {
return fmt.Errorf("app %s does not exist: %v", appName, err)
}
r, _ := regexp.Compile("^[a-z].*")
if !r.MatchString(appName) {
return fmt.Errorf("app name (%s) must begin with lowercase alphanumeric character", appName)
}
return err
}
// VerifyImage returns true if docker image exists in local repo
func VerifyImage(image string) bool {
imageCmd := NewShellCmd(strings.Join([]string{"docker inspect", image}, " "))
imageCmd.ShowOutput = false
if imageCmd.Execute() {
return true
}
return false
return imageCmd.Execute()
}
//PlugnTrigger fire the given plugn trigger with the given args

View File

@@ -1,38 +1,106 @@
package common
import (
"io/ioutil"
"os"
"strings"
"testing"
. "github.com/onsi/gomega"
)
func TestGetEnv(t *testing.T) {
var (
testAppName = "test-app-1"
testAppDir = strings.Join([]string{"/home/dokku/", testAppName}, "")
testEnvFile = strings.Join([]string{testAppDir, "/ENV"}, "")
testEnvLine = "export testKey=TESTING"
)
func setupTestApp() (err error) {
Expect(os.MkdirAll(testAppDir, 0644)).To(Succeed())
b := []byte(testEnvLine + "\n")
if err = ioutil.WriteFile(testEnvFile, b, 0644); err != nil {
return
}
return
}
func teardownTestApp() {
os.RemoveAll(testAppDir)
}
func TestCommonGetEnv(t *testing.T) {
RegisterTestingT(t)
Expect(MustGetEnv("DOKKU_ROOT")).To(Equal("/home/dokku"))
}
func TestGetAppImageRepo(t *testing.T) {
func TestCommonGetAppImageRepo(t *testing.T) {
RegisterTestingT(t)
Expect(GetAppImageRepo("testapp")).To(Equal("dokku/testapp"))
}
func TestVerifyImageInvalid(t *testing.T) {
func TestCommonVerifyImageInvalid(t *testing.T) {
RegisterTestingT(t)
Expect(VerifyImage("testapp")).To(Equal(false))
}
func TestVerifyAppNameInvalid(t *testing.T) {
func TestCommonVerifyAppNameInvalid(t *testing.T) {
RegisterTestingT(t)
err := VerifyAppName("1994testApp")
Expect(err).To(HaveOccurred())
}
func TestVerifyAppName(t *testing.T) {
func TestCommonVerifyAppName(t *testing.T) {
RegisterTestingT(t)
dir := "/home/dokku/testApp"
os.MkdirAll(dir, 0644)
err := VerifyAppName("testApp")
Expect(err).NotTo(HaveOccurred())
os.RemoveAll(dir)
Expect(setupTestApp()).To(Succeed())
Expect(VerifyAppName(testAppName)).To(Succeed())
teardownTestApp()
}
func TestCommonDokkuAppsError(t *testing.T) {
RegisterTestingT(t)
_, err := DokkuApps()
Expect(err).To(HaveOccurred())
}
func TestCommonDokkuApps(t *testing.T) {
RegisterTestingT(t)
Expect(setupTestApp()).To(Succeed())
apps, err := DokkuApps()
Expect(err).NotTo(HaveOccurred())
Expect(apps).To(HaveLen(1))
Expect(apps[0]).To(Equal(testAppName))
teardownTestApp()
}
func TestCommonFileToSlice(t *testing.T) {
RegisterTestingT(t)
Expect(setupTestApp()).To(Succeed())
lines, err := FileToSlice(testEnvFile)
Expect(err).NotTo(HaveOccurred())
Expect(lines).To(Equal([]string{testEnvLine}))
teardownTestApp()
}
func TestCommonFileExists(t *testing.T) {
RegisterTestingT(t)
Expect(setupTestApp()).To(Succeed())
Expect(FileExists(testEnvFile)).To(BeTrue())
teardownTestApp()
}
func TestCommonReadFirstLine(t *testing.T) {
RegisterTestingT(t)
line := ReadFirstLine(testEnvFile)
Expect(line).To(Equal(""))
Expect(setupTestApp()).To(Succeed())
line = ReadFirstLine(testEnvFile)
Expect(line).To(Equal(testEnvLine))
teardownTestApp()
}
func TestCommonStripInlineComments(t *testing.T) {
RegisterTestingT(t)
text := StripInlineComments(strings.Join([]string{testEnvLine, "# testing comment"}, " "))
Expect(text).To(Equal(testEnvLine))
}

View File

@@ -440,7 +440,7 @@ dokku_build() {
source "$PLUGIN_AVAILABLE_PATH/config/functions"
local APP="$1"; local IMAGE_SOURCE_TYPE="$2"; local TMP_WORK_DIR="$3"; local IMAGE=$(get_app_image_name "$APP")
local id
local cid
verify_app_name "$APP"
local CACHE_DIR="$DOKKU_ROOT/$APP/cache"
@@ -451,9 +451,9 @@ dokku_build() {
case "$IMAGE_SOURCE_TYPE" in
herokuish)
DOKKU_IMAGE="$(config_get "$APP" DOKKU_IMAGE || echo "$DOKKU_IMAGE")"
local id=$(tar -c . | docker run "$DOKKU_GLOBAL_RUN_ARGS" -i -a stdin "$DOKKU_IMAGE" /bin/bash -c "mkdir -p /app && tar -xC /app")
test "$(docker wait "$id")" -eq 0
docker commit "$id" "$IMAGE" > /dev/null
cid=$(tar -c . | docker run "$DOKKU_GLOBAL_RUN_ARGS" -i -a stdin "$DOKKU_IMAGE" /bin/bash -c "mkdir -p /app && tar -xC /app")
test "$(docker wait "$cid")" -eq 0
docker commit "$cid" "$IMAGE" > /dev/null
[[ -d $CACHE_DIR ]] || mkdir -p "$CACHE_DIR"
plugn trigger pre-build-buildpack "$APP"
@@ -462,10 +462,10 @@ dokku_build() {
declare -a ARG_ARRAY
eval "ARG_ARRAY=($DOCKER_ARGS)"
# shellcheck disable=SC2086
id=$(docker run $DOKKU_GLOBAL_RUN_ARGS -d -v $CACHE_DIR:/cache -e CACHE_PATH=/cache "${ARG_ARRAY[@]}" $IMAGE /build)
docker attach "$id"
test "$(docker wait "$id")" -eq 0
docker commit "$id" "$IMAGE" > /dev/null
cid=$(docker run $DOKKU_GLOBAL_RUN_ARGS -d -v $CACHE_DIR:/cache -e CACHE_PATH=/cache "${ARG_ARRAY[@]}" $IMAGE /build)
docker attach "$cid"
test "$(docker wait "$cid")" -eq 0
docker commit "$cid" "$IMAGE" > /dev/null
plugn trigger post-build-buildpack "$APP"
;;
@@ -506,20 +506,21 @@ dokku_release() {
source "$PLUGIN_AVAILABLE_PATH/config/functions"
local APP="$1"; local IMAGE_SOURCE_TYPE="$2"; local IMAGE_TAG="$3"; local IMAGE=$(get_app_image_name "$APP" "$IMAGE_TAG")
local cid
verify_app_name "$APP"
case "$IMAGE_SOURCE_TYPE" in
herokuish)
plugn trigger pre-release-buildpack "$APP" "$IMAGE_TAG"
if [[ -n $(config_export global) ]]; then
local id=$(config_export global | docker run "$DOKKU_GLOBAL_RUN_ARGS" -i -a stdin "$IMAGE" /bin/bash -c "mkdir -p /app/.profile.d && cat > /app/.profile.d/00-global-env.sh")
test "$(docker wait "$id")" -eq 0
docker commit "$id" "$IMAGE" > /dev/null
cid=$(config_export global | docker run "$DOKKU_GLOBAL_RUN_ARGS" -i -a stdin "$IMAGE" /bin/bash -c "mkdir -p /app/.profile.d && cat > /app/.profile.d/00-global-env.sh")
test "$(docker wait "$cid")" -eq 0
docker commit "$cid" "$IMAGE" > /dev/null
fi
if [[ -n $(config_export app "$APP") ]]; then
local id=$(config_export app "$APP" | docker run "$DOKKU_GLOBAL_RUN_ARGS" -i -a stdin "$IMAGE" /bin/bash -c "mkdir -p /app/.profile.d && cat > /app/.profile.d/01-app-env.sh")
test "$(docker wait "$id")" -eq 0
docker commit "$id" "$IMAGE" > /dev/null
cid=$(config_export app "$APP" | docker run "$DOKKU_GLOBAL_RUN_ARGS" -i -a stdin "$IMAGE" /bin/bash -c "mkdir -p /app/.profile.d && cat > /app/.profile.d/01-app-env.sh")
test "$(docker wait "$cid")" -eq 0
docker commit "$cid" "$IMAGE" > /dev/null
fi
plugn trigger post-release-buildpack "$APP" "$IMAGE_TAG"
;;
@@ -541,19 +542,21 @@ dokku_deploy_cmd() {
local cmd="deploy"
source "$PLUGIN_AVAILABLE_PATH/checks/functions"
source "$PLUGIN_AVAILABLE_PATH/config/functions"
source "$PLUGIN_AVAILABLE_PATH/proxy/functions"
[[ -z $1 ]] && dokku_log_fail "Please specify an app to run the command on"
local APP="$1"; local IMAGE_TAG="$2"; local IMAGE=$(get_deploying_app_image_name "$APP" "$IMAGE_TAG")
local APP="$1" IMAGE_TAG="$2"
local DOKKU_DOCKER_STOP_TIMEOUT DOKKU_HEROKUISH DOKKU_NETWORK_BIND_ALL IMAGE
DOKKU_HEROKUISH=false
IMAGE=$(get_deploying_app_image_name "$APP" "$IMAGE_TAG")
verify_app_name "$APP"
plugn trigger pre-deploy "$APP" "$IMAGE_TAG"
is_image_herokuish_based "$IMAGE" && local DOKKU_HEROKUISH=true
is_image_herokuish_based "$IMAGE" && DOKKU_HEROKUISH=true
local DOKKU_SCALE_FILE="$DOKKU_ROOT/$APP/DOKKU_SCALE"
local oldids=$(get_app_container_ids "$APP")
local DOKKU_IS_APP_PROXY_ENABLED="$(is_app_proxy_enabled "$APP")"
local DOKKU_DOCKER_STOP_TIMEOUT="$(config_get "$APP" DOKKU_DOCKER_STOP_TIMEOUT || true)"
DOKKU_NETWORK_BIND_ALL="$(plugn trigger network-get-property "$APP" bind-all-interfaces)"
DOKKU_DOCKER_STOP_TIMEOUT="$(config_get "$APP" DOKKU_DOCKER_STOP_TIMEOUT || true)"
[[ $DOKKU_DOCKER_STOP_TIMEOUT ]] && DOCKER_STOP_TIME_ARG="--time=${DOKKU_DOCKER_STOP_TIMEOUT}"
local line; local PROC_TYPE; local PROC_COUNT; local CONTAINER_INDEX
@@ -577,10 +580,8 @@ dokku_deploy_cmd() {
fi
while [[ $CONTAINER_INDEX -le $PROC_COUNT ]]; do
local id=""; local port=""; local ipaddr=""
local cid=""; local port=""; local ipaddr=""
local DOKKU_CONTAINER_ID_FILE="$DOKKU_ROOT/$APP/CONTAINER.$PROC_TYPE.$CONTAINER_INDEX"
local DOKKU_IP_FILE="$DOKKU_ROOT/$APP/IP.$PROC_TYPE.$CONTAINER_INDEX"
local DOKKU_PORT_FILE="$DOKKU_ROOT/$APP/PORT.$PROC_TYPE.$CONTAINER_INDEX"
# start the app
local DOCKER_ARGS
@@ -591,69 +592,60 @@ dokku_deploy_cmd() {
declare -a ARG_ARRAY
eval "ARG_ARRAY=($DOCKER_ARGS)"
[[ -n "$DOKKU_HEROKUISH" ]] && local START_CMD="/start $PROC_TYPE"
[[ "$DOKKU_HEROKUISH" == "true" ]] && local START_CMD="/start $PROC_TYPE"
if [[ -z "$DOKKU_HEROKUISH" ]]; then
local DOKKU_DOCKERFILE_PORTS=($(config_get "$APP" DOKKU_DOCKERFILE_PORTS || true))
if [[ "$DOKKU_HEROKUISH" == "false" ]]; then
local DOKKU_DOCKERFILE_START_CMD=$(config_get "$APP" DOKKU_DOCKERFILE_START_CMD || true)
local DOKKU_PROCFILE_START_CMD=$(get_cmd_from_procfile "$APP" "$PROC_TYPE")
local START_CMD=${DOKKU_DOCKERFILE_START_CMD:-$DOKKU_PROCFILE_START_CMD}
fi
if [[ "$PROC_TYPE" == "web" ]]; then
if [[ -z "${DOKKU_DOCKERFILE_PORTS[*]}" ]]; then
local port=5000
local DOKKU_DOCKER_PORT_ARGS+="-p $port"
else
local p
for p in ${DOKKU_DOCKERFILE_PORTS[*]};do
if [[ ! "$p" =~ .*udp.* ]]; then
# set port to first non-udp port
local p=${p//\/tcp}
local port=${port:="$p"}
fi
local DOKKU_DOCKER_PORT_ARGS+=" -p $p "
done
fi
if [[ "$DOKKU_IS_APP_PROXY_ENABLED" == "true" ]]; then
# shellcheck disable=SC2086
id=$(docker run $DOKKU_GLOBAL_RUN_ARGS -d -e PORT=$port "${ARG_ARRAY[@]}" $IMAGE $START_CMD)
local ipaddr=$(docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "$id")
# Docker < 1.9 compatibility
if [[ -z $ipaddr ]]; then
local ipaddr=$(docker inspect --format '{{ .NetworkSettings.IPAddress }}' "$id")
ports=($(plugn trigger network-compute-ports "$APP" "$PROC_TYPE" "$DOKKU_HEROKUISH"))
local DOKKU_DOCKER_PORT_ARGS=""
local DOKKU_PORT=""
for p in "${ports[@]}"; do
if [[ ! "$p" =~ .*udp.* ]]; then
DOKKU_PORT=${DOKKU_PORT:="$p"}
fi
DOKKU_DOCKER_PORT_ARGS+=" -p $p "
done
if [[ "$DOKKU_NETWORK_BIND_ALL" == "false" ]]; then
# shellcheck disable=SC2086
cid=$(docker run $DOKKU_GLOBAL_RUN_ARGS -d -e PORT=$DOKKU_PORT "${ARG_ARRAY[@]}" $IMAGE $START_CMD)
else
# shellcheck disable=SC2086
id=$(docker run $DOKKU_GLOBAL_RUN_ARGS -d $DOKKU_DOCKER_PORT_ARGS -e PORT=$port "${ARG_ARRAY[@]}" $IMAGE $START_CMD)
local port=$(docker port "$id" "$port" | sed 's/[0-9.]*://')
local ipaddr=127.0.0.1
cid=$(docker run $DOKKU_GLOBAL_RUN_ARGS -d $DOKKU_DOCKER_PORT_ARGS -e PORT=$DOKKU_PORT "${ARG_ARRAY[@]}" $IMAGE $START_CMD)
fi
else
# shellcheck disable=SC2086
id=$(docker run $DOKKU_GLOBAL_RUN_ARGS -d "${ARG_ARRAY[@]}" $IMAGE $START_CMD)
cid=$(docker run $DOKKU_GLOBAL_RUN_ARGS -d "${ARG_ARRAY[@]}" $IMAGE $START_CMD)
fi
ipaddr=$(plugn trigger network-get-ipaddr "$APP" "$PROC_TYPE" "$cid")
port=$(plugn trigger network-get-port "$APP" "$PROC_TYPE" "$DOKKU_HEROKUISH" "$cid")
kill_new() {
declare desc="wrapper function to kill newly started app container"
local id="$1"
docker inspect "$id" &> /dev/null && docker stop "$id" > /dev/null && docker kill "$id" &> /dev/null
local cid="$1"
docker inspect "$cid" &> /dev/null && docker stop "$cid" > /dev/null && docker kill "$cid" &> /dev/null
trap - INT TERM EXIT
kill -9 $$
}
# run checks first, then post-deploy hooks, which switches proxy traffic
trap 'kill_new $id' INT TERM EXIT
trap 'kill_new $cid' INT TERM EXIT
if [[ "$(is_app_proctype_checks_disabled "$APP" "$PROC_TYPE")" == "false" ]]; then
dokku_log_info1 "Attempting pre-flight checks"
plugn trigger check-deploy "$APP" "$id" "$PROC_TYPE" "$port" "$ipaddr"
plugn trigger check-deploy "$APP" "$cid" "$PROC_TYPE" "$port" "$ipaddr"
fi
trap - INT TERM EXIT
# now using the new container
[[ -n "$id" ]] && echo "$id" > "$DOKKU_CONTAINER_ID_FILE"
[[ -n "$ipaddr" ]] && echo "$ipaddr" > "$DOKKU_IP_FILE"
[[ -n "$port" ]] && echo "$port" > "$DOKKU_PORT_FILE"
[[ -n "$cid" ]] && echo "$cid" > "$DOKKU_CONTAINER_ID_FILE"
[[ -n "$ipaddr" ]] && plugn trigger network-write-ipaddr "$APP" "$PROC_TYPE" "$CONTAINER_INDEX" "$ipaddr"
[[ -n "$port" ]] && plugn trigger network-write-port "$APP" "$PROC_TYPE" "$CONTAINER_INDEX" "$port"
# cleanup pre-migration files
rm -f "$DOKKU_ROOT/$APP/CONTAINER" "$DOKKU_ROOT/$APP/IP" "$DOKKU_ROOT/$APP/PORT"
@@ -1054,9 +1046,11 @@ get_app_urls() {
echo "$(< "$DOKKU_ROOT/HOSTNAME"):$app_port (container)"
done
else
shopt -s nullglob
for PORT_FILE in $DOKKU_ROOT/$APP/PORT.*; do
echo "$SCHEME://$(< "$DOKKU_ROOT/HOSTNAME"):$(< "$PORT_FILE") (container)"
local DOKKU_APP_LISTENERS PORT
DOKKU_APP_LISTENERS="$(plugn trigger network-get-listeners "$APP" | xargs)"
for DOKKU_APP_LISTENER in $DOKKU_APP_LISTENERS; do
PORT="$(echo "$DOKKU_APP_LISTENER" | cut -d ':' -f2)"
echo "$SCHEME://$(< "$DOKKU_ROOT/HOSTNAME"):$PORT (container)"
done
shopt -u nullglob
fi

56
plugins/common/log.go Normal file
View File

@@ -0,0 +1,56 @@
package common
import (
"fmt"
"os"
)
// LogFail is the failure log formatter
// prints text to stderr and exits with status 1
func LogFail(text string) {
fmt.Fprintln(os.Stderr, fmt.Sprintf("FAILED: %s", text))
os.Exit(1)
}
// LogInfo1 is the info1 header formatter
func LogInfo1(text string) {
fmt.Fprintln(os.Stdout, fmt.Sprintf("-----> %s", text))
}
// LogInfo1Quiet is the info1 header formatter (with quiet option)
func LogInfo1Quiet(text string) {
if os.Getenv("DOKKU_QUIET_OUTPUT") != "" {
LogInfo1(text)
}
}
// LogInfo2 is the info2 header formatter
func LogInfo2(text string) {
fmt.Fprintln(os.Stdout, fmt.Sprintf("=====> %s", text))
}
// LogInfo2Quiet is the info2 header formatter (with quiet option)
func LogInfo2Quiet(text string) {
if os.Getenv("DOKKU_QUIET_OUTPUT") == "" {
LogInfo2(text)
}
}
// LogVerbose is the verbose log formatter
// prints indented text to stdout
func LogVerbose(text string) {
fmt.Fprintln(os.Stdout, fmt.Sprintf(" %s", text))
}
// LogVerboseQuiet is the verbose log formatter
// prints indented text to stdout (with quiet option)
func LogVerboseQuiet(text string) {
if os.Getenv("DOKKU_QUIET_OUTPUT") != "" {
LogVerbose(text)
}
}
// LogWarn is the warning log formatter
func LogWarn(text string) {
fmt.Fprintln(os.Stderr, fmt.Sprintf(" ! %s", text))
}

View File

@@ -1,4 +1,4 @@
[plugin]
description = "dokku core common plugin"
version = "0.10.4"
version = "0.10.5"
[plugin.config]

View File

@@ -0,0 +1,164 @@
package common
import (
"fmt"
"io/ioutil"
"os"
"os/user"
"reflect"
"strconv"
"strings"
)
// CommandPropertySet is a generic function that will set a property for a given plugin/app combination
func CommandPropertySet(pluginName, appName, property, value string, properties map[string]string) {
if err := VerifyAppName(appName); err != nil {
LogFail(err.Error())
}
if property == "" {
LogFail("No property specified")
}
if _, ok := properties[property]; !ok {
properties := reflect.ValueOf(properties).MapKeys()
validPropertyList := make([]string, len(properties))
for i := 0; i < len(properties); i++ {
validPropertyList[i] = properties[i].String()
}
LogFail(fmt.Sprintf("Invalid property specified, valid properties include: %s", strings.Join(validPropertyList, ", ")))
}
if value != "" {
LogInfo2Quiet(fmt.Sprintf("Setting %s to %s", property, value))
PropertyWrite(pluginName, appName, property, value)
} else {
LogInfo2Quiet(fmt.Sprintf("Unsetting %s", property))
PropertyDelete(pluginName, appName, property)
}
}
// PropertyDelete deletes a property from the plugin properties for an app
func PropertyDelete(pluginName string, appName string, property string) {
pluginAppConfigRoot := getPluginAppPropertyPath(pluginName, appName)
propertyPath := strings.Join([]string{pluginAppConfigRoot, property}, "/")
if err := os.Remove(propertyPath); err != nil {
LogFail(fmt.Sprintf("Unable to remove %s property %s.%s", pluginName, appName, property))
}
}
// PropertyDestroy destroys the plugin properties for an app
func PropertyDestroy(pluginName string, appName string) {
if appName == "_all_" {
pluginConfigPath := getPluginConfigPath(pluginName)
os.RemoveAll(pluginConfigPath)
} else {
pluginAppConfigRoot := getPluginAppPropertyPath(pluginName, appName)
os.RemoveAll(pluginAppConfigRoot)
}
}
// PropertyExists returns whether a property exists or not
func PropertyExists(pluginName string, appName string, property string) bool {
pluginAppConfigRoot := getPluginAppPropertyPath(pluginName, appName)
propertyPath := strings.Join([]string{pluginAppConfigRoot, property}, "/")
_, err := os.Stat(propertyPath)
return !os.IsNotExist(err)
}
// PropertyGet returns the value for a given property
func PropertyGet(pluginName string, appName string, property string) string {
return PropertyGetDefault(pluginName, appName, property, "")
}
// PropertyGetDefault returns the value for a given property with a specified default value
func PropertyGetDefault(pluginName, appName, property, defaultValue string) (val string) {
if !PropertyExists(pluginName, appName, property) {
return
}
pluginAppConfigRoot := getPluginAppPropertyPath(pluginName, appName)
propertyPath := strings.Join([]string{pluginAppConfigRoot, property}, "/")
b, err := ioutil.ReadFile(propertyPath)
if err != nil {
LogWarn(fmt.Sprintf("Unable to read %s property %s.%s", pluginName, appName, property))
return
}
val = string(b)
return
}
// PropertyWrite writes a value for a given application property
func PropertyWrite(pluginName string, appName string, property string, value string) {
if err := makePropertyPath(pluginName, appName); err != nil {
LogFail(fmt.Sprintf("Unable to create %s config directory for %s: %s", pluginName, appName, err.Error()))
}
pluginAppConfigRoot := getPluginAppPropertyPath(pluginName, appName)
propertyPath := strings.Join([]string{pluginAppConfigRoot, property}, "/")
file, err := os.Create(propertyPath)
if err != nil {
LogFail(fmt.Sprintf("Unable to write %s config value %s.%s: %s", pluginName, appName, property, err.Error()))
}
defer file.Close()
fmt.Fprintf(file, value)
file.Chmod(0600)
setPermissions(propertyPath, 0600)
}
// PropertySetup creates the plugin config root
func PropertySetup(pluginName string) (err error) {
pluginConfigRoot := getPluginConfigPath(pluginName)
if err = os.MkdirAll(pluginConfigRoot, 0755); err != nil {
return
}
return setPermissions(pluginConfigRoot, 0755)
}
// getPluginAppPropertyPath returns the plugin property path for a given plugin/app combination
func getPluginAppPropertyPath(pluginName string, appName string) string {
return strings.Join([]string{getPluginConfigPath(pluginName), appName}, "/")
}
// getPluginConfigPath returns the plugin property path for a given plugin
func getPluginConfigPath(pluginName string) string {
return strings.Join([]string{MustGetEnv("DOKKU_LIB_ROOT"), "config", pluginName}, "/")
}
// makePropertyPath ensures that a property path exists
func makePropertyPath(pluginName string, appName string) (err error) {
pluginAppConfigRoot := getPluginAppPropertyPath(pluginName, appName)
if err = os.MkdirAll(pluginAppConfigRoot, 0755); err != nil {
return
}
return setPermissions(pluginAppConfigRoot, 0755)
}
// setPermissions sets the proper owner and filemode for a given file
func setPermissions(path string, fileMode os.FileMode) (err error) {
if err = os.Chmod(path, fileMode); err != nil {
return err
}
group, err := user.LookupGroup("dokku")
if err != nil {
return
}
user, err := user.Lookup("dokku")
if err != nil {
return
}
uid, err := strconv.Atoi(user.Uid)
if err != nil {
return
}
gid, err := strconv.Atoi(group.Gid)
if err != nil {
return
}
return os.Chown(path, uid, gid)
}