Link to home
Start Free TrialLog in
Avatar of Mohammed Hamada
Mohammed HamadaFlag for Portugal

asked on

Install Linux script fails to configure and install an app

I have two scripts, first one Installs Postgres 10 with preconfigured settings for the database, then another one that will install Mirth app to connect to this database. 


postgress is up and running and I can connect to it from PgAdmin, however the script is indicating that it's not running. 


The script is bourne shell which I am not very familiar with. I'd appreciate if someone could tell what's the cause of the error as it's stating that "System appears to not be running a local postgres instance."


Here is my script



#Install Mirth
#!/bin/sh
# This script will install a new Agenta Server instance on a fresh Ubuntu 14.04 server.
# This script is experimental and does not ensure any security.
 
USER_ID=$(id -u)
if [ $USER_ID -ne 0 ]
  then echo "Please run as root"
  exit 70
fi
 
RED='\033[0;31m' # Downloads, apt-get
BLU='\033[0;34m' # Local Edits
NC='\033[0m' # No Color
 
validate_previous_command() {
 RESULT=$?
 ## Check the exit code of previous command. If non-zero, we failed.
 ## Gasp out our dying words to standard out, then fully exit with the original exit code.
 if [ $RESULT -ne 0 ]; then
   echo -e "Previous command ${BLU} ${*} ${NC} appears to have ${RED}failed${NC} with status code: ${RESULT}"
   ## use of BASH_LINENO is unfortunately a bashism. Dash at least simply treats this as empty string.
   ## Furthermore, LINENO is supposed to be supported by POSIX, dash simply hasn't caught up with the times.
   echo -e "Error was detected at line number ${BLU} ${BASH_LINENO} ${NC}."
   echo -e "Install Script will now ${RED}abort${NC}."
   exit $RESULT;
 else
   echo -e " + step ${*} reports success."
 fi
}
 
## Goal here is to check that we don't already have the server running.
## command 'pf' lists all running processes. '-ef' specifies to return all processes.
## pipe to command 'grep' to look for the process of interest.
## pipe to grep again, to exclude the copy of grep that found itself.
# Use || true to catch non-zero exit codes from grep failing to find anything.
INVERT_MATCH="grep\|${0}\|${1}"
## echo $INVERT_MATCH ## Only need to echo this for debugging.
 
MIRTH_RUNNING=$(sudo ps -ef | grep --ignore-case mirth    | grep --invert-match "$INVERT_MATCH" || true)
 
# What did we get back for the mirth instance.
echo $MIRTH_RUNNING
 
# Test here uses '! -z' (not empty) to see if the early grep had any hits.
if [ ! -z "$MIRTH_RUNNING" ]; then
  echo -e "System appears to be ${RED}already running an instance${NC} of Mirth Connect."
  echo -e "Please ${RED}stop${NC} the instance using command:"
  echo "    /usr/local/mirthconnect/mcservice stop "
  exit 80
fi
 
DEFAULT_AWS_FILE_PREFIX=mirth-one-view-develop
AWS_FILE_PREFIX=${1:-$DEFAULT_AWS_FILE_PREFIX}
 
echo "This script will install Agenta Server (Mirth) using default settings."
echo -e "The current AWS file Prefix is: ${RED}${AWS_FILE_PREFIX}${NC}\n"
 
if [ "$AWS_FILE_PREFIX" = "$DEFAULT_AWS_FILE_PREFIX" ]; then
  echo -e "This corresponds to the ${BLU}default development${NC} branch."
  echo -e "If you instead wanted a specific version release or feature branch, please re-run the command as:"
  echo -e "\t${0} mirth-one-view-<branch-or-tag-name>"
  echo -e "Note the branch-or-tag parameter is case-sensitive."
fi
 
## -e ${RED} ${NC}
echo "This script will install mcserver using default settings."
echo -ne "Press ${BLU}Enter${NC} to continue, or ${RED}Ctrl-C${NC} to abort."
 
# Waits for the user to press enter. User might also ctrl-c to cancel.
read enter
 
echo -e "${BLU}Checking for existing Java version on system.${NC}"
java -version # check if we have Java installed or not.
if [ $? -ne 0 ]; then
  echo -e "${RED}Installing Java ...${NC}"
  sudo apt-get install openjdk-11-jdk -y # If no Java, (likely) go install it. Refresh coffee while downloading.
  # if this fails, try `sudo apt install openjdk-11-jre-headless`
  java -version # check if we have Java installed or not.
  validate_previous_command "install java"
else
  echo -e "${BLU}Using existing Java version on system.${NC}"
fi
 
echo -e "${RED}Downloading Mirth Connect Installer ...${NC}"
wget --verbose http://downloads.mirthcorp.com/connect/3.10.1.b280/mirthconnect-3.10.1.b280-unix.sh # Pull the Installer down from Mirth Corp.
validate_previous_command "download mirth installer"
 
echo "Download complete."
 
echo -e "${BLU}Running Mirth Connect Installer ...${NC}"
# echo "This part of the install process may require you to enter data."
 
INSTRUCTIONS="# Hit [Enter] to read the terms.\n
# Automatically uses defaults for everything. Two values require details:\n
# application destination directory should be '/etc/opt/mirthconnect' or '/opt/mirthconnect'\n
# logs destination should be '/logs/mirthconnect'\n
# When it asks you which components to install, select '2,3'\n
# Other than these, continue pressing [Enter] to use the defaults."
# echo $INSTRUCTIONS # Can now be skippped due to piped input below. Including for posterity and debugging.
 
# echo -n "Press Enter to continue."
 
# read enter # Don't make the user do this.
 
## Mirth Install ##
# So the Mirth Installer has a bunch of command line input it wants.
# We're going to feed it prepared input based on suggestion here: https://stackoverflow.com/questions/8352851/how-to-call-shell-script-from-another-shell-script
# Which only half worked, so I switched to this one: https://unix.stackexchange.com/questions/286917/how-can-i-respond-to-a-prompt-within-a-shell-script-running-in-background
 
# We need 18 (!) 'newline' presses for the terms, followed by a '1\n' (To accept them)
# Sometimes we have an existing directory, so add one more \n. If it's not there,
# we just get asked twice about the accept step.
# We then accept the defaults for most things, so 1 newline at first.
# Select  '2,3\n' to omit the administrator launcher install (it's glitchy on command line)
# Then need 9  defaults again.
# We then have the '/opt/mirthconnect\n' and '/logs/mirthconnect\n' section.
# Install Service 'y\n', skip manager, 'n\n', skip readme 'n\n'
# Some remaining steps
MIRTH_SCRIPT_INPUT='o\n\n\n\n\n\n\n
\n\n\n\n\n\n
\n\n\n\n\n\n
1\n
\n
2,3\n
\n\n\n\n\n\n\n\n\n
/opt/mirthconnect\n
/logs/mirthconnect\n
y\n
n\n
n\n
'
 
# run the install script we just pulled, piping in the prepared input above.
echo $MIRTH_SCRIPT_INPUT | sudo sh mirthconnect-3.10.1.b280-unix.sh
validate_previous_command "run mirth installer"
 
echo -e "${BLU}Inspecting Mirth Installation ...${NC}"
cp /usr/local/mirthconnect/client-lib/commons-beanutils-1.9.3.jar /usr/local/mirthconnect/cli-lib/
cp /usr/local/mirthconnect/client-lib/commons-text-*.jar /usr/local/mirthconnect/cli-lib/
ls /usr/local/mirthconnect # check the default install directory.
validate_previous_command "confirm mirth install directory"
 
/usr/local/mirthconnect/mcservice status || true
 
echo -e "${BLU}Shutting down Mirth Connect to edit properties ...${NC}"
sudo /usr/local/mirthconnect/mcservice stop
 
echo -e "${BLU}Configuring Mirth Connect to use local Database ...${NC}"
# We must now update the database settings from the default derby to production grade PostGreSQL.
sudo sed -i.default '/database = derby/c \
database = postgres' /usr/local/mirthconnect/conf/mirth.properties
validate_previous_command "edit mirth property files"
 
