Пример #1
0
def _check_when_disabled(config):
    """Stop agent.

    Args:
        agent_filepath: Filepath of agent to be restarted.
        agent_name: Agent name

    Returns:
        None

    """
    # Get agent status variables
    agent_name = config.agent_name()
    pidfile = daemon.pid_file(agent_name)

    # Shutdown agent if running
    if os.path.isfile(pidfile) is True:
        with open(pidfile, 'r') as f_handle:
            pidvalue = int(f_handle.readline().strip())
        if psutil.pid_exists(pidvalue) is True:
            log_message = ('Agent "%s" is alive, but should be disabled. '
                           'Attempting to stop.'
                           '') % (agent_name)
            log.log2info(1032, log_message)
            _stop(config)
Пример #2
0
    def start(self):
        """Start the daemon.

        Args:
            None

        Returns:

        """
        # Check for a pidfile to see if the daemon already runs
        try:
            with open(self.pidfile, 'r') as pf_handle:
                pid = int(pf_handle.read().strip())

        except IOError:
            pid = None

        if pid:
            log_message = (
                'PID file: %s already exists. Daemon already running?'
                '') % (self.pidfile)
            log.log2die(1062, log_message)

        # Start the daemon
        # self.daemonize()

        # Log success
        log_message = ('Daemon Started - PID file: %s') % (self.pidfile)
        log.log2info(1070, log_message)

        # Run code for daemon
        self.run()
Пример #3
0
    def stop(self):
        """Stop the daemon.

        Args:
            None

        Returns:

        """
        # Get the pid from the pidfile
        try:
            with open(self.pidfile, 'r') as pf_handle:
                pid = int(pf_handle.read().strip())
        except IOError:
            pid = None

        if not pid:
            log_message = ('PID file: %s does not exist. Daemon not running?'
                           '') % (self.pidfile)
            log.log2warning(1063, log_message)
            # Not an error in a restart
            return

        # Try killing the daemon process
        try:
            while 1:
                if self.lockfile is None:
                    os.kill(pid, signal.SIGTERM)
                else:
                    time.sleep(0.3)
                    if os.path.exists(self.lockfile) is True:
                        continue
                    else:
                        os.kill(pid, signal.SIGTERM)
                time.sleep(0.3)
        except OSError as err:
            error = str(err.args)
            if error.find("No such process") > 0:
                self.delpid()
                self.dellock()
            else:
                log_message = (str(err.args))
                log_message = ('%s - PID file: %s') % (log_message,
                                                       self.pidfile)
                log.log2die(1068, log_message)
        except:
            log_message = ('Unknown daemon "stop" error for PID file: %s'
                           '') % (self.pidfile)
            log.log2die(1066, log_message)

        # Log success
        self.delpid()
        self.dellock()
        log_message = ('Daemon Stopped - PID file: %s') % (self.pidfile)
        log.log2info(1071, log_message)
Пример #4
0
    def purge(self):
        """Purge data from cache by posting to central server.

        Args:
            None

        Returns:
            success: "True: if successful

        """
        # Initialize key variables
        id_agent = self.data['id_agent']

        # Add files in cache directory to list only if they match the
        # cache suffix
        all_filenames = [
            filename for filename in os.listdir(self.cache_dir)
            if os.path.isfile(os.path.join(self.cache_dir, filename))
        ]
        filenames = [
            filename for filename in all_filenames
            if filename.endswith(self.cache_suffix)
        ]

        # Read cache file
        for filename in filenames:
            # Only post files for our own UID value
            if id_agent not in filename:
                continue

            # Get the full filepath for the cache file and post
            filepath = os.path.join(self.cache_dir, filename)
            with open(filepath, 'r') as f_handle:
                try:
                    data = json.load(f_handle)
                except:
                    # Log removal
                    log_message = (
                        'Error reading previously cached agent data file %s '
                        'for agent %s. May be corrupted.'
                        '') % (filepath, self.name())
                    log.log2die(1064, log_message)

            # Post file
            success = self.post(save=False, data=data)

            # Delete file if successful
            if success is True:
                os.remove(filepath)

                # Log removal
                log_message = ('Purging cache file %s after successfully '
                               'contacting server %s'
                               '') % (filepath, self.url)
                log.log2info(1029, log_message)
Пример #5
0
    def post(self, save=True, data=None):
        """Post data to central server.

        Args:
            save: When True, save data to cache directory if postinf fails
            data: Data to post. If None, then uses self.data

        Returns:
            success: "True: if successful

        """
        # Initialize key variables
        success = False
        response = False
        timestamp = self.data['timestamp']
        id_agent = self.data['id_agent']

        # Create data to post
        if data is None:
            data = self.data

        # Post data save to cache if this fails
        try:
            result = requests.post(self.url, json=data)
            response = True
        except:
            if save is True:
                # Create a unique very long filename to reduce risk of
                filename = ('%s/%s_%s.json') % (self.cache_dir, timestamp,
                                                self.cache_suffix)

                # Save data
                with open(filename, 'w') as f_handle:
                    json.dump(data, f_handle)

        # Define success
        if response is True:
            if result.status_code == 200:
                success = True

        # Log message
        if success is True:
            log_message = ('Agent "%s" successfully contacted server %s'
                           '') % (self.name(), self.url)
            log.log2info(1027, log_message)
        else:
            log_message = ('Agent "%s" failed to contact server %s'
                           '') % (self.name(), self.url)
            log.log2warning(1028, log_message)

        # Return
        return success
Пример #6
0
def _start(config):
    """Start agent.

    Args:
        config: Agent configuration object

    Returns:
        None

    """
    # Initialize key variables
    agent_name = config.agent_name()
    agent_filepath = _agent_filepath(config)

    # Start
    log_message = ('Starting agent "%s".' '') % (agent_name)
    log.log2info(1077, log_message)
    command2run = ('%s --start') % (agent_filepath)
    _execute(command2run)
Пример #7
0
def _check_when_enabled(config):
    """Stop agent.

    Args:
        config: Agent configuration object

    Returns:
        None

    """
    # Initialize key variables
    agent_name = config.agent_name()
    agent_filepath = _agent_filepath(config)

    # Get agent status variables
    pidfile = daemon.pid_file(agent_name)
    lockfile = daemon.lock_file(agent_name)

    # Ignore agents that cannot be found
    if os.path.isfile(agent_filepath) is False:
        log_message = ('Agent executable file %s listed in the '
                       'configuration file '
                       'of agent "%s" does not exist. Please fix.'
                       '') % (agent_filepath, agent_name)
        log.log2info(1075, log_message)
        return

    # Check for pid file
    if os.path.isfile(pidfile) is True:
        with open(pidfile, 'r') as f_handle:
            pidvalue = int(f_handle.readline().strip())

        # Check if service died catastrophically. No PID file
        if psutil.pid_exists(pidvalue) is False:
            log_message = ('Agent "%s" is dead. Attempting to restart.'
                           '') % (agent_name)
            log.log2info(1041, log_message)

            # Remove PID file and restart
            os.remove(pidfile)
            _restart(config)

        else:
            # Check if agent hung without updating the PID
            if config.monitor_agent_pid() is True:
                try:
                    mtime = os.path.getmtime(pidfile)
                except OSError:
                    mtime = 0
                if mtime < int(time.time()) - (60 * 10):
                    log_message = ('Agent "%s" is hung. Attempting to restart.'
                                   '') % (agent_name)
                    log.log2info(1076, log_message)
                    _restart(config)
    else:
        if os.path.isfile(lockfile) is True:
            _restart(config)
        else:
            _start(config)