Use Python to execute the executable jar package.

  1. There are many ways to execute jar generated by Spring boot. Here is the most commonly used example. In the environment with java, you can run the spring boot project directly by using the following command
java -jar app.jar

One disadvantage of this method is that it can't run in the background.

  1. In this case, you need to use a nohup command in linux
nohup command

Purpose: run the command without hanging up.

Syntax: nohup command [Arg []]

Description: the nohup Command runs the Command specified by the Command parameter and any related Arg parameters, ignoring all the sign up signals.

Use the nohup command to run programs in the background after logging out. To run the nohup command in the background, add & to the end of the command.

So just use the command nohup Java - jar website. Jar & to run the program in the background

  1. Problem: to start multiple applications in the same environment and restart them, you need to find the corresponding PID to kill. However, when multiple applications are started, grep search will inevitably find multiple. In this way, there will be risks when killing.
  2. Solution: save PID when application starts. Then kill according to PID
  3. There is no corresponding Properties class in Python, so you need to implement a similar function
  4. This class provides the functions of adding, modifying and querying
  5. Realize interaction and make scripts more general. Here is the whole code of python
#!/usr/bin/env python
# _*_ encoding:utf-8 _*_
import os
import re
import shlex
import subprocess
import sys
import tempfile
import time

# Current filename
_daemon = os.path.basename(__file__)

print "Current filename:%s" % _daemon


class Properties:
    """
    //Property file class
    """

    def __init__(self, file_name):
        """
        //Constructor
        :param file_name:
        """
        exist_file(file_name)

        self.file_name = file_name
        self.properties = {}
        try:
            fopen = open(self.file_name, 'r')
            for line in fopen:
                line = line.strip()
                if line.find('=') > 0 and not line.startswith('#'):
                    strs = line.split('=')
                    self.properties[strs[0].strip()] = strs[1].strip()
        except Exception, e:
            raise e
        else:
            fopen.close()

    def has_key(self, key):
        """
        //Whether KEY exists
        :param key:
        :return:
        """
        return self.properties.has_key(key)

    def get(self, key, default_value=''):
        """
        //Get according to KEY
        :param key:
        :param default_value:
        :return:
        """
        if self.properties.has_key(key):
            return self.properties[key]
        return default_value

    def put(self, key, value):
        """
        //Add / modify profile
        :param key:
        :param value:
        :return:
        """
        self.properties[key] = value
        replace_property(self.file_name, key + '=.*', key + '=' + value, True)

    def get_app_home(self):
        """
        //Return to the directory of jar
        :return:
        """
        return self.get("APP_HOME")

    def get_jar_name(self):
        """
        //Return jar name
        :return:
        """
        return self.get("JAR_NAME")

    def get_java_home(self):
        """
        //Return the directory of JAVA instruction
        :return:
        """
        return self.get("JAVA_HOME")

    def get_main_class(self):
        """
        //Main function
        :return:
        """
        return self.get("MAIN_CLASS")

    def get_server_port(self):
        """
        //Get the port number. If no port number is entered
        //The port number configured in the configuration file is used by default
        :return:
        """
        if self.get("SERVER_PORT") == '':
            return " "
        else:
            return " --server.port=" + props.get("SERVER_PORT")

    def get_run_command(self):
        """
        //Get start command
        :return:
        """
        RUN_COMMAND = "nohup " + self.get_java_home() + " " + get_java_options() + " -jar " + self.get_app_home() + "/" + self.get_jar_name() + self.get_server_port() + " >> /dev/null 2>&1 &"
        return RUN_COMMAND

    def get_program(self):
        """
        //Get the jar and the full path of the port
        :return:
        """
        return self.get_app_home() + "/" + self.get_jar_name() + self.get_server_port()

    def getProgramPid(self):
        return self.get("PROGRAM_ID")

    def startProgram(self):
        p_pid = self.getProgramPid()
        if p_pid != '':
            print("The program seems to have been started pid is :%s" % p_pid)
        else:
            print('Starting program.....')
            args = shlex.split(self.get_run_command())
            print args
            process = subprocess.Popen(args, shell=False, stdin=None, stdout=None)
            pid = process.pid
            # print ("pid:%s" % pid)
            # Save the process id to the configuration file
            self.put("PROGRAM_ID", str(pid))
            # if os.system(self.get_run_command()) == 0:
            print('Program startup success,pid is %s:' % pid)

    def stopProgram(self):
        """
        //Stop program
        :return:
        """
        p_pid = self.getProgramPid()
        if p_pid == '':
            print('%s is not running ...' % self.get_program())
        else:
            os.system('kill ' + p_pid)
            print('Program stopped successfully......')

    def monitor(self):
        while 1:
            time.sleep(10)
            p_pid = self.getProgramPid()
            if p_pid == '':
                print('It seems this program is not running. Start it now!')
                self.startProgram()

    def getDaemonPid(self):
        """
        //Get Python daemons ID
        :return:
        """
        result = self.get("DAEMON_ID")
        return result

    def startDaemon(self):
        """
        //Launch daemons 
        :return:
        """
        d_pid = self.getDaemonPid()
        if d_pid != '':
            print('daemon program is running...')
        else:
            print('starting daemon program...')
            daemon_command = "nohup python %s monitor >> /dev/null 2>&1 &" % _daemon
            process = subprocess.Popen(shlex.split(daemon_command), shell=False, stdin=None, stdout=None)
            pid = process.pid
            self.put("DAEMON_ID", str(pid))
            print('Program startup success,pid is %s:' % pid)

    def stopDaemon(self):
        """
        //Stop Python Daemons
        :return:
        """
        d_pid = self.getDaemonPid()
        if d_pid == '':
            print('Daemon program is not running...')
        else:
            os.system('kill ' + d_pid)
            print('Daemon program was killed......')