# Note wildcard matching following key part.
sudo sed -i.temp '/database.url = jdbc:derby.*/c \
database.url = jdbc:postgresql:\/\/localhost:5432\/mirthdb' /usr/local/mirthconnect/conf/mirth.properties
sudo sed -i.temp '/database.username =/c \
database.username = TestUser' /usr/local/mirthconnect/conf/mirth.properties
sudo sed -i.temp '/database.password/c \
database.password = TestPassword' /usr/local/mirthconnect/conf/mirth.properties
 
echo -e "${BLU}Configuring Mirth Connect to use more Java memory ...${NC}"
sudo sed -i.temp '/-Xmx256m/c \
-Xmx1024m' /usr/local/mirthconnect/mcservice.vmoptions
validate_previous_command "edit mirth vmoptions files"
 
sleep 15s # Give the mirth service we shut down enough time to actually drop.
 
echo -e "${BLU}Restarting Mirth Connect ...${NC}"
sudo /usr/local/mirthconnect/mcservice start
validate_previous_command "reboot mirth server"
 
sleep 15s # We often get weirdness with mirth not being fully booted up when we start this next step.
## Check if Mirth is now running. If it's not, give it more time to think. "|| true" catches non-zero exit codes from grep.
MIRTH_RUNNING_1=$(sudo ps -ef | grep --ignore-case mirthconnect | grep --invert-match "grep" || true)
echo -e "Mirth is Running: ${MIRTH_RUNNING_1}"
if [ -z "$MIRTH_RUNNING_1" ]; then
  echo -e "${BLU}Allowing Mirth extra time to start ...${NC}"
  sleep 15s
 
  ## Give mirth a bit and then try again.
  MIRTH_RUNNING_2=$(sudo ps -ef | grep --ignore-case mirthconnect | grep --invert-match "grep" || true)
  echo -e "Check if Mirth is Running: ${MIRTH_RUNNING_2}"
  if [ -z "$MIRTH_RUNNING_2" ]; then
    echo -e "${RED}WARNING${NC}: Mirth has still not started! ${BLU}restarting ...${NC}"
    sudo /usr/local/mirthconnect/mcservice restart
    sleep 30s
 
    ## Three strikes and you're out.
    MIRTH_RUNNING_3=$(sudo ps -ef | grep --ignore-case mirthconnect | grep --invert-match "grep" || true)
    echo -e "Check if Mirth is Running: ${MIRTH_RUNNING_3}"
    if [ -z "$MIRTH_RUNNING_3" ]; then
      echo -e "${RED}ERROR${NC}: Mirth has failed to start. ${RED}ABORTING.${NC}"
      exit 909 # Exit code chosen arbitrarily.
    fi
  fi
fi
 
echo -e "${RED}Validating that Mirth has started ...${NC}"
curl localhost:8080 -4 --retry 9 --retry-connrefused
# Note, technically we're allowing this to fail.
# Curl in docker needs the -4 flag for connection refused to get treated right.
# https://github.com/appropriate/docker-curl/issues/5
 
echo -e "${BLU}Adding new test user to Mirth ...${NC}"
# Add a new user to the system.
MC_COMMAND_ADD_USER="user add test test test Technologies \"test Technologies LLC\" support@test.com\n
quit\n
"
 
# Log into mccommand, run the above script.
echo $MC_COMMAND_ADD_USER | /usr/local/mirthconnect/mccommand -u admin -p admin
validate_previous_command "add new mirth user"
 
echo -e "${BLU}Granting folder permissions to user ${NEW_OWNER} ...${NC}"
# Update mirth folders to be owned by proper person.
sudo chown --recursive $NEW_OWNER:$NEW_OWNER /opt/mirthconnect
sudo chown --recursive $NEW_OWNER:$NEW_OWNER /logs/mirthconnect
sudo chown --recursive $NEW_OWNER:$NEW_OWNER /usr/local/mirthconnect
validate_previous_command "reassign mirth folder ownership"
 
# Required values.
export AWS_ACCESS_KEY_ID=*******
export AWS_SECRET_ACCESS_KEY=*******
export AWS_DEFAULT_REGION=us-east-2
 
# Pull down starter channels.
SUB_DIRECTORY=mirth-endpoints
echo -e "${RED}Downloading Endpoint Channels folder from AWS S3 ...${NC}"
TARGET_S3_FILE_ENDPOINT_CONF=s3://backend-as-a-service/install-files/$AWS_FILE_PREFIX-endpoint-core-conf.zip
aws s3 cp $TARGET_S3_FILE_ENDPOINT_CONF $SUB_DIRECTORY/mirth-endpoint-core-conf.zip
validate_previous_command "download mirth endpoint files"
 
# Extract the files
unzip -o $SUB_DIRECTORY/mirth-endpoint-core-conf.zip -d $SUB_DIRECTORY
validate_previous_command "extract mirth endpoint files"
 
LOCAL_DIR=$(pwd)/$SUB_DIRECTORY
 
echo -e "${BLU}Loading Core Endpoint Channels into Agenta Server ...${NC}"
 
# Script file
# Import each channel indicated in https://docs.google.com/spreadsheets/d/10iD5n34iAaJuNgOW5qc844T7a4h3aOTQ1Rn8XnP9PwQ/edit#gid=1177050146
MC_COMMAND_INPUT="user remove 1\n
import ${LOCAL_DIR}/EPIC_Router.xml force\n
import ${LOCAL_DIR}/ADPAC_Router.xml force\n
import ${LOCAL_DIR}/Screen_Pop_Router.xml force\n
import ${LOCAL_DIR}/MIRTH_CHANNELS_Healthcheck.xml force\n
import ${LOCAL_DIR}/Request_Log_Read.xml force\n
import ${LOCAL_DIR}/Error_Log.xml force\n
import ${LOCAL_DIR}/Error_Log_Read.xml force\n
import ${LOCAL_DIR}/Error_Emails.xml force\n
import ${LOCAL_DIR}/Usage_Emails.xml force\n
import ${LOCAL_DIR}/Request_Log_Pruner.xml force\n
import ${LOCAL_DIR}/Patient_Lookup.xml force\n
import ${LOCAL_DIR}/Patient_Search.xml force\n
import ${LOCAL_DIR}/Patient_Search_Global.xml force\n
import ${LOCAL_DIR}/Get_SNMP_Stats.xml\n
import ${LOCAL_DIR}/CRON_MonitorStats.xml\n
codetemplate library import ${LOCAL_DIR}/TEMPLATE_LIBRARY_Epic_Extractors.xml force\n
codetemplate library import ${LOCAL_DIR}/TEMPLATE_LIBRARY_Error_Code_Mapping.xml force\n
codetemplate library import ${LOCAL_DIR}/TEMPLATE_LIBRARY_API_Parameter_Functions.xml force\n
codetemplate library import ${LOCAL_DIR}/TEMPLATE_LIBRARY_Input-Validate.xml force\n
codetemplate library import ${LOCAL_DIR}/TEMPLATE_LIBRARY_Code-Templates.xml force\n
codetemplate library import ${LOCAL_DIR}/TEMPLATE_LIBRARY_Encoder-Decoders.xml force\n
codetemplate library import ${LOCAL_DIR}/TEMPLATE_LIBRARY_Stub-Data-Templates.xml force\n
importmap ${LOCAL_DIR}/INSTALL_CONFIG.properties\n
importalert ${LOCAL_DIR}/ROUTER_ERROR_ALERT.xml\n
channel deploy *\n
status\n
quit\n
"
 
# Log into mccommand, run the above script.
echo "$MC_COMMAND_INPUT" | /usr/local/mirthconnect/mccommand -u testuser -p testpass
validate_previous_command "import endpoint files into mirth"
 
 
echo -e "${BLU}Enabling Data Pruner ...${NC}"
# The mirth command line doesn't give us an easy way to manipulate the data pruner.
# However, mirth has an https api we can use instead. Apparently the data pruner is an 'extension',
# so we end up altering the property xml of the requested extension to make the enable happen.
curl --location --insecure --user testuser:testpass \
--request PUT 'https://localhost:8443/api/extensions/Data%20Pruner/properties?mergeProperties=true' \
--header 'Content-Type: application/xml' \
--data-raw '<properties>
<property name="enabled">true</property>
</properties>'
validate_previous_command "enable data pruner"
# TODO: verify
 
 
RESOURCE_DIRECTORY=/usr/local/mirthconnect/ownlib
# Prepare for loading custom resources.
mkdir -p $RESOURCE_DIRECTORY
validate_previous_command "create custom resource directory"
## TODO: verify
 
echo -e "${RED}Downloading custom resources folder from AWS S3 ...${NC}"
 
TARGET_S3_FILE_ENDPOINT_CONF=s3://backend-as-a-service/install-files/$AWS_FILE_PREFIX-custom-resources.zip
aws s3 cp $TARGET_S3_FILE_ENDPOINT_CONF $SUB_DIRECTORY/custom-resources.zip
validate_previous_command "download custom resources from s3"
 
# Extract the files
unzip -o $SUB_DIRECTORY/custom-resources.zip -d $RESOURCE_DIRECTORY
validate_previous_command "extract downloaded zip"
 
echo -e "${BLU}Enabling custom resources ...${NC}"
curl --location --insecure --user testuser:testpass \
--request PUT 'https://localhost:8443/api/server/resources' \
--header 'Content-Type: application/xml' \
--data-raw '<list>
    <com.mirth.connect.plugins.directoryresource.DirectoryResourceProperties version="3.8.1">
        <pluginPointName>Directory Resource</pluginPointName>
        <type>Directory</type>
        <id>Default Resource</id>
        <name>[Default Resource]</name>
        <description>Loads libraries from the custom-lib folder in the Mirth Connect home directory.</description>
        <includeWithGlobalScripts>true</includeWithGlobalScripts>
        <directory>custom-lib</directory>
        <directoryRecursion>true</directoryRecursion>
    </com.mirth.connect.plugins.directoryresource.DirectoryResourceProperties>
    <com.mirth.connect.plugins.directoryresource.DirectoryResourceProperties version="3.8.1">
        <pluginPointName>Directory Resource</pluginPointName>
        <type>Directory</type>
        <id>02745791-6b4b-4d75-874b-68edb6bde7d4</id>
        <name>decryption</name>
        <description></description>
        <includeWithGlobalScripts>true</includeWithGlobalScripts>
        <directory>ownlib</directory>
        <directoryRecursion>true</directoryRecursion>
    </com.mirth.connect.plugins.directoryresource.DirectoryResourceProperties>
</list>'
validate_previous_command "enable custom resources"
 
echo -e "${RED}Querying local healthcheck channels ...${NC}"
curl --location --insecure localhost/healthcheck
validate_previous_command "validate nginx healthcheck endpoint"
 
echo "" # new line
curl --location --insecure localhost/epic/v1/healthcheck
validate_previous_command "validate epic router healthcheck endpoint"
 
echo "" # new line
curl --location --insecure localhost/adpac/v1/healthcheck
validate_previous_command "validate adpac router healthcheck endpoint"
 
# Note success.
echo "" # new line
echo -e "\n${BLU}Installation complete.${NC}\n
${BLU}Changelog can be found at:${NC} ${CHANGELOG_FILENAME}\n
If you have not already done so, ${BLU}run the Postgres and Mirth install scripts${NC}.\n
Please ${RED}restart${NC} the machine and verify the installation.\n"

Open in new window



Avatar of arnold
arnold
Flag of United States of America image

The script is running in the wrong shell.

It looks as though you want the script to run under /bin/bash  not /bin/sh.

What do you get if you run bash -x script?
Also, the "#!" MUST be the first 2 characters in the file - move the "#Install Mirth" comment to after the #! line.

Consider using code snippets for putting large chunks of code in posts. I'll ask someone to add it in your question. 

The error message you report doesn't seem to be coming from the script you posted. Please post the complete output from the script, so that we can see where it happens.
Avatar of dfke
dfke

Hi,

Yes the shebang must be on the first line.


Cheers
Avatar of Mohammed Hamada

ASKER

@arnold, please forgive my ignorance but not sure what do you mean under bin/bash ? 

I am using "sudo sh script.sh" to run the command . does running it under bin/bash means using different way?


@Simon, the actual script doesn't include this word. I just added on my personal notepad file. but thank you

The error is coming from the script here's a screenshot


User generated image


I'm confused. The script checks for running as root, sets a few fixed variables, and checks for a previous version of "mirth" running. The next thing it does is output a couple of lines of text, i.e.
echo "This script will install Agenta Server (Mirth) using default settings."
echo -e "The current AWS file Prefix is: ${RED}${AWS_FILE_PREFIX}${NC}\n"

Open in new window

I don't see that text on your output. Where is the "system appears to not be running" message come from?

Also, @arnold was saying that this appears to be a bash script (it uses the $BASH_LINENO variable, for example), but your shebang line says "#!/bin/sh", and as you have said, you are calling it directly with "sh". If you call it that way, the shebang line is ignored. You need to call it with bash, so
sudo bash script.sh

Open in new window

You can see that you have used "sh" because the "echo" command in "sh" doesn't understand the "-e" parameter (the one to interpret backslash escaped characters) - the output above just echoes the "-e" to the screen.

I tried running it with bash, same result again. I as well don't understand where is this output coming from. 

Could it be due to calling previous error ? before this script I ran another script that installs and configures Postgres 10 + cluster . I checked postgres status and its working just fine. I even updated postgres version to 11.


User generated image


Try running "sudo bash -x script.sh" (as @arnold suggested in the first response!) - the "-x" will print out each line of the script just before it runs it. That will at least show us where the failure is.

Looks like it couldn't run some part of the script but at the end the same result, Does it call another script maybe and run it? 


User generated image


You aren't running the script that you posted. That script has the "MIRTH_RUNNING=" line shown in your output, but no the "POSTGRES_RUNNING=" line immediately following it.

Please post
- the correct script, and remember to remove any credentials in the file. We only really need the text up to the POSTGRES_RUNNING line + a few lines after that to include the if/fi section after it.
- the output of "sudo ps -ef", particularly any "postgres" or "pg" lines.

Apologies, looks like I was actually looking at the wrong script. Here should be the correct one. 


#!/bin/sh


# This script will install a new Agenta Server instance on a fresh Ubuntu 14.04 server.


# This script is experimental and does not ensure any security.






USER_ID=$(id -u)


if [ $USER_ID -ne 0 ]


  then echo "Please run as root"


  exit 70


fi






RED='\033[0;31m' # Downloads, apt-get


BLU='\033[0;34m' # Local Edits


NC='\033[0m' # No Color






validate_previous_command() {


 RESULT=$?


 ## Check the exit code of previous command. If non-zero, we failed.


 ## Gasp out our dying words to standard out, then fully exit with the original exit code.


 if [ $RESULT -ne 0 ]; then


   echo -e "Previous command ${BLU} ${*} ${NC} appears to have ${RED}failed${NC} with status code: ${RESULT}"


   ## use of BASH_LINENO is unfortunately a bashism. Dash at least simply treats this as empty string.


   ## Furthermore, LINENO is supposed to be supported by POSIX, dash simply hasn't caught up with the times.


   echo -e "Error was detected at line number ${BLU} ${BASH_LINENO} ${NC}."


   echo -e "Install Script will now ${RED}abort${NC}."


   exit $RESULT;


 else


   echo -e " + step ${*} reports success."


 fi


}






## Goal here is to check that we don't already have the server running.


## command 'pf' lists all running processes. '-ef' specifies to return all processes.


## pipe to command 'grep' to look for the process of interest.


## pipe to grep again, to exclude the copy of grep that found itself.


# Use || true to catch non-zero exit codes from grep failing to find anything.


INVERT_MATCH="grep\|${0}\|${1}"


## echo $INVERT_MATCH ## Only need to echo this for debugging.






MIRTH_RUNNING=$(sudo ps -ef | grep --ignore-case mirth    | grep --invert-match "$INVERT_MATCH" || true)


POSTGRES_RUNN=$(sudo ps -ef | grep --ignore-case postgres | grep --invert-match "$INVERT_MATCH" || true)






# What did we get back for the mirth instance.


echo $MIRTH_RUNNING






# Test here uses '! -z' (not empty) to see if the early grep had any hits.


if [ ! -z "$MIRTH_RUNNING" ]; then


  echo -e "System appears to be ${RED}already running an instance${NC} of Mirth Connect."


  echo -e "Please ${RED}stop${NC} the instance using command:"


  echo "    /usr/local/mirthconnect/mcservice stop "


  exit 80


fi






echo $POSTGRES_RUNN


# Test here uses ' -z' (is empty) to see if the early grep had any hits.


