diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4c11728da..e318d33e3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,8 +4,8 @@ on: push: env: - GOLANGCI_LINT_VERSION: 'v1.46.2' - NFPM_VERSION: 'v2.18.0' + GOLANGCI_LINT_VERSION: 'v1.49.0' + NFPM_VERSION: 'v2.18.1' jobs: lint: diff --git a/.nfpm.yaml b/.nfpm.yaml index 215eb56db..6c1c827c4 100644 --- a/.nfpm.yaml +++ b/.nfpm.yaml @@ -15,7 +15,7 @@ contents: - src: nginx-agent.conf dst: /etc/nginx-agent/nginx-agent.conf file_info: - mode: 0660 + mode: 0640 - src: ./scripts/packages/nginx-agent.service dst: /etc/systemd/system/nginx-agent.service - src: ./scripts/selinux/nginx_agent_selinux.8.gz diff --git a/scripts/.local-nfpm.yaml b/scripts/.local-nfpm.yaml index 07ad07e68..26a4b6001 100644 --- a/scripts/.local-nfpm.yaml +++ b/scripts/.local-nfpm.yaml @@ -13,7 +13,7 @@ contents: - src: nginx-agent.conf dst: /etc/nginx-agent/nginx-agent.conf file_info: - mode: 0660 + mode: 0640 - src: ./scripts/packages/nginx-agent.service dst: /etc/systemd/system/nginx-agent.service - src: ./scripts/selinux/nginx_agent_selinux.8.gz diff --git a/scripts/docker/alpine/Dockerfile b/scripts/docker/alpine/Dockerfile index 3ae43a4f5..87826c720 100644 --- a/scripts/docker/alpine/Dockerfile +++ b/scripts/docker/alpine/Dockerfile @@ -60,7 +60,7 @@ RUN --mount=type=secret,id=nginx-crt,dst=/etc/apk/cert.pem \ nginx-agent \ " \ && apk update \ - && apk add $nginxPackages + && apk add $nginxPackages # run the nginx and agent FROM install as runtime diff --git a/scripts/packages/nginx-agent b/scripts/packages/nginx-agent index ccddbd7b9..6f4d6629c 100644 --- a/scripts/packages/nginx-agent +++ b/scripts/packages/nginx-agent @@ -21,7 +21,6 @@ status_cmd="status_agent" start_agent() { PATH=$PATH:/usr/local/sbin - mkdir -p /var/log/nginx-agent /usr/sbin/daemon -f -p ${pidfile} ${command} } diff --git a/scripts/packages/packager/local-entrypoint.sh b/scripts/packages/packager/local-entrypoint.sh index d5c96299a..2898b2832 100644 --- a/scripts/packages/packager/local-entrypoint.sh +++ b/scripts/packages/packager/local-entrypoint.sh @@ -12,6 +12,7 @@ mkdir -p /staging/usr/local/etc/rc.d cp nginx-agent.conf /staging/usr/local/etc/nginx-agent cp scripts/packages/nginx-agent /staging/usr/local/etc/rc.d +cp scripts/packages/preinstall.sh /staging/+PRE_INSTALL cp scripts/packages/postremove.sh /staging/+PRE_DEINSTALL cp scripts/packages/postinstall.sh /staging/+POST_INSTALL cp scripts/packages/plist /staging diff --git a/scripts/packages/packager/signed-entrypoint.sh b/scripts/packages/packager/signed-entrypoint.sh index 05f204768..0e123d1a9 100644 --- a/scripts/packages/packager/signed-entrypoint.sh +++ b/scripts/packages/packager/signed-entrypoint.sh @@ -16,6 +16,7 @@ mkdir -p staging/usr/local/etc/rc.d cp nginx-agent.conf staging/usr/local/etc/nginx-agent cp scripts/packages/nginx-agent staging/usr/local/etc/rc.d +cp scripts/packages/preinstall.sh /staging/+PRE_INSTALL cp scripts/packages/postremove.sh staging/+PRE_DEINSTALL cp scripts/packages/postinstall.sh staging/+POST_INSTALL cp scripts/packages/plist staging diff --git a/scripts/packages/postinstall.sh b/scripts/packages/postinstall.sh index f503bd58a..9547c07b9 100755 --- a/scripts/packages/postinstall.sh +++ b/scripts/packages/postinstall.sh @@ -18,166 +18,190 @@ AGENT_USER=$(id -nu) WORKER_USER="" AGENT_GROUP="nginx-agent" -if command -v systemctl; then - printf "PostInstall: Reading NGINX systemctl unit file for user information\n" - nginx_unit_file=$(systemctl status nginx | grep -Po "\(\K\/.*service") - pid_file=$(grep -Po "PIDFile=\K.*$" "${nginx_unit_file}") - - if [ ! -f "$pid_file" ]; then - echo "${pid_file} does not exist" - else - pidId=$(cat "${pid_file}") - nginx_user=$(ps --no-headers -u -p "${pidId}" | head -1 | awk '{print $1}') +detect_nginx_users() { + if command -V systemctl >/dev/null 2>&1; then + printf "PostInstall: Reading NGINX systemctl unit file for user information\n" + nginx_unit_file=$(systemctl status nginx | grep -Po "\(\K\/.*service") + pid_file=$(grep -Po "PIDFile=\K.*$" "${nginx_unit_file}") + + if [ ! -f "$pid_file" ]; then + printf "%s does not exist\n" "${pid_file}" + else + pidId=$(cat "${pid_file}") + nginx_user=$(ps --no-headers -u -p "${pidId}" | head -1 | awk '{print $1}') + fi + + if [ ! "${nginx_user}" ]; then + printf "No NGINX user found\n" + fi fi - if [ ! "${nginx_user}" ]; then - printf "No NGINX user found\n" - fi -fi - -if [ -z "${nginx_user}" ]; then - printf "PostInstall: Reading NGINX process information to determine NGINX user\n" - nginx_user=$(ps aux | grep "nginx: master process" | grep -v grep | head -1 | awk '{print $1}') - if [ -z "${nginx_user}" ]; then - printf "No NGINX user found\n" - fi -fi + printf "PostInstall: Reading NGINX process information to determine NGINX user\n" + nginx_user=$(ps aux | grep "nginx: master process" | grep -v grep | head -1 | awk '{print $1}') -if [ "${nginx_user}" ]; then - echo "NGINX processes running as user '${nginx_user}'. nginx-agent will be configured to run as same user" - AGENT_USER=${nginx_user} -else - echo "WARNING: No NGINX processes detected." -fi + if [ -z "${nginx_user}" ]; then + printf "No NGINX user found\n" + fi + fi -if [ -z "${worker_user}" ]; then - printf "PostInstall: Reading NGINX process information to determine NGINX user\n" - worker_user=$(ps aux | grep "nginx: worker process" | grep -v grep | head -1 | awk '{print $1}') + if [ "${nginx_user}" ]; then + echo "NGINX processes running as user '${nginx_user}'. nginx-agent will be configured to run as same user" + AGENT_USER=${nginx_user} + else + echo "WARNING: No NGINX processes detected." + fi if [ -z "${worker_user}" ]; then - printf "No NGINX worker user found\n" - fi -fi + printf "PostInstall: Reading NGINX process information to determine NGINX user\n" + worker_user=$(ps aux | grep "nginx: worker process" | grep -v grep | head -1 | awk '{print $1}') -if [ "${worker_user}" ]; then - echo "NGINX processes running as user '${worker_user}'. nginx-agent will try add that user to '${AGENT_GROUP}'" - WORKER_USER=${worker_user} -else - echo "WARNING: No NGINX worker processes detected." -fi + if [ -z "${worker_user}" ]; then + printf "No NGINX worker user found\n" + fi + fi -if [ -z "${AGENT_USER}" ]; then - echo "\$USER not defined. Running as root" - USER=root - AGENT_USER=root -fi + if [ "${worker_user}" ]; then + echo "NGINX processes running as user '${worker_user}'. nginx-agent will try add that user to '${AGENT_GROUP}'" + WORKER_USER=${worker_user} + else + echo "WARNING: No NGINX worker processes detected." + fi -if [ "$(id -u)" = "0" ]; then - echo "Sudo permissions detected" -else - echo "No sudo permission detected, please run as sudo" - exit 1 -fi + if [ -z "${AGENT_USER}" ]; then + echo "\$USER not defined. Running as root" + USER=root + AGENT_USER=root + fi +} -if [ -z "${AGENT_EXE}" ]; then - printf "Could not determine path to nginx-agent, using default...\n" +ensure_sudo() { + if [ "$(id -u)" = "0" ]; then + echo "Sudo permissions detected" + else + echo "No sudo permission detected, please run as sudo" + exit 1 + fi +} +ensure_agent_path() { if [ ! -f "${AGENT_EXE}" ]; then echo "nginx-agent not in default path, exiting..." exit 1 fi -fi -printf "Found nginx-agent %s\n" "${AGENT_EXE}" + printf "Found nginx-agent %s\n" "${AGENT_EXE}" +} -if command -v systemctl; then - printf "PostInstall: Adding nginx-agent group %s\n" "${AGENT_GROUP}" - groupadd "${AGENT_GROUP}" +create_agent_group() { + if command -V systemctl >/dev/null 2>&1; then + printf "PostInstall: Adding nginx-agent group %s\n" "${AGENT_GROUP}" + groupadd "${AGENT_GROUP}" - printf "PostInstall: Adding NGINX / agent user %s to group %s\n" "${AGENT_USER}" "${AGENT_GROUP}" - usermod -a -G "${AGENT_GROUP}" "${AGENT_USER}" - if [ "${WORKER_USER}" ]; then - printf "PostInstall: Adding NGINX Worker user %s to group %s\n" "${WORKER_USER}" "${AGENT_GROUP}" - usermod -a -G "${AGENT_GROUP}" "${WORKER_USER}" + printf "PostInstall: Adding NGINX / agent user %s to group %s\n" "${AGENT_USER}" "${AGENT_GROUP}" + usermod -a -G "${AGENT_GROUP}" "${AGENT_USER}" + if [ "${WORKER_USER}" ]; then + printf "PostInstall: Adding NGINX Worker user %s to group %s\n" "${WORKER_USER}" "${AGENT_GROUP}" + usermod -a -G "${AGENT_GROUP}" "${WORKER_USER}" + fi fi -fi - -if [ "$ID" = "freebsd" ]; then - printf "PostInstall: Adding nginx-agent group %s\n" "${AGENT_GROUP}" - pw groupadd "${AGENT_GROUP}" - - printf "PostInstall: Adding NGINX / agent user %s to group %s\n" "${AGENT_USER}" "${AGENT_GROUP}" - pw groupmod "${AGENT_GROUP}" -M "${AGENT_USER}" - if [ "${WORKER_USER}" ]; then - printf "PostInstall: Adding NGINX Worker user %s to group %s\n" "${WORKER_USER}" "${AGENT_GROUP}" - pw groupmod "${AGENT_GROUP}" -M "${WORKER_USER}" - fi -fi -if [ "$ID" = "alpine" ]; then - printf "PostInstall: Adding nginx-agent group %s\n" "${AGENT_GROUP}" - addgroup "${AGENT_GROUP}" + if [ "$ID" = "freebsd" ]; then + printf "PostInstall: Adding nginx-agent group %s\n" "${AGENT_GROUP}" + pw groupadd "${AGENT_GROUP}" - printf "PostInstall: Adding NGINX / agent user %s to group %s\n" "${AGENT_USER}" "${AGENT_GROUP}" - addgroup "${AGENT_USER}" "${AGENT_GROUP}" - if [ "${WORKER_USER}" ]; then - printf "PostInstall: Adding NGINX Worker user %s to group %s\n" "${WORKER_USER}" "${AGENT_GROUP}" - addgroup "${WORKER_USER}" "${AGENT_GROUP}" + printf "PostInstall: Adding NGINX / agent user %s to group %s\n" "${AGENT_USER}" "${AGENT_GROUP}" + pw groupmod "${AGENT_GROUP}" -M "${AGENT_USER}" + if [ "${WORKER_USER}" ]; then + printf "PostInstall: Adding NGINX Worker user %s to group %s\n" "${WORKER_USER}" "${AGENT_GROUP}" + pw groupmod "${AGENT_GROUP}" -M "${WORKER_USER}" + fi fi -fi - -printf "PostInstall: Creating NGINX Agent run directory \n" -mkdir -p "${AGENT_RUN_DIR}" - -printf "PostInstall: Modifying group ownership of NGINX Agent run directory \n" -chown "${AGENT_USER}":"${AGENT_GROUP}" "${AGENT_RUN_DIR}" - -# Fill in data to unit file that's acquired post install -if command -v systemctl; then - printf "PostInstall: Modifying NGINX Agent unit file with correct locations and user information\n" - EXE_CMD="s|\${AGENT_EXE}|${AGENT_EXE}|g" - sed -i -e $EXE_CMD ${AGENT_UNIT_LOCATION}/${AGENT_UNIT_FILE} - - LOG_DIR_CMD="s|\${AGENT_LOG_DIR}|${AGENT_LOG_DIR}|g" - sed -i -e $LOG_DIR_CMD ${AGENT_UNIT_LOCATION}/${AGENT_UNIT_FILE} - - RUN_DIR_CMD="s|\${AGENT_RUN_DIR}|${AGENT_RUN_DIR}|g" - sed -i -e $RUN_DIR_CMD ${AGENT_UNIT_LOCATION}/${AGENT_UNIT_FILE} - USER_CMD="s/\${AGENT_USER}/${AGENT_USER}/g" - sed -i -e $USER_CMD ${AGENT_UNIT_LOCATION}/${AGENT_UNIT_FILE} + if [ "$ID" = "alpine" ]; then + printf "PostInstall: Adding nginx-agent group %s\n" "${AGENT_GROUP}" + addgroup "${AGENT_GROUP}" - GROUP_CMD="s/\${AGENT_GROUP}/${AGENT_GROUP}/g" - sed -i -e $GROUP_CMD ${AGENT_UNIT_LOCATION}/${AGENT_UNIT_FILE} - - printf "PostInstall: Reload the service unit from disk\n" - systemctl daemon-reload - printf "PostInstall: Unmask the service unit from disk\n" - systemctl unmask "${AGENT_UNIT_FILE}" - printf "PostInstall: Set the preset flag for the service unit\n" - systemctl preset "${AGENT_UNIT_FILE}" - printf "PostInstall: Set the enabled flag for the service unit\n" - systemctl enable "${AGENT_UNIT_FILE}" -fi + printf "PostInstall: Adding NGINX / agent user %s to group %s\n" "${AGENT_USER}" "${AGENT_GROUP}" + addgroup "${AGENT_USER}" "${AGENT_GROUP}" + if [ "${WORKER_USER}" ]; then + printf "PostInstall: Adding NGINX Worker user %s to group %s\n" "${WORKER_USER}" "${AGENT_GROUP}" + addgroup "${WORKER_USER}" "${AGENT_GROUP}" + fi + fi +} + +create_run_dir() { + printf "PostInstall: Creating NGINX Agent run directory \n" + mkdir -p "${AGENT_RUN_DIR}" + + printf "PostInstall: Modifying group ownership of NGINX Agent run directory \n" + chown "${AGENT_USER}":"${AGENT_GROUP}" "${AGENT_RUN_DIR}" +} + +update_unit_file() { + # Fill in data to unit file that's acquired post install + if command -V systemctl >/dev/null 2>&1; then + printf "PostInstall: Modifying NGINX Agent unit file with correct locations and user information\n" + EXE_CMD="s|\${AGENT_EXE}|${AGENT_EXE}|g" + sed -i -e $EXE_CMD ${AGENT_UNIT_LOCATION}/${AGENT_UNIT_FILE} + + LOG_DIR_CMD="s|\${AGENT_LOG_DIR}|${AGENT_LOG_DIR}|g" + sed -i -e $LOG_DIR_CMD ${AGENT_UNIT_LOCATION}/${AGENT_UNIT_FILE} + + RUN_DIR_CMD="s|\${AGENT_RUN_DIR}|${AGENT_RUN_DIR}|g" + sed -i -e $RUN_DIR_CMD ${AGENT_UNIT_LOCATION}/${AGENT_UNIT_FILE} + + USER_CMD="s/\${AGENT_USER}/${AGENT_USER}/g" + sed -i -e $USER_CMD ${AGENT_UNIT_LOCATION}/${AGENT_UNIT_FILE} + + GROUP_CMD="s/\${AGENT_GROUP}/${AGENT_GROUP}/g" + sed -i -e $GROUP_CMD ${AGENT_UNIT_LOCATION}/${AGENT_UNIT_FILE} + + printf "PostInstall: Reload the service unit from disk\n" + systemctl daemon-reload + printf "PostInstall: Unmask the service unit from disk\n" + systemctl unmask "${AGENT_UNIT_FILE}" + printf "PostInstall: Set the preset flag for the service unit\n" + systemctl preset "${AGENT_UNIT_FILE}" + printf "PostInstall: Set the enabled flag for the service unit\n" + systemctl enable "${AGENT_UNIT_FILE}" + fi -if [ "$ID" = "freebsd" ]; then - printf "PostInstall: Enabling NGINX Agent Service\n" - sysrc nginx_agent_enable=YES -fi + if [ "$ID" = "freebsd" ]; then + printf "PostInstall: Enabling NGINX Agent Service\n" + sysrc nginx_agent_enable=YES + fi +} -echo "----------------------------------------------------------------------" -echo " NGINX Agent package has been successfully installed." -echo "" -echo " Please follow the next steps to start the software:" -if [ "$ID" = "freebsd" ]; then - echo " sudo service nginx-agent start" +summary() { + echo "----------------------------------------------------------------------" + echo " NGINX Agent package has been successfully installed." echo "" -else - echo " sudo systemctl start nginx-agent" + echo " Please follow the next steps to start the software:" + if [ "$ID" = "freebsd" ]; then + echo " sudo service nginx-agent start" + echo "" + else + echo " sudo systemctl start nginx-agent" + echo "" + fi + echo " Configuration settings can be adjusted here:" + echo " ${BSD_HIER}/etc/nginx-agent/nginx-agent.conf" echo "" -fi -echo " Configuration settings can be adjusted here:" -echo " ${BSD_HIER}/etc/nginx-agent/nginx-agent.conf" -echo "" -echo "----------------------------------------------------------------------" + echo "----------------------------------------------------------------------" +} + +# +# Main body of the script +# +{ + detect_nginx_users + ensure_sudo + ensure_agent_path + create_agent_group + create_run_dir + update_unit_file + summary +} + diff --git a/scripts/packages/postremove.sh b/scripts/packages/postremove.sh index f0cf3debb..a8e050073 100755 --- a/scripts/packages/postremove.sh +++ b/scripts/packages/postremove.sh @@ -5,12 +5,12 @@ if [ "$ID" = "freebsd" ]; then echo "Stop and remove nginx-agent service" - service nginx-agent onestop || true - sysrc -x nginx_agent_enable || true -elif command -v systemctl; then + service nginx-agent onestop >/dev/null 2>&1 || true + sysrc -x nginx_agent_enable >/dev/null 2>&1 || true +elif command -V systemctl >/dev/null 2>&1; then echo "Stop and disable nginx-agent service" - systemctl stop nginx-agent || true - systemctl disable nginx-agent || true + systemctl stop nginx-agent >/dev/null 2>&1 || true + systemctl disable nginx-agent >/dev/null 2>&1 || true echo "Running daemon-reload" systemctl daemon-reload || true fi diff --git a/scripts/packages/preinstall.sh b/scripts/packages/preinstall.sh index 10c9f255e..5a50d063d 100644 --- a/scripts/packages/preinstall.sh +++ b/scripts/packages/preinstall.sh @@ -17,7 +17,6 @@ INSTANCE_GROUP="" ###### Default variables ################################ export AGENT_GROUP="${AGENT_GROUP:-$(id -ng)}" -export AGENT_INSTALL_LOG="${AGENT_INSTALL_LOG:-/tmp/agent-install.log}" # Determine OS platform # shellcheck source=/dev/null @@ -26,6 +25,7 @@ export AGENT_INSTALL_LOG="${AGENT_INSTALL_LOG:-/tmp/agent-install.log}" if [ "$ID" = "freebsd" ]; then AGENT_CONFIG_FILE=${AGENT_CONFIG_FILE:-"/usr/local/etc/nginx-agent/nginx-agent.conf"} AGENT_DYNAMIC_CONFIG_DIR="/usr/local/etc/nginx-agent" + mkdir -p /var/log/nginx-agent/ else AGENT_CONFIG_FILE=${AGENT_CONFIG_FILE:-"/etc/nginx-agent/nginx-agent.conf"} AGENT_DYNAMIC_CONFIG_DIR="/etc/nginx-agent" @@ -50,8 +50,6 @@ AGENT_DYNAMIC_CONFIG_COMMENT="# " -ALLOWABLE_LOG_LEVELS="trace debug info error fatal panic" - # # Functions # @@ -65,7 +63,6 @@ err_exit() { title() { printf "\n --- NGINX Agent Package Installer --- \n\n" printf " --- Will install the NGINX Agent in 5 seconds ---\n" - printf " --- Install log is outputted to: %s\n" "${AGENT_INSTALL_LOG}" sleep 5 } @@ -77,16 +74,7 @@ ensure_sudo() { fi } -is_empty() { - if [ -z "$2" ]; then - printf "\nValue for '%s' blank... skipping" "$1" - return 0 - fi - return 1 -} - load_config_values() { - # If the file doesn't exist attempt to create it if [ ! -f "$AGENT_DYNAMIC_CONFIG_FILE" ]; then printf "Could not find %s ... Creating file\n" ${AGENT_DYNAMIC_CONFIG_FILE} @@ -96,7 +84,7 @@ load_config_values() { fi # Check if there are existing values - _instance_group="$(grep "^instance_group:" "${AGENT_DYNAMIC_CONFIG_FILE}" | head -n 1 | cut -d : -f 2 | sed "s/^[[:space:]]//")" + _instance_group="$(grep "^instance_group:" "${AGENT_DYNAMIC_CONFIG_FILE}" | head -n 1 | cut -d : -f 2 | sed "s/^[[:space:]]//")" if [ "$_instance_group" ] && [ ! "${INSTANCE_GROUP}" ]; then INSTANCE_GROUP=$_instance_group @@ -104,33 +92,17 @@ load_config_values() { } update_config_file() { - agent_config_updated="" - dynamic_config_updated="" - - printf "Updating %s ...\n" "${AGENT_DYNAMIC_CONFIG_FILE}" - sed_cmd="sed -i.bak " if [ ! -f "$AGENT_CONFIG_FILE" ]; then - err_exit "$AGENT_CONFIG_FILE does not exist" - fi - if [ ! -f "$AGENT_DYNAMIC_CONFIG_FILE" ]; then - err_exit "$AGENT_DYNAMIC_CONFIG_FILE does not exist" + printf "Agent config file %s does not exist. Could not be updated\n" "$AGENT_CONFIG_FILE" + exit 0 fi + printf "Updating %s ...\n" "${AGENT_CONFIG_FILE}" + # Replace Host + sed_cmd="sed -i.bak " ${sed_cmd} "s/host:.*$/host: ${PACKAGE_HOST}/" "${AGENT_CONFIG_FILE}" - # Check the instance group and set accordingly - if [ "${INSTANCE_GROUP}" ]; then - if [ "$(grep -cP '^(?=[\s]*+[^#])[^#]*(instance_group)' "${AGENT_DYNAMIC_CONFIG_FILE}")" -ge 1 ]; then - printf "Setting existing instance_group: %s\n" "${INSTANCE_GROUP}" - ${sed_cmd} "/^[[:space:]]*#/!s/\(instance_group:.*\)/instance_group: ${INSTANCE_GROUP}/g" "${AGENT_DYNAMIC_CONFIG_FILE}" - else - printf "Setting instance_group: %s\n" "${INSTANCE_GROUP}" - printf "instance_group: %s\n" "${INSTANCE_GROUP}" >> "${AGENT_DYNAMIC_CONFIG_FILE}" - fi - dynamic_config_updated="true" - fi - # Check the log-level and set accordingly if [ "${LOG_LEVEL}" ]; then if [ "$(grep -cP '^(?=[\s]*+[^#])[^#]*(level:)' "${AGENT_CONFIG_FILE}")" -ge 1 ]; then @@ -140,28 +112,35 @@ update_config_file() { printf "Setting log level: %s\n" "${LOG_LEVEL}" _log_level_replacement="s/^log:/log:\\ level: ${LOG_LEVEL}/" - ${sed_cmd} "${_log_level_replacement}" "${AGENT_CONFIG_FILE}" printf "Successfully updated %s\n" "${AGENT_CONFIG_FILE}" fi - agent_config_updated="true" fi - if [ "${dynamic_config_updated=}" ]; then + printf "Successfully updated %s\n" "${AGENT_CONFIG_FILE}" + + # Check the instance group and set accordingly + if [ "${INSTANCE_GROUP}" ]; then + printf "Updating %s ...\n" "${AGENT_DYNAMIC_CONFIG_FILE}" + + if [ "$(grep -cP '^(?=[\s]*+[^#])[^#]*(instance_group)' "${AGENT_DYNAMIC_CONFIG_FILE}")" -ge 1 ]; then + printf "Setting existing instance_group: %s\n" "${INSTANCE_GROUP}" + ${sed_cmd} "/^[[:space:]]*#/!s/\(instance_group:.*\)/instance_group: ${INSTANCE_GROUP}/g" "${AGENT_DYNAMIC_CONFIG_FILE}" + else + printf "Setting instance_group: %s\n" "${INSTANCE_GROUP}" + printf "instance_group: %s\n" "${INSTANCE_GROUP}" >> "${AGENT_DYNAMIC_CONFIG_FILE}" + fi + printf "Successfully updated %s\n" "${AGENT_DYNAMIC_CONFIG_FILE}" fi - - if [ "${agent_config_updated=}" ]; then - printf "Successfully updated %s\n" "${AGENT_CONFIG_FILE}" - fi } # # Main body of the script # { - title - ensure_sudo - load_config_values - update_config_file -} | tee "${AGENT_INSTALL_LOG}" + title + ensure_sudo + load_config_values + update_config_file +} diff --git a/src/core/logger/log.go b/src/core/logger/log.go index d0a621bab..53b13c34a 100644 --- a/src/core/logger/log.go +++ b/src/core/logger/log.go @@ -45,7 +45,7 @@ func SetLogFile(logFile string) *os.File { logPath = path.Join(logPath, defaultLogFile) } - logFileHandle, err := os.OpenFile(logPath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0664) + logFileHandle, err := os.OpenFile(logPath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0640) if err != nil { log.Errorf("Failed to set log file, proceeding to log only to stdout/stderr: %v", err) return nil diff --git a/test/install/agent_install_test.go b/test/install/agent_install_test.go index 27d7df9ef..354765f87 100644 --- a/test/install/agent_install_test.go +++ b/test/install/agent_install_test.go @@ -9,89 +9,95 @@ import ( "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const ( + osReleasePath = "/etc/os-release" + maxFileSize = int64(20000000) + maxInstallTime = 30 * time.Second ) var ( AGENT_PACKAGE_FILE = os.Getenv("AGENT_PACKAGE_FILE") - maxFileSize = int64(20000000) - maxInstallTime = 30 * time.Second - expectedLogMsg = LogMessages() - expectedAgentDirs = AgentDirectories() - systemDetails = SystemData() ) -/* -Test Agent Install and Uninstall. -Verifies that agent installs with correct output and files. -Verifies that agent uninstalls and removes all the files. -*/ +// TestAgentManualInstallUninstall tests Agent Install and Uninstall. +// Verifies that agent installs with correct output and files. +// Verifies that agent uninstalls and removes all the files. func TestAgentManualInstallUninstall(t *testing.T) { + expectedLogMsgs := map[string]string{ + "ConnectionStatus": "agent_connect_response: configs: > > status: >", + "InstallFoundNginxAgent": "Found nginx-agent /usr/bin/nginx-agent", + "InstallAgentToRunAs": "nginx-agent will be configured to run as same user", + "InstallAgentSuccess": "NGINX Agent package has been successfully installed.", + "InstallAgentStartCmd": "sudo systemctl start nginx-agent", + "UninstallAgent": "Removing nginx-agent", + "UninstallAgentStopService": "Stop and disable nginx-agent service", + "UninstallAgentPurgingFiles": "Purging configuration files for nginx-agent", + } - //Set up assertions - checkAgentInstall := assert.New(t) + expectedAgentPaths := map[string]string{ + "AgentConfigFile": "/etc/nginx-agent/nginx-agent.conf", + "AgentSystemFile": "/etc/systemd/system/multi-user.target.wants/nginx-agent.service", + } - //Check the agent tarball is present + // Check the environment variable $AGENT_PACKAGE_FILE is set + require.NotEmpty(t, AGENT_PACKAGE_FILE, "Environment variable $AGENT_PACKAGE_FILE not set") + + // Check the agent tarball is present file, err := os.Stat(AGENT_PACKAGE_FILE) - if err != nil { - t.Errorf("Error accessing agent tarball at location: " + AGENT_PACKAGE_FILE) - } + require.NoError(t, err, "Error accessing tarball at: "+AGENT_PACKAGE_FILE) - //Install Agent and record installation time/install output - installTime, agentLog := installAgent(AGENT_PACKAGE_FILE, t) + // Install Agent and record installation time/install output + installTime, agentLog := installAgent(t, AGENT_PACKAGE_FILE) - //Check the file size is less than or equal 20MB + // Check the file size is less than or equal 20MB assert.LessOrEqual(t, file.Size(), maxFileSize) - //Check the install time under 30s + // Check the install time under 30s assert.LessOrEqual(t, installTime, float64(maxInstallTime)) - //Check install output - checkAgentInstall.Contains(agentLog, expectedLogMsg["InstallFoundNginxAgent"]) - checkAgentInstall.Contains(agentLog, expectedLogMsg["InstallAgentToRunAs"]) - checkAgentInstall.Contains(agentLog, expectedLogMsg["InstallAgentSuccess"]) - checkAgentInstall.Contains(agentLog, expectedLogMsg["InstallAgentStartCmd"]) + // Check install output + assert.Contains(t, agentLog, expectedLogMsgs["InstallFoundNginxAgent"]) + assert.Contains(t, agentLog, expectedLogMsgs["InstallAgentToRunAs"]) + assert.Contains(t, agentLog, expectedLogMsgs["InstallAgentSuccess"]) + assert.Contains(t, agentLog, expectedLogMsgs["InstallAgentStartCmd"]) - //Check nginx-agent config is created. - _, agentConfigErr := os.Stat(expectedAgentDirs["AgentConfigFile"]) - checkAgentInstall.Nil(agentConfigErr) + // Check nginx-agent config is created. + assert.FileExists(t, expectedAgentPaths["AgentConfigFile"]) - //Check nginx-agent system unit file is created. - _, agentServiceFile := os.Stat(expectedAgentDirs["AgentSystemFile"]) - checkAgentInstall.Nil(agentServiceFile) + // Check nginx-agent system unit file is created. + assert.FileExists(t, expectedAgentPaths["AgentSystemFile"]) - //Uninstall the agent package - uninstallLog := uninstallAgent("nginx-agent", t) + // Uninstall the agent package + uninstallLog := uninstallAgent(t, "nginx-agent") - //Check uninstall output - checkAgentInstall.Contains(uninstallLog, expectedLogMsg["UninstallAgent"]) - checkAgentInstall.Contains(uninstallLog, expectedLogMsg["UninstallAgentStopService"]) - checkAgentInstall.Contains(uninstallLog, expectedLogMsg["UninstallAgentPurgingFiles"]) + // Check uninstall output + assert.Contains(t, uninstallLog, expectedLogMsgs["UninstallAgent"]) + assert.Contains(t, uninstallLog, expectedLogMsgs["UninstallAgentStopService"]) + assert.Contains(t, uninstallLog, expectedLogMsgs["UninstallAgentPurgingFiles"]) - //Check nginx-agent config is removed. - _, deletedConfigErr := os.Stat(expectedAgentDirs["AgentConfigFile"]) - checkAgentInstall.NotNil(deletedConfigErr) + // Check nginx-agent config is removed. + assert.NoFileExists(t, expectedAgentPaths["AgentConfigFile"]) - //Check nginx-agent system unit file is removed. - _, deletedServiceFileError := os.Stat(expectedAgentDirs["AgentSystemFile"]) - checkAgentInstall.NotNil(deletedServiceFileError) + // Check nginx-agent system unit file is removed. + assert.NoFileExists(t, expectedAgentPaths["AgentSystemFile"]) } -// Installs the agent returning total install time and install output -func installAgent(agentPackage string, verify *testing.T) (float64, string) { +// installAgent installs the agent returning total install time and install output +func installAgent(t *testing.T, agentPackage string) (float64, string) { + // Get OS to create install cmd + installCmd := createInstallCommand(t) - //Get OS to create install cmd - installCmd := createInstallCommand(verify) - - //Start install timer + // Start install timer start := time.Now() - //Start agent installation and capture install output + // Start agent installation and capture install output cmd := exec.Command(installCmd[0], installCmd[1], installCmd[2], agentPackage) + stdoutStderr, err := cmd.CombinedOutput() - if err != nil { - verify.Errorf("Error with installation: " + err.Error()) - verify.FailNow() - } + require.NoError(t, err) end := time.Now() elapsed := end.Sub(start) @@ -99,33 +105,26 @@ func installAgent(agentPackage string, verify *testing.T) (float64, string) { return float64(elapsed), string(stdoutStderr) } -// Uninstall the agent returning output -func uninstallAgent(agentPackage string, verify *testing.T) string { +// uninstallAgent uninstall the agent returning output +func uninstallAgent(t *testing.T, agentPackage string) string { + // Get OS to create uninstall cmd + uninstallCmd := createUninstallCommand(t) - //Get OS to create uninstall cmd - uninstallCmd := createUninstallCommand(verify) - - //Start agent uninstall and capture uninstall output + // Start agent uninstall and capture uninstall output cmd := exec.Command(uninstallCmd[0], uninstallCmd[1], uninstallCmd[2], uninstallCmd[3], agentPackage) stdoutStderr, err := cmd.CombinedOutput() - if err != nil { - verify.Errorf("Error with uninstall: " + err.Error()) - verify.FailNow() - } + require.NoError(t, err) return string(stdoutStderr) } // Creates install command based on OS func createInstallCommand(t *testing.T) []string { + // Check OS release file exists first to determine OS + require.FileExists(t, osReleasePath) - //Check OS release file exists first to determine OS - _, err := os.Stat(systemDetails["OSReleaseFile"]) - if err != nil { - t.Errorf("Error accessing os-release file " + err.Error()) - } - content, _ := ioutil.ReadFile(systemDetails["OSReleaseFile"]) + content, _ := ioutil.ReadFile(osReleasePath) os := string(content) if strings.Contains(os, "UBUNTU") || strings.Contains(os, "Debian") { return []string{"sudo", "apt", "install"} @@ -136,13 +135,10 @@ func createInstallCommand(t *testing.T) []string { // Creates uninstall command based on OS func createUninstallCommand(t *testing.T) []string { + // Check OS release file exists first to determine OS + require.FileExists(t, osReleasePath) - //Check OS release file exists first to determine OS - _, err := os.Stat(systemDetails["OSReleaseFile"]) - if err != nil { - t.Errorf("Error accessing os-release file " + err.Error()) - } - content, _ := ioutil.ReadFile(systemDetails["OSReleaseFile"]) + content, _ := ioutil.ReadFile(osReleasePath) os := string(content) if strings.Contains(os, "UBUNTU") || strings.Contains(os, "Debian") { return []string{"sudo", "apt", "purge", "-y"} @@ -150,30 +146,3 @@ func createUninstallCommand(t *testing.T) []string { return []string{"sudo", "yum", "remove", "-y"} } } - -func LogMessages() map[string]string { - return map[string]string{ - "ConnectionStatus": "agent_connect_response: configs: > > status: >", - "InstallFoundNginxAgent": "Found nginx-agent /usr/bin/nginx-agent", - "InstallAgentToRunAs": "nginx-agent will be configured to run as same user", - "InstallAgentSuccess": "NGINX Agent package has been successfully installed.", - "InstallAgentStartCmd": "sudo systemctl start nginx-agent", - "UninstallAgent": "Removing nginx-agent", - "UninstallAgentStopService": "Stop and disable nginx-agent service", - "UninstallAgentPurgingFiles": "Purging configuration files for nginx-agent", - } -} - -func AgentDirectories() map[string]string { - return map[string]string{ - "AgentConfigFile": "/etc/nginx-agent/nginx-agent.conf", - "AgentInstallLog": "/tmp/agent-install.log", - "AgentSystemFile": "/etc/systemd/system/multi-user.target.wants/nginx-agent.service", - } -} - -func SystemData() map[string]string { - return map[string]string{ - "OSReleaseFile": "/etc/os-release", - } -} diff --git a/test/performance/vendor/github.com/nginx/agent/v2/src/core/logger/log.go b/test/performance/vendor/github.com/nginx/agent/v2/src/core/logger/log.go index d0a621bab..53b13c34a 100644 --- a/test/performance/vendor/github.com/nginx/agent/v2/src/core/logger/log.go +++ b/test/performance/vendor/github.com/nginx/agent/v2/src/core/logger/log.go @@ -45,7 +45,7 @@ func SetLogFile(logFile string) *os.File { logPath = path.Join(logPath, defaultLogFile) } - logFileHandle, err := os.OpenFile(logPath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0664) + logFileHandle, err := os.OpenFile(logPath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0640) if err != nil { log.Errorf("Failed to set log file, proceeding to log only to stdout/stderr: %v", err) return nil