Skip to content
Snippets Groups Projects
JavaRunner.py 5.49 KiB
Newer Older
  • Learn to ignore specific revisions
  • # Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (https://tfs.etsi.org/)
    #
    # Licensed under the Apache License, Version 2.0 (the "License");
    # you may not use this file except in compliance with the License.
    # You may obtain a copy of the License at
    #
    #      http://www.apache.org/licenses/LICENSE-2.0
    #
    # Unless required by applicable law or agreed to in writing, software
    # distributed under the License is distributed on an "AS IS" BASIS,
    # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    # See the License for the specific language governing permissions and
    # limitations under the License.
    
    import logging,threading, time
    import logging
    from lxml import etree
    import os
    import subprocess
    
    XML_CONFIG_FILE="/var/teraflow/pcep/service/resources/PCEServerConfiguration.xml"
    
    LOGGER = logging.getLogger(__name__)
    
    class JavaRunner:
    
        def __init__(self,address): 
            self.__process=None
            self.__lock = threading.Lock()
            self.__address = address
    
        def getCurrentLocalPort(self):
            with self.__lock:
                return self.__localPort
    
        def getCurrentMngPort(self):
            with self.__lock:
                return self.__managementPort
        def getPid(self):
            return self.__process.pid
    
        def execAndKill(self):
    
            LOGGER.debug("Before exec and kill")
            os.chdir("/var/teraflow/pcep/service/resources/")
            cwd = os.getcwd()
            LOGGER.info("Current working directory: %s", cwd)
            # Security shell=False
            self.__process=subprocess.Popen(['java -jar PCE-jar-with-dependencies.jar '],#+ XML_CONFIG_FILE
                    shell=False,start_new_session=True,stdout=subprocess.PIPE)
            LOGGER.debug("Time to sleep")
            java_pid = self.__process.pid
            print("Java PID:", java_pid)    
            time.sleep(15)
            self.__process.terminate()
    
        def execPcep(self) -> bool:
                """
                Executes java pcep in non-blocking process
                """
                LOGGER.debug("Executing JavaRunner")
                os.chdir("/var/teraflow/pcep/service/resources/")
                try:
                    #self.__process = subprocess.Popen(['java', '-jar', 'Ejecutable_2.jar'],
                    #                                shell=False, start_new_session=True,
                    #                                stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    
                    LOGGER.debug("Executing command: %s", ('java', '-Dlog4j.configurationFile=log4j2.xml', '-jar', 'PCE-jar-with-dependencies.jar', 'PCEServerConfiguration.xml'))
                    self.__process = subprocess.Popen(['java', '-Dlog4j.configurationFile=log4j2.xml', '-jar', 'PCE-jar-with-dependencies.jar', 'PCEServerConfiguration.xml'],
    
                                                    shell=False, start_new_session=True,
                                                    stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    
                    stdout_thread = threading.Thread(target=self.read_stdout)
                    stderr_thread = threading.Thread(target=self.read_stderr)
    
                    stdout_thread.start()
                    stderr_thread.start()
    
                    self.__process.wait()
    
                    stdout_thread.join()
                    stderr_thread.join()
                
                except subprocess.CalledProcessError as err:
                    LOGGER.debug('ERROR: %s', err)
                
                return self.__process
    
        def read_stdout(self):
            try:
                for line in iter(self.__process.stdout.readline, b''):
                    print(f"STDOUT: {line.decode('utf-8')}", flush=True)
            except Exception as e:
                print(f"Error in read_stdout: {e}")
    
        def read_stderr(self):
            try:
                for line in iter(self.__process.stderr.readline, b''):
                    print(f"STDERR: {line.decode('utf-8')}", flush=True)
            except Exception as e:
                print(f"Error in read_stderr: {e}")
    
        def setPort(self,port):
             self.__peerPort=port
             return True
        def setAsNumber(self,asNumber):
             self.__asNumber=asNumber
             return True
    
        def setPeer(self, address) -> bool:
                """
                Sets XML existing config file with peer address and port. TODO: as_number
                """
                XMLParser = etree.XMLParser(remove_blank_text=False)
                tree = etree.parse(XML_CONFIG_FILE, parser=XMLParser)
                root = tree.getroot()
                
                # Find the <LocalPCEAddress> element
                pceAddress = root.find(".//LocalPCEAddress")
    
                #Check if the element is found
                if pceAddress is not None:
                    LOGGER.debug("Old LocalPCEAddress value: %s", pceAddress.text)
                    # Update the text content of the element with the new address
                    pceAddress.text = str(address)
                    LOGGER.debug("New LocalPCEAddress value: %s", pceAddress.text)
                    # Save the modified XML back to the file
                    tree.write(XML_CONFIG_FILE, pretty_print=True)
    
                    return True  # Return True to indicate success
    
                return False  # Return False if the element is not found
                
                #return True
    
        def endBGPSpeaker(self) -> bool:
                """
                Kills java program connected to BGPLS Speaker with SIGKILL signal
                """
                LOGGER.debug("sending kill signal to process %s",self.__process.pid)
                LOGGER.debug("PID: %d",self.__process.pid)
                self.__process.kill()
                return True
        
        def getRunnerInfo(self):
             return self.__address,self.__asNumber,self.__peerPort