if [ -z "$POSTGRES_RUNN" ]; then


  echo -e "System appears to not be running a local postgres instance."


  echo -e "Please ${RED}install${NC} the expected postgres instance using script:"


  echo "    agenta_install_ubuntu_psql.sh "


  exit 82


fi






DEFAULT_AWS_FILE_PREFIX=mirth-one-view-develop


AWS_FILE_PREFIX=${1:-$DEFAULT_AWS_FILE_PREFIX}






echo "This script will install Agenta Server (Mirth) using default settings."


echo -e "The current AWS file Prefix is: ${RED}${AWS_FILE_PREFIX}${NC}\n"






if [ "$AWS_FILE_PREFIX" = "$DEFAULT_AWS_FILE_PREFIX" ]; then


  echo -e "This corresponds to the ${BLU}default development${NC} branch."


  echo -e "If you instead wanted a specific version release or feature branch, please re-run the command as:"


  echo -e "\t${0} mirth-one-view-<branch-or-tag-name>"


  echo -e "Note the branch-or-tag parameter is case-sensitive."


fi






## -e ${RED} ${NC}


echo "This script will install mcserver using default settings."


echo -ne "Press ${BLU}Enter${NC} to continue, or ${RED}Ctrl-C${NC} to abort."






# Waits for the user to press enter. User might also ctrl-c to cancel.


read enter






echo -e "${BLU}Checking for existing Java version on system.${NC}"


java -version # check if we have Java installed or not.


if [ $? -ne 0 ]; then


  echo -e "${RED}Installing Java ...${NC}"


  sudo apt-get install openjdk-11-jdk -y # If no Java, (likely) go install it. Refresh coffee while downloading.


  # if this fails, try `sudo apt install openjdk-11-jre-headless`


  java -version # check if we have Java installed or not.


  validate_previous_command "install java"


else


  echo -e "${BLU}Using existing Java version on system.${NC}"


fi






echo -e "${RED}Downloading Mirth Connect Installer ...${NC}"


wget --verbose http://downloads.mirthcorp.com/connect/3.10.1.b280/mirthconnect-3.10.1.b280-unix.sh # Pull the Installer down from Mirth Corp.


validate_previous_command "download mirth installer"






echo "Download complete."






echo -e "${BLU}Running Mirth Connect Installer ...${NC}"


# echo "This part of the install process may require you to enter data."






INSTRUCTIONS="# Hit [Enter] to read the terms.\n


# Automatically uses defaults for everything. Two values require details:\n


# application destination directory should be '/etc/opt/mirthconnect' or '/opt/mirthconnect'\n


# logs destination should be '/logs/mirthconnect'\n


# When it asks you which components to install, select '2,3'\n


# Other than these, continue pressing [Enter] to use the defaults."


# echo $INSTRUCTIONS # Can now be skippped due to piped input below. Including for posterity and debugging.






# echo -n "Press Enter to continue."






# read enter # Don't make the user do this.






## Mirth Install ##


# So the Mirth Installer has a bunch of command line input it wants.


# We're going to feed it prepared input based on suggestion here: https://stackoverflow.com/questions/8352851/how-to-call-shell-script-from-another-shell-script


# Which only half worked, so I switched to this one: https://unix.stackexchange.com/questions/286917/how-can-i-respond-to-a-prompt-within-a-shell-script-running-in-background






# We need 18 (!) 'newline' presses for the terms, followed by a '1\n' (To accept them)


# Sometimes we have an existing directory, so add one more \n. If it's not there,


# we just get asked twice about the accept step.


# We then accept the defaults for most things, so 1 newline at first.


# Select  '2,3\n' to omit the administrator launcher install (it's glitchy on command line)


# Then need 9  defaults again.


# We then have the '/opt/mirthconnect\n' and '/logs/mirthconnect\n' section.


# Install Service 'y\n', skip manager, 'n\n', skip readme 'n\n'


# Some remaining steps


MIRTH_SCRIPT_INPUT='o\n\n\n\n\n\n\n


\n\n\n\n\n\n


\n\n\n\n\n\n


1\n


\n


2,3\n


\n\n\n\n\n\n\n\n\n


/opt/mirthconnect\n


/logs/mirthconnect\n


y\n


n\n


n\n


'






# run the install script we just pulled, piping in the prepared input above.


echo $MIRTH_SCRIPT_INPUT | sudo sh mirthconnect-3.10.1.b280-unix.sh


validate_previous_command "run mirth installer"






echo -e "${BLU}Inspecting Mirth Installation ...${NC}"


cp /usr/local/mirthconnect/client-lib/commons-beanutils-1.9.3.jar /usr/local/mirthconnect/cli-lib/


cp /usr/local/mirthconnect/client-lib/commons-text-*.jar /usr/local/mirthconnect/cli-lib/


ls /usr/local/mirthconnect # check the default install directory.


validate_previous_command "confirm mirth install directory"






/usr/local/mirthconnect/mcservice status || true






echo -e "${BLU}Shutting down Mirth Connect to edit properties ...${NC}"


sudo /usr/local/mirthconnect/mcservice stop






echo -e "${BLU}Configuring Mirth Connect to use local Database ...${NC}"


# We must now update the database settings from the default derby to production grade PostGreSQL.


sudo sed -i.default '/database = derby/c \


database = postgres' /usr/local/mirthconnect/conf/mirth.properties


validate_previous_command "edit mirth property files"






# Note wildcard matching following key part.


sudo sed -i.temp '/database.url = jdbc:derby.*/c \


database.url = jdbc:postgresql:\/\/localhost:5432\/mirthdb' /usr/local/mirthconnect/conf/mirth.properties


sudo sed -i.temp '/database.username =/c \


database.username = test' /usr/local/mirthconnect/conf/mirth.properties


sudo sed -i.temp '/database.password/c \


database.password = test' /usr/local/mirthconnect/conf/mirth.properties






echo -e "${BLU}Configuring Mirth Connect to use more Java memory ...${NC}"


sudo sed -i.temp '/-Xmx256m/c \


-Xmx1024m' /usr/local/mirthconnect/mcservice.vmoptions


validate_previous_command "edit mirth vmoptions files"






SERVICE_VMOPTIONS=$(grep 'add-opens' /usr/local/mirthconnect/mcservice.vmoptions)


SERVER_VMOPTIONS=$(grep 'add-opens' /usr/local/mirthconnect/mcserver.vmoptions)










# Test here uses '-z' (is empty) to see if the early grep had any hits.


# In the event of no hits, we want to add the extra vmoptions to the mcservice and mcserve.


if [  -z "$SERVICE_VMOPTIONS" ]; then


  echo -e "${BLU}Applying VM options change to handle Java 9+ for mcservice...${NC}"


  sudo sh -c 'cat /usr/local/mirthconnect/docs/mcservice-java9+.vmoptions >> /usr/local/mirthconnect/mcservice.vmoptions'


  validate_previous_command "Apply Java 9+ vmoptions to mcservice"


fi






# Test here uses '-z' (is empty) to see if the early grep had any hits.


# In the event of no hits, we want to add the extra vmoptions to the mcservice and mcserve.


if [  -z "$SERVICE_VMOPTIONS" ]; then


  echo -e "${BLU}Applying VM options change to handle Java 9+ for mcservice...${NC}"


  sudo sh -c 'cat /usr/local/mirthconnect/docs/mcservice-java9+.vmoptions >> /usr/local/mirthconnect/mcserver.vmoptions'


  validate_previous_command "Apply Java 9+ vmoptions to mcservice"


fi






sleep 15s # Give the mirth service we shut down enough time to actually drop.






echo -e "${BLU}Restarting Mirth Connect ...${NC}"


sudo /usr/local/mirthconnect/mcservice start


validate_previous_command "reboot mirth server"






sleep 15s # We often get weirdness with mirth not being fully booted up when we start this next step.


## Check if Mirth is now running. If it's not, give it more time to think. "|| true" catches non-zero exit codes from grep.


MIRTH_RUNNING_1=$(sudo ps -ef | grep --ignore-case mirthconnect | grep --invert-match "grep" || true)


echo -e "Mirth is Running: ${MIRTH_RUNNING_1}"