def exist_file(file_name):
    """
    //Determine whether the file exists or not. If not, create it
    :param file_name:
    :return:
    """
    if not os.path.exists(file_name):
        os.mknod(file_name)
        os.system("chmod 777  %s" % file_name)
    else:
        print "file %s is found" % file_name


def parse(file_name):
    """
    //Parsing files
    :param file_name:
    :return:
    """
    return Properties(file_name)


def replace_property(file_name, from_regex, to_str, append_on_not_exists=True):
    """
    //Replace attribute
    :param file_name:
    :param from_regex:
    :param to_str:
    :param append_on_not_exists:
    :return:
    """
    file = tempfile.TemporaryFile()  # Create temporary file

    if os.path.exists(file_name):
        r_open = open(file_name, 'r')
        pattern = re.compile(r'' + from_regex)
        found = None
        for line in r_open:  # Read the original file
            if pattern.search(line) and not line.strip().startswith('#'):
                found = True
                line = re.sub(from_regex, to_str, line)
            file.write(line)  # Write temporary file
        if not found and append_on_not_exists:
            file.write('\n' + to_str)
        r_open.close()
        file.seek(0)

        content = file.read()  # Read everything in the temporary file

        if os.path.exists(file_name):
            os.remove(file_name)

        w_open = open(file_name, 'w')
        w_open.write(content)  # Write the contents of the temporary file to the original file
        w_open.close()

        file.close()  # Close temporary files and delete them automatically
    else:
        print "file %s not found" % file_name


def get_java_options():
    """
    java startup parameter
    :return:
    """
    JAVA_OPTS = "-Xms1024m -Xmx1024m -XX:MaxPermSize=2048m -Djava.awt.headless=true -XX:-UseGCOverheadLimit"
    return JAVA_OPTS


if __name__ == '__main__':
    _input_file_path = raw_input('Enter property file name:')
    # file_path = 'demo.properties'
    props = Properties(_input_file_path)  # read file

    # Type the Java environment to start
    if props.has_key('JAVA_HOME'):
        if props.get('JAVA_HOME') == '':
            _input_java_home = raw_input('Enter the JAVA Instruction directory:')
            props.put('JAVA_HOME', _input_java_home)  # Modify / add key=value
        else:
            print 'Configuration in file JAVA Instruction directory:%s' % props.get('JAVA_HOME')
    else:
        _input_java_home = raw_input('Enter the JAVA Instruction directory:')
        props.put('JAVA_HOME', _input_java_home)  # Modify / add key=value

    # Type the jar directory
    if props.has_key('APP_HOME'):
        if props.get('APP_HOME') == '':
            _input_app_home = raw_input('Enter the jar Catalog:')
            props.put('APP_HOME', _input_app_home)  # Modify / add key=value
        else:
            print 'Configuration started in file jar Catalog:%s' % props.get('APP_HOME')
    else:
        _input_app_home = raw_input('Enter the jar Catalog:')
        props.put('APP_HOME', _input_app_home)  # Modify / add key=value

    # Type the name of the jar you started
    if props.has_key('JAR_NAME'):
        if props.get('JAR_NAME') == '':
            _input_jar_name = raw_input('Enter the jar Package name:')
            props.put("JAR_NAME", _input_jar_name)
        else:
            print 'Configuration started in file jar Name:%s' % props.get('JAR_NAME')
    else:
        _input_jar_name = raw_input('Enter the jar Package name:')
        props.put("JAR_NAME", _input_jar_name)

    # Type the site start port
    if props.has_key('SERVER_PORT'):
        if props.get('SERVER_PORT') == '':
            _input_server_port = raw_input('Enter website start port:')
            props.put("SERVER_PORT", _input_server_port)
        else:
            print 'Configure boot port in file:%s' % props.get('SERVER_PORT')
    else:
        _input_server_port = raw_input('Enter website start port:')
        props.put("SERVER_PORT", _input_server_port)

    # print "site start command:% s"% props.get \ run \ command()

    # Type instructions
    if len(sys.argv) == 2:
        args = sys.argv[1]
    else:
        args = raw_input('Enter command parameters: [ start | stop | restart | monitor ]: ')

    if args == 'start':
        props.startProgram()
        props.startDaemon()
    elif args == 'stop':
        props.stopDaemon()
        props.stopProgram()
    elif args == 'restart':
        props.stopDaemon()
        props.stopProgram()
        time.sleep(3)
        props.startProgram()
        props.startDaemon()
    elif args == 'monitor':
        props.monitor()
    else:
        print('nothing to do')

Tags: Java Python Spring shell

Posted on Sun, 03 May 2020 08:06:06 -0700 by Atomic Taco