if [ -z "$MIRTH_RUNNING_1" ]; then


  echo -e "${BLU}Allowing Mirth extra time to start ...${NC}"


  sleep 15s






  ## Give mirth a bit and then try again.


  MIRTH_RUNNING_2=$(sudo ps -ef | grep --ignore-case mirthconnect | grep --invert-match "grep" || true)


  echo -e "Check if Mirth is Running: ${MIRTH_RUNNING_2}"


  if [ -z "$MIRTH_RUNNING_2" ]; then


    echo -e "${RED}WARNING${NC}: Mirth has still not started! ${BLU}restarting ...${NC}"


    sudo /usr/local/mirthconnect/mcservice restart


    sleep 30s






    ## Three strikes and you're out.


    MIRTH_RUNNING_3=$(sudo ps -ef | grep --ignore-case mirthconnect | grep --invert-match "grep" || true)


    echo -e "Check if Mirth is Running: ${MIRTH_RUNNING_3}"


    if [ -z "$MIRTH_RUNNING_3" ]; then


      echo -e "${RED}ERROR${NC}: Mirth has failed to start. ${RED}ABORTING.${NC}"


      exit 909 # Exit code chosen arbitrarily.


    fi


  fi


fi






echo -e "${RED}Validating that Mirth has started ...${NC}"


curl localhost:8080 -4 --retry 9 --retry-connrefused


# Note, technically we're allowing this to fail.


# Curl in docker needs the -4 flag for connection refused to get treated right.


# https://github.com/appropriate/docker-curl/issues/5






echo -e "${BLU}Adding new test user to Mirth ...${NC}"


# Add a new user to the system.


MC_COMMAND_ADD_USER="user add test test test Technologies \"test Technologies LLC\" support@test.com\n


quit\n


"






# Log into mccommand, run the above script.


echo $MC_COMMAND_ADD_USER | /usr/local/mirthconnect/mccommand -u admin -p admin


validate_previous_command "add new mirth user"






echo -e "${BLU}Granting folder permissions to user ${NEW_OWNER} ...${NC}"


# Update mirth folders to be owned by proper person.


sudo chown --recursive $NEW_OWNER:$NEW_OWNER /opt/mirthconnect


sudo chown --recursive $NEW_OWNER:$NEW_OWNER /logs/mirthconnect


sudo chown --recursive $NEW_OWNER:$NEW_OWNER /usr/local/mirthconnect


validate_previous_command "reassign mirth folder ownership"






# Required values.










# Pull down starter channels.


SUB_DIRECTORY=mirth-endpoints


echo -e "${RED}Downloading Endpoint Channels folder from AWS S3 ...${NC}"


TARGET_S3_FILE_ENDPOINT_CONF=s3://backend-as-a-service/install-files/$AWS_FILE_PREFIX-endpoint-core-conf.zip


aws s3 cp $TARGET_S3_FILE_ENDPOINT_CONF $SUB_DIRECTORY/mirth-endpoint-core-conf.zip


validate_previous_command "download mirth endpoint files"






# Extract the files


unzip -o $SUB_DIRECTORY/mirth-endpoint-core-conf.zip -d $SUB_DIRECTORY


validate_previous_command "extract mirth endpoint files"






LOCAL_DIR=$(pwd)/$SUB_DIRECTORY






echo -e "${BLU}Loading Core Endpoint Channels into Agenta Server ...${NC}"






# Script file


# Import each channel indicated in 


MC_COMMAND_INPUT="user remove 1\n


import ${LOCAL_DIR}/EPIC_Router.xml force\n


import ${LOCAL_DIR}/ADPAC_Router.xml force\n


import ${LOCAL_DIR}/Screen_Pop_Router.xml force\n


import ${LOCAL_DIR}/Healthcheck.xml force\n


import ${LOCAL_DIR}/Request_Log_Read.xml force\n


import ${LOCAL_DIR}/Error_Log.xml force\n


import ${LOCAL_DIR}/Error_Log_Read.xml force\n


import ${LOCAL_DIR}/Request_Log_Pruner.xml force\n


import ${LOCAL_DIR}/Patient_Lookup.xml force\n


codetemplate library import ${LOCAL_DIR}/TEMPLATE_LIBRARY_Epic_Extractors.xml force\n


codetemplate library import ${LOCAL_DIR}/TEMPLATE_LIBRARY_Error_Code_Mapping.xml force\n


codetemplate library import ${LOCAL_DIR}/TEMPLATE_LIBRARY_API_Parameter_Functions.xml force\n


codetemplate library import ${LOCAL_DIR}/TEMPLATE_LIBRARY_Input-Validate.xml force\n


codetemplate library import ${LOCAL_DIR}/TEMPLATE_LIBRARY_Code-Templates.xml force\n


codetemplate library import ${LOCAL_DIR}/TEMPLATE_LIBRARY_Encoder-Decoders.xml force\n


codetemplate library import ${LOCAL_DIR}/TEMPLATE_LIBRARY_Stub-Data-Templates.xml force\n


importmap ${LOCAL_DIR}/INSTALL_CONFIG.properties\n


importalert ${LOCAL_DIR}/ROUTER_ERROR_ALERT.xml\n


channel deploy *\n


status\n


quit\n


"






# Log into mccommand, run the above script.


echo "$MC_COMMAND_INPUT" | /usr/local/mirthconnect/mccommand -u test -p test


validate_previous_command "import endpoint files into mirth"










echo -e "${BLU}Enabling Data Pruner ...${NC}"


# The mirth command line doesn't give us an easy way to manipulate the data pruner.


# However, mirth has an https api we can use instead. Apparently the data pruner is an 'extension',


# so we end up altering the property xml of the requested extension to make the enable happen.


curl --location --insecure --user test:test \


--request PUT 'https://localhost:8443/api/extensions/Data%20Pruner/properties?mergeProperties=true' \


--header 'Content-Type: application/xml' \


--data-raw '<properties>


<property name="enabled">true</property>


</properties>'


validate_previous_command "enable data pruner"


# TODO: verify










RESOURCE_DIRECTORY=/usr/local/mirthconnect/ownlib


# Prepare for loading custom resources.


mkdir -p $RESOURCE_DIRECTORY


validate_previous_command "create custom resource directory"


## TODO: verify






echo -e "${RED}Downloading custom resources folder from AWS S3 ...${NC}"






TARGET_S3_FILE_ENDPOINT_CONF=s3://backend-as-a-service/install-files/$AWS_FILE_PREFIX-custom-resources.zip


aws s3 cp $TARGET_S3_FILE_ENDPOINT_CONF $SUB_DIRECTORY/custom-resources.zip


validate_previous_command "download custom resources from s3"






# Extract the files


unzip -o $SUB_DIRECTORY/custom-resources.zip -d $RESOURCE_DIRECTORY


validate_previous_command "extract downloaded zip"






echo -e "${BLU}Enabling custom resources ...${NC}"


curl --location --insecure --user test:test \


--request PUT 'https://localhost:8443/api/server/resources' \


--header 'Content-Type: application/xml' \


--data-raw '<list>


    <com.mirth.connect.plugins.directoryresource.DirectoryResourceProperties version="3.8.1">


        <pluginPointName>Directory Resource</pluginPointName>


        <type>Directory</type>


        <id>Default Resource</id>


        <name>[Default Resource]</name>


        <description>Loads libraries from the custom-lib folder in the Mirth Connect home directory.</description>


        <includeWithGlobalScripts>true</includeWithGlobalScripts>


        <directory>custom-lib</directory>


        <directoryRecursion>true</directoryRecursion>


    </com.mirth.connect.plugins.directoryresource.DirectoryResourceProperties>


    <com.mirth.connect.plugins.directoryresource.DirectoryResourceProperties version="3.8.1">


        <pluginPointName>Directory Resource</pluginPointName>


        <type>Directory</type>


        <id>02745791-6b4b-4d75-874b-68edb6bde7d4</id>


        <name>decryption</name>


        <description></description>


        <includeWithGlobalScripts>true</includeWithGlobalScripts>


        <directory>ownlib</directory>


        <directoryRecursion>true</directoryRecursion>


    </com.mirth.connect.plugins.directoryresource.DirectoryResourceProperties>


</list>'


validate_previous_command "enable custom resources"






echo -e "${RED}Querying local healthcheck channels ...${NC}"


curl --location --insecure localhost/healthcheck


validate_previous_command "validate nginx healthcheck endpoint"






echo "" # new line


curl --location --insecure localhost/epic/v1/healthcheck


validate_previous_command "validate epic router healthcheck endpoint"






echo "" # new line


curl --location --insecure localhost/adpac/v1/healthcheck


validate_previous_command "validate adpac router healthcheck endpoint"






# Note success.


echo "" # new line


echo -e "\n${BLU}Installation complete.${NC}\n


${BLU}Changelog can be found at:${NC} ${CHANGELOG_FILENAME}\n


If you have not already done so, ${BLU}run the Postgres and Mirth install scripts${NC}.\n


Please ${RED}restart${NC} the machine and verify the installation.\n"
#!/bin/sh


# This script will install a new Agenta Server instance on a fresh Ubuntu 14.04 server.


# This script is experimental and does not ensure any security.






USER_ID=$(id -u)


if [ $USER_ID -ne 0 ]


  then echo "Please run as root"


  exit 70


fi






RED='\033[0;31m' # Downloads, apt-get


BLU='\033[0;34m' # Local Edits


NC='\033[0m' # No Color






validate_previous_command() {


 RESULT=$?


 ## Check the exit code of previous command. If non-zero, we failed.


 ## Gasp out our dying words to standard out, then fully exit with the original exit code.


 if [ $RESULT -ne 0 ]; then


   echo -e "Previous command ${BLU} ${*} ${NC} appears to have ${RED}failed${NC} with status code: ${RESULT}"


   ## use of BASH_LINENO is unfortunately a bashism. Dash at least simply treats this as empty string.


   ## Furthermore, LINENO is supposed to be supported by POSIX, dash simply hasn't caught up with the times.


   echo -e "Error was detected at line number ${BLU} ${BASH_LINENO} ${NC}."


   echo -e "Install Script will now ${RED}abort${NC}."


   exit $RESULT;


 else


   echo -e " + step ${*} reports success."


 fi


}






## Goal here is to check that we don't already have the server running.


## command 'pf' lists all running processes. '-ef' specifies to return all processes.


## pipe to command 'grep' to look for the process of interest.


## pipe to grep again, to exclude the copy of grep that found itself.


# Use || true to catch non-zero exit codes from grep failing to find anything.


INVERT_MATCH="grep\|${0}\|${1}"


## echo $INVERT_MATCH ## Only need to echo this for debugging.






MIRTH_RUNNING=$(sudo ps -ef | grep --ignore-case mirth    | grep --invert-match "$INVERT_MATCH" || true)


POSTGRES_RUNN=$(sudo ps -ef | grep --ignore-case postgres | grep --invert-match "$INVERT_MATCH" || true)






# What did we get back for the mirth instance.


echo $MIRTH_RUNNING






# Test here uses '! -z' (not empty) to see if the early grep had any hits.


if [ ! -z "$MIRTH_RUNNING" ]; then


  echo -e "System appears to be ${RED}already running an instance${NC} of Mirth Connect."


  echo -e "Please ${RED}stop${NC} the instance using command:"


  echo "    /usr/local/mirthconnect/mcservice stop "


  exit 80


fi






echo $POSTGRES_RUNN


# Test here uses ' -z' (is empty) to see if the early grep had any hits.


if [ -z "$POSTGRES_RUNN" ]; then


  echo -e "System appears to not be running a local postgres instance."


  echo -e "Please ${RED}install${NC} the expected postgres instance using script:"


  echo "    agenta_install_ubuntu_psql.sh "


  exit 82


fi






DEFAULT_AWS_FILE_PREFIX=mirth-one-view-develop


AWS_FILE_PREFIX=${1:-$DEFAULT_AWS_FILE_PREFIX}






echo "This script will install Agenta Server (Mirth) using default settings."


echo -e "The current AWS file Prefix is: ${RED}${AWS_FILE_PREFIX}${NC}\n"






if [ "$AWS_FILE_PREFIX" = "$DEFAULT_AWS_FILE_PREFIX" ]; then


  echo -e "This corresponds to the ${BLU}default development${NC} branch."


  echo -e "If you instead wanted a specific version release or feature branch, please re-run the command as:"


  echo -e "\t${0} mirth-one-view-<branch-or-tag-name>"


  echo -e "Note the branch-or-tag parameter is case-sensitive."


fi






## -e ${RED} ${NC}


echo "This script will install mcserver using default settings."


echo -ne "Press ${BLU}Enter${NC} to continue, or ${RED}Ctrl-C${NC} to abort."






# Waits for the user to press enter. User might also ctrl-c to cancel.


read enter






echo -e "${BLU}Checking for existing Java version on system.${NC}"


java -version # check if we have Java installed or not.


if [ $? -ne 0 ]; then


  echo -e "${RED}Installing Java ...${NC}"


  sudo apt-get install openjdk-11-jdk -y # If no Java, (likely) go install it. Refresh coffee while downloading.


  # if this fails, try `sudo apt install openjdk-11-jre-headless`


  java -version # check if we have Java installed or not.


  validate_previous_command "install java"


else


  echo -e "${BLU}Using existing Java version on system.${NC}"


fi






echo -e "${RED}Downloading Mirth Connect Installer ...${NC}"


wget --verbose http://downloads.mirthcorp.com/connect/3.10.1.b280/mirthconnect-3.10.1.b280-unix.sh # Pull the Installer down from Mirth Corp.


validate_previous_command "download mirth installer"






echo "Download complete."






echo -e "${BLU}Running Mirth Connect Installer ...${NC}"


# echo "This part of the install process may require you to enter data."






INSTRUCTIONS="# Hit [Enter] to read the terms.\n


# Automatically uses defaults for everything. Two values require details:\n


# application destination directory should be '/etc/opt/mirthconnect' or '/opt/mirthconnect'\n


# logs destination should be '/logs/mirthconnect'\n


# When it asks you which components to install, select '2,3'\n


# Other than these, continue pressing [Enter] to use the defaults."


# echo $INSTRUCTIONS # Can now be skippped due to piped input below. Including for posterity and debugging.






# echo -n "Press Enter to continue."






# read enter # Don't make the user do this.






## Mirth Install ##


# So the Mirth Installer has a bunch of command line input it wants.


# We're going to feed it prepared input based on suggestion here: https://stackoverflow.com/questions/8352851/how-to-call-shell-script-from-another-shell-script


# Which only half worked, so I switched to this one: https://unix.stackexchange.com/questions/286917/how-can-i-respond-to-a-prompt-within-a-shell-script-running-in-background






# We need 18 (!) 'newline' presses for the terms, followed by a '1\n' (To accept them)


# Sometimes we have an existing directory, so add one more \n. If it's not there,


# we just get asked twice about the accept step.


# We then accept the defaults for most things, so 1 newline at first.


# Select  '2,3\n' to omit the administrator launcher install (it's glitchy on command line)


# Then need 9  defaults again.


# We then have the '/opt/mirthconnect\n' and '/logs/mirthconnect\n' section.


# Install Service 'y\n', skip manager, 'n\n', skip readme 'n\n'


# Some remaining steps


MIRTH_SCRIPT_INPUT='o\n\n\n\n\n\n\n


\n\n\n\n\n\n


\n\n\n\n\n\n


1\n


\n


2,3\n


\n\n\n\n\n\n\n\n\n


/opt/mirthconnect\n


/logs/mirthconnect\n


y\n


n\n


n\n


'






# run the install script we just pulled, piping in the prepared input above.


echo $MIRTH_SCRIPT_INPUT | sudo sh mirthconnect-3.10.1.b280-unix.sh


validate_previous_command "run mirth installer"






echo -e "${BLU}Inspecting Mirth Installation ...${NC}"


cp /usr/local/mirthconnect/client-lib/commons-beanutils-1.9.3.jar /usr/local/mirthconnect/cli-lib/


cp /usr/local/mirthconnect/client-lib/commons-text-*.jar /usr/local/mirthconnect/cli-lib/


ls /usr/local/mirthconnect # check the default install directory.


validate_previous_command "confirm mirth install directory"






/usr/local/mirthconnect/mcservice status || true






echo -e "${BLU}Shutting down Mirth Connect to edit properties ...${NC}"


sudo /usr/local/mirthconnect/mcservice stop






echo -e "${BLU}Configuring Mirth Connect to use local Database ...${NC}"


# We must now update the database settings from the default derby to production grade PostGreSQL.


sudo sed -i.default '/database = derby/c \


database = postgres' /usr/local/mirthconnect/conf/mirth.properties


validate_previous_command "edit mirth property files"






# Note wildcard matching following key part.


sudo sed -i.temp '/database.url = jdbc:derby.*/c \


database.url = jdbc:postgresql:\/\/localhost:5432\/mirthdb' /usr/local/mirthconnect/conf/mirth.properties


sudo sed -i.temp '/database.username =/c \


database.username = test' /usr/local/mirthconnect/conf/mirth.properties


sudo sed -i.temp '/database.password/c \


database.password = test' /usr/local/mirthconnect/conf/mirth.properties






echo -e "${BLU}Configuring Mirth Connect to use more Java memory ...${NC}"


sudo sed -i.temp '/-Xmx256m/c \


-Xmx1024m' /usr/local/mirthconnect/mcservice.vmoptions


validate_previous_command "edit mirth vmoptions files"






SERVICE_VMOPTIONS=$(grep 'add-opens' /usr/local/mirthconnect/mcservice.vmoptions)


SERVER_VMOPTIONS=$(grep 'add-opens' /usr/local/mirthconnect/mcserver.vmoptions)










# Test here uses '-z' (is empty) to see if the early grep had any hits.


# In the event of no hits, we want to add the extra vmoptions to the mcservice and mcserve.


if [  -z "$SERVICE_VMOPTIONS" ]; then


  echo -e "${BLU}Applying VM options change to handle Java 9+ for mcservice...${NC}"


  sudo sh -c 'cat /usr/local/mirthconnect/docs/mcservice-java9+.vmoptions >> /usr/local/mirthconnect/mcservice.vmoptions'


  validate_previous_command "Apply Java 9+ vmoptions to mcservice"


fi






# Test here uses '-z' (is empty) to see if the early grep had any hits.


# In the event of no hits, we want to add the extra vmoptions to the mcservice and mcserve.


if [  -z "$SERVICE_VMOPTIONS" ]; then


  echo -e "${BLU}Applying VM options change to handle Java 9+ for mcservice...${NC}"


  sudo sh -c 'cat /usr/local/mirthconnect/docs/mcservice-java9+.vmoptions >> /usr/local/mirthconnect/mcserver.vmoptions'


  validate_previous_command "Apply Java 9+ vmoptions to mcservice"


fi






sleep 15s # Give the mirth service we shut down enough time to actually drop.






echo -e "${BLU}Restarting Mirth Connect ...${NC}"


sudo /usr/local/mirthconnect/mcservice start


validate_previous_command "reboot mirth server"






sleep 15s # We often get weirdness with mirth not being fully booted up when we start this next step.


## Check if Mirth is now running. If it's not, give it more time to think. "|| true" catches non-zero exit codes from grep.


MIRTH_RUNNING_1=$(sudo ps -ef | grep --ignore-case mirthconnect | grep --invert-match "grep" || true)


echo -e "Mirth is Running: ${MIRTH_RUNNING_1}"


if [ -z "$MIRTH_RUNNING_1" ]; then


  echo -e "${BLU}Allowing Mirth extra time to start ...${NC}"


  sleep 15s






  ## Give mirth a bit and then try again.


  MIRTH_RUNNING_2=$(sudo ps -ef | grep --ignore-case mirthconnect | grep --invert-match "grep" || true)


  echo -e "Check if Mirth is Running: ${MIRTH_RUNNING_2}"


  if [ -z "$MIRTH_RUNNING_2" ]; then


    echo -e "${RED}WARNING${NC}: Mirth has still not started! ${BLU}restarting ...${NC}"


    sudo /usr/local/mirthconnect/mcservice restart


    sleep 30s






    ## Three strikes and you're out.


    MIRTH_RUNNING_3=$(sudo ps -ef | grep --ignore-case mirthconnect | grep --invert-match "grep" || true)


    echo -e "Check if Mirth is Running: ${MIRTH_RUNNING_3}"


    if [ -z "$MIRTH_RUNNING_3" ]; then


      echo -e "${RED}ERROR${NC}: Mirth has failed to start. ${RED}ABORTING.${NC}"


      exit 909 # Exit code chosen arbitrarily.


    fi


  fi


fi






echo -e "${RED}Validating that Mirth has started ...${NC}"


curl localhost:8080 -4 --retry 9 --retry-connrefused


# Note, technically we're allowing this to fail.


# Curl in docker needs the -4 flag for connection refused to get treated right.


# https://github.com/appropriate/docker-curl/issues/5






echo -e "${BLU}Adding new test user to Mirth ...${NC}"


# Add a new user to the system.


MC_COMMAND_ADD_USER="user add test test test Technologies \"test Technologies LLC\" support@test.com\n


quit\n


"






# Log into mccommand, run the above script.


echo $MC_COMMAND_ADD_USER | /usr/local/mirthconnect/mccommand -u admin -p admin


validate_previous_command "add new mirth user"


echo -e "${BLU}Granting folder permissions to user ${NEW_OWNER} ...${NC}"


# Update mirth folders to be owned by proper person.


sudo chown --recursive $NEW_OWNER:$NEW_OWNER /opt/mirthconnect


sudo chown --recursive $NEW_OWNER:$NEW_OWNER /logs/mirthconnect


sudo chown --recursive $NEW_OWNER:$NEW_OWNER /usr/local/mirthconnect


validate_previous_command "reassign mirth folder ownership"






# Required values.










# Pull down starter channels.


SUB_DIRECTORY=mirth-endpoints


echo -e "${RED}Downloading Endpoint Channels folder from AWS S3 ...${NC}"


TARGET_S3_FILE_ENDPOINT_CONF=s3://backend-as-a-service/install-files/$AWS_FILE_PREFIX-endpoint-core-conf.zip


aws s3 cp $TARGET_S3_FILE_ENDPOINT_CONF $SUB_DIRECTORY/mirth-endpoint-core-conf.zip


validate_previous_command "download mirth endpoint files"






# Extract the files


unzip -o $SUB_DIRECTORY/mirth-endpoint-core-conf.zip -d $SUB_DIRECTORY


validate_previous_command "extract mirth endpoint files"






LOCAL_DIR=$(pwd)/$SUB_DIRECTORY






echo -e "${BLU}Loading Core Endpoint Channels into Agenta Server ...${NC}"






# Script file


# Import each channel indicated in 


MC_COMMAND_INPUT="user remove 1\n


import ${LOCAL_DIR}/EPIC_Router.xml force\n


import ${LOCAL_DIR}/ADPAC_Router.xml force\n


import ${LOCAL_DIR}/Screen_Pop_Router.xml force\n


import ${LOCAL_DIR}/Healthcheck.xml force\n


import ${LOCAL_DIR}/Request_Log_Read.xml force\n


import ${LOCAL_DIR}/Error_Log.xml force\n


import ${LOCAL_DIR}/Error_Log_Read.xml force\n


import ${LOCAL_DIR}/Request_Log_Pruner.xml force\n


import ${LOCAL_DIR}/Patient_Lookup.xml force\n


codetemplate library import ${LOCAL_DIR}/TEMPLATE_LIBRARY_Epic_Extractors.xml force\n


codetemplate library import ${LOCAL_DIR}/TEMPLATE_LIBRARY_Error_Code_Mapping.xml force\n


codetemplate library import ${LOCAL_DIR}/TEMPLATE_LIBRARY_API_Parameter_Functions.xml force\n


codetemplate library import ${LOCAL_DIR}/TEMPLATE_LIBRARY_Input-Validate.xml force\n


codetemplate library import ${LOCAL_DIR}/TEMPLATE_LIBRARY_Code-Templates.xml force\n


codetemplate library import ${LOCAL_DIR}/TEMPLATE_LIBRARY_Encoder-Decoders.xml force\n


codetemplate library import ${LOCAL_DIR}/TEMPLATE_LIBRARY_Stub-Data-Templates.xml force\n


importmap ${LOCAL_DIR}/INSTALL_CONFIG.properties\n


importalert ${LOCAL_DIR}/ROUTER_ERROR_ALERT.xml\n


channel deploy *\n


status\n


quit\n


"


# Log into mccommand, run the above script.


echo "$MC_COMMAND_INPUT" | /usr/local/mirthconnect/mccommand -u test -p test


validate_previous_command "import endpoint files into mirth"










echo -e "${BLU}Enabling Data Pruner ...${NC}"


# The mirth command line doesn't give us an easy way to manipulate the data pruner.


# However, mirth has an https api we can use instead. Apparently the data pruner is an 'extension',


# so we end up altering the property xml of the requested extension to make the enable happen.


curl --location --insecure --user test:test \


--request PUT 'https://localhost:8443/api/extensions/Data%20Pruner/properties?mergeProperties=true' \


--header 'Content-Type: application/xml' \


--data-raw '<properties>


<property name="enabled">true</property>


</properties>'


validate_previous_command "enable data pruner"


# TODO: verify










RESOURCE_DIRECTORY=/usr/local/mirthconnect/ownlib


# Prepare for loading custom resources.


mkdir -p $RESOURCE_DIRECTORY


validate_previous_command "create custom resource directory"


## TODO: verify






echo -e "${RED}Downloading custom resources folder from AWS S3 ...${NC}"






TARGET_S3_FILE_ENDPOINT_CONF=s3://backend-as-a-service/install-files/$AWS_FILE_PREFIX-custom-resources.zip


aws s3 cp $TARGET_S3_FILE_ENDPOINT_CONF $SUB_DIRECTORY/custom-resources.zip


validate_previous_command "download custom resources from s3"






# Extract the files


unzip -o $SUB_DIRECTORY/custom-resources.zip -d $RESOURCE_DIRECTORY


validate_previous_command "extract downloaded zip"






echo -e "${BLU}Enabling custom resources ...${NC}"


curl --location --insecure --user test:test \


--request PUT 'https://localhost:8443/api/server/resources' \


--header 'Content-Type: application/xml' \


--data-raw '<list>


    <com.mirth.connect.plugins.directoryresource.DirectoryResourceProperties version="3.8.1">


        <pluginPointName>Directory Resource</pluginPointName>


        <type>Directory</type>


        <id>Default Resource</id>


        <name>[Default Resource]</name>


        <description>Loads libraries from the custom-lib folder in the Mirth Connect home directory.</description>


        <includeWithGlobalScripts>true</includeWithGlobalScripts>


        <directory>custom-lib</directory>


        <directoryRecursion>true</directoryRecursion>


    </com.mirth.connect.plugins.directoryresource.DirectoryResourceProperties>


    <com.mirth.connect.plugins.directoryresource.DirectoryResourceProperties version="3.8.1">


        <pluginPointName>Directory Resource</pluginPointName>


        <type>Directory</type>


        <id>02745791-6b4b-4d75-874b-68edb6bde7d4</id>


        <name>decryption</name>


        <description></description>


        <includeWithGlobalScripts>true</includeWithGlobalScripts>


        <directory>ownlib</directory>


        <directoryRecursion>true</directoryRecursion>


    </com.mirth.connect.plugins.directoryresource.DirectoryResourceProperties>


</list>'


validate_previous_command "enable custom resources"






echo -e "${RED}Querying local healthcheck channels ...${NC}"


curl --location --insecure localhost/healthcheck


validate_previous_command "validate nginx healthcheck endpoint"






echo "" # new line


curl --location --insecure localhost/epic/v1/healthcheck


validate_previous_command "validate epic router healthcheck endpoint"






echo "" # new line


curl --location --insecure localhost/adpac/v1/healthcheck


validate_previous_command "validate adpac router healthcheck endpoint"






# Note success.


echo "" # new line


echo -e "\n${BLU}Installation complete.${NC}\n


${BLU}Changelog can be found at:${NC} ${CHANGELOG_FILENAME}\n


If you have not already done so, ${BLU}run the Postgres and Mirth install scripts${NC}.\n


Please ${RED}restart${NC} the machine and verify the installation.\n"































Open in new window


I think it's the POSTGRES_RUNN= line which is the problem.

We'll need the "sudo ps -ef" output to be sure, but I think that the "grep" on ps, then "grep -v grep" is breaking. I would always advise against doing this - it's all fine until the command t
you want happens to have the string "grep" somewhere in it (e.g. "analyse_planningreport.sh"), or in your case, whatever the first parameter to the script  is. You are better off using the pgrep command.

You're absolutely right, echo  $MIRTH_RUNNING and echo $POSTGRES_RUNN returns empty although when I run both without latest portion of the command I do get a result.


Here is what I did, I took the line 79 and ran it like this

"POSTGRES_RUNN=$(sudo ps -ef | grep --ignore-case postgres)" 


Then did echo $POSTGRES_RUNN .. I get a result about the process. 


With pgrep I ran the below command but still got no result like the line 79.

POSTGRES_RUNN=$(sudo pgrep -fi mirth | grep -i --invert-match "$INVERT_MATCH" || true)


you should not include sudo in the sript, it is not necessary to elevated to run ps -ef

i.e.you elevated rights when you run the script.

I think the main cause of the issue is the second grep. it should exclude if there are any errors but its resulting in cancelling the first grep thus returning an empty value for the variable POSTGRES_RUNN



INVERT_MATCH="grep\|${0}\|${1}"


## echo $INVERT_MATCH ## Only need to echo this for debugging.


MIRTH_RUNNING=$(ps -ef | grep mirth | { grep -v grep || true; } | grep --invert-match "$INVERT_MATCH" || true)


POSTGRES_RUNN=$(sudo ps -ef | grep --ignore-case postgres | grep --invert-match "$INVERT_MATCH" || true)

Open in new window


ASKER CERTIFIED SOLUTION
Avatar of simon3270
simon3270
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial

Hi Simon,


What you did seems to have fixed the postgres issue but now it's complaining about mirth, I managed to get passed this by slightly changing the ps command to the below 


User generated image


I used this one instead


ps -fC to specificlly look for a running process with the exact name instead of getting other results 


User generated image


Do you think this is the right way of doing it? 


Thank you very much


It seems the script is also failing when setting up mirth and choosing to setup default directory. I am getting the following error when the script attempts to install


User generated image


My guess is that the issue in the first few lines where it supposed to setup the mirthconnect directory. because after the script failed with this outcome , I couldn't find the directory at all


User generated image



MIRTH_SCRIPT_INPUT='o\n\n\n\n\n\n\n


\n\n\n\n\n\n


\n\n\n\n\n\n


1\n


\n


2,3\n


\n\n\n\n\n\n\n\n\n


/opt/mirthconnect\n


/logs/mirthconnect\n


y\n


n\n


n\n


'



# run the install script we just pulled, piping in the prepared input above.


echo $MIRTH_SCRIPT_INPUT | sudo sh mirthconnect-3.10.1.b280-unix.sh


validate_previous_command "run mirth installer"




echo -e "${BLU}Inspecting Mirth Installation ...${NC}"


cp /usr/local/mirthconnect/client-lib/commons-beanutils-1.9.3.jar /usr/local/mirthconnect/cli-lib/


cp /usr/local/mirthconnect/client-lib/commons-text-*.jar /usr/local/mirthconnect/cli-lib/


ls /usr/local/mirthconnect # check the default install directory.


validate_previous_command "confirm mirth install directory"

Open in new window


Yes, "ps -fC" is one way to do it, though "pgrep" would have the same effect. That's why I asked to see the "ps - ef" output, so we could find a good search pattern.

As for the mirth installation failure, that's probably a new question (we can't fix all problems in such a long script in one question!). My guess is that the "mirthconnect" install script has changed, or the MIRTH_SCRIPT_INPUT is not quite correct.

A few suggestions:
- Please use "bash", not "sh". The script is clearly written for bash, and running it with sh will cause it to behave wrongly.
- If you get an error like this, "bash -x" will show you what the script was doing.
- If the fix is not obvious, try running the last few commands before the failure manually. Add "exit 0" to the script after the bit you know is working. Then in your "bash" shell, set any shell variables that you need, and run each command by copying individual lines from the script and pasting them on the command line. The first check after running each command should be "echo $?" to make sure that the return code is zero. Then check that the command did what you expected.

In future, if you can show output as text rather than an image, it would make our life easier. I know some remote desktop systems make that hard, and in the past I have had to email myself text output from the system I was running the commands on.

Thanks a lot Simon, I agree with you I have opened this in a different question URL . I would appreciate your help with that one as well 

https://www.experts-exchange.com/dashboard/#/questions/29256286