Ejemplo n.º 1
0
    def __init__(self,
                 username,
                 agent_id,
                 operation_id,
                 success,
                 error=None,
                 status_code=None,
                 uri=None,
                 method=None):
        """
        Args:
            username (str): The name of the user who made this api call
            agent_id (str): 36 character UUID of the agent.
            operation_id (str): 36 character UUID of the operation.
            success (str): true or false.

        Kwargs:
            error (str): The error message, if the operation failed.
            status_code (int): The exact status of this operation.
            uri (str): The uri which was called for the results.
            method (str): The method used to call this api.

        Basic Usage:
            >>> from vFense.operations.results import OperationResults
            >>> username = '******'
            >>> operation_id = '8fed3dc7-33d4-4278-9bd4-398a68bf7f22'
            >>> agent_id = 'db6bf07-c5da-4494-93bb-109db205ca64'
            >>> success = 'true'
            >>> results = OperationResults(
                    username, agent_id, operation_id, success
                )
        """

        self.agent_id = agent_id
        self.operation_id = operation_id
        self.username = username
        self.uri = uri
        self.method = method
        self.agent_data = get_agent_info(self.agent_id)
        self.operation_data = get_agent_operation(self.operation_id)
        self.customer_name = self.agent_data[AgentKey.CustomerName]
        self.date_now = DbTime.time_now()
        self.begining_of_time = DbTime.begining_of_time()
        self.error = error
        self.success = success
        self.status_code = status_code
        self.operation = (AgentOperation(
            self.username,
            self.customer_name,
        ))
Ejemplo n.º 2
0
def update_agent_status(agent_id, username=None, uri=None, method=None):
    """Update the status of an agent.
    Args:
        agent_id (str): 36 character uuid of the agent you are updating.

    Kwargs:
        user_name (str): The name of the user who called this function.
        uri (str): The uri that was used to call this function.
        method (str): The HTTP methos that was used to call this function.

    Basic Usage:
        >>> from vFense.core.agent.agents import update_agent_status
        >>> agent_id = '0a1f9a3c-9200-42ef-ba63-f4fd17f0644c'
        >>> update_agent_status(agent_id)
        {
            'uri': None,
            'rv_status_code': 1008,
            'http_method': None,
            'http_status': 200,
            'message': 'admin - agent 52faa1db-290a-47a7-a4cf-e4ad70e25c38 was updated',
            'data': {'needs_reboot': 'no'}
        }
    """
    status = update_agent_status.func_name + ' - '
    now = time()
    agent_data = {
        AgentKey.LastAgentUpdate: DbTime.epoch_time_to_db_time(now),
        AgentKey.AgentStatus: 'up'
    }
    status_code, count, error, generated_ids = (update_agent_data(
        agent_id, agent_data))
    if status_code == DbCodes.Replaced:
        msg = 'agent_id %s updated'
        generic_status_code = GenericCodes.ObjectUpdated
        vfense_status_code = AgentCodes.AgentsUpdated

    elif status_code == DbCodes.Skipped:
        msg = 'agent_id %s does not exist'
        generic_status_code = GenericFailureCodes.FailedToUpdateObject
        vfense_status_code = AgentFailureCodes.AgentsDoesNotExist

    elif status_code == DbCodes.Errors:
        msg = 'agent_id %s could not be updated'
        generic_status_code = GenericFailureCodes.FailedToUpdateObject
        vfense_status_code = AgentFailureCodes.AgentsFailedToUpdate

    agent_data[AgentKey.LastAgentUpdate] = now

    results = {
        ApiResultKeys.DB_STATUS_CODE: status_code,
        ApiResultKeys.GENERIC_STATUS_CODE: generic_status_code,
        ApiResultKeys.VFENSE_STATUS_CODE: vfense_status_code,
        ApiResultKeys.MESSAGE: status + msg,
        ApiResultKeys.DATA: [],
        ApiResultKeys.USERNAME: username,
        ApiResultKeys.URI: uri,
        ApiResultKeys.HTTP_METHOD: method
    }

    return results
Ejemplo n.º 3
0
    def __init__(
            self, username, agent_id, operation_id,
            success, error=None, status_code=None,
            uri=None, method=None
        ):
        """
        Args:
            username (str): The name of the user who made this api call
            agent_id (str): 36 character UUID of the agent.
            operation_id (str): 36 character UUID of the operation.
            success (str): true or false.

        Kwargs:
            error (str): The error message, if the operation failed.
            status_code (int): The exact status of this operation.
            uri (str): The uri which was called for the results.
            method (str): The method used to call this api.

        Basic Usage:
            >>> from vFense.operations.results import OperationResults
            >>> username = '******'
            >>> operation_id = '8fed3dc7-33d4-4278-9bd4-398a68bf7f22'
            >>> agent_id = 'db6bf07-c5da-4494-93bb-109db205ca64'
            >>> success = 'true'
            >>> results = OperationResults(
                    username, agent_id, operation_id, success
                )
        """

        self.agent_id = agent_id
        self.operation_id = operation_id
        self.username = username
        self.uri = uri
        self.method = method
        self.agent_data = get_agent_info(self.agent_id)
        self.operation_data = get_agent_operation(self.operation_id)
        self.customer_name = self.agent_data[AgentKey.CustomerName]
        self.date_now = DbTime.time_now()
        self.begining_of_time = DbTime.begining_of_time()
        self.error = error
        self.success = success
        self.status_code = status_code
        self.operation = (
            AgentOperation(
                self.username, self.customer_name,
            )
        )
Ejemplo n.º 4
0
 def __init__(self, username, customer_name, agent_id, os_code, os_string):
     self.username = username
     self.agent_id = agent_id
     self.customer_name = customer_name
     self.os_code = os_code
     self.os_string = os_string
     self.inserted_count = 0
     self.updated_count = 0
     self.modified_time = DbTime.time_now()
Ejemplo n.º 5
0
def update_agent_status(agent_id, username=None, uri=None, method=None):
    """Update the status of an agent.
    Args:
        agent_id (str): 36 character uuid of the agent you are updating.

    Kwargs:
        user_name (str): The name of the user who called this function.
        uri (str): The uri that was used to call this function.
        method (str): The HTTP methos that was used to call this function.

    Basic Usage:
        >>> from vFense.core.agent.agents import update_agent_status
        >>> agent_id = '0a1f9a3c-9200-42ef-ba63-f4fd17f0644c'
        >>> update_agent_status(agent_id)
        {
            'uri': None,
            'rv_status_code': 1008,
            'http_method': None,
            'http_status': 200,
            'message': 'admin - agent 52faa1db-290a-47a7-a4cf-e4ad70e25c38 was updated',
            'data': {'needs_reboot': 'no'}
        }
    """
    status = update_agent_status.func_name + " - "
    now = time()
    agent_data = {AgentKey.LastAgentUpdate: DbTime.epoch_time_to_db_time(now), AgentKey.AgentStatus: "up"}
    status_code, count, error, generated_ids = update_agent_data(agent_id, agent_data)
    if status_code == DbCodes.Replaced:
        msg = "agent_id %s updated"
        generic_status_code = GenericCodes.ObjectUpdated
        vfense_status_code = AgentCodes.AgentsUpdated

    elif status_code == DbCodes.Skipped:
        msg = "agent_id %s does not exist"
        generic_status_code = GenericFailureCodes.FailedToUpdateObject
        vfense_status_code = AgentFailureCodes.AgentsDoesNotExist

    elif status_code == DbCodes.Errors:
        msg = "agent_id %s could not be updated"
        generic_status_code = GenericFailureCodes.FailedToUpdateObject
        vfense_status_code = AgentFailureCodes.AgentsFailedToUpdate

    agent_data[AgentKey.LastAgentUpdate] = now

    results = {
        ApiResultKeys.DB_STATUS_CODE: status_code,
        ApiResultKeys.GENERIC_STATUS_CODE: generic_status_code,
        ApiResultKeys.VFENSE_STATUS_CODE: vfense_status_code,
        ApiResultKeys.MESSAGE: status + msg,
        ApiResultKeys.DATA: [],
        ApiResultKeys.USERNAME: username,
        ApiResultKeys.URI: uri,
        ApiResultKeys.HTTP_METHOD: method,
    }

    return results
Ejemplo n.º 6
0
    def add_agent_to_operation(self, agent_id, operation_id):
        """Add an operation for an agent
        Args:
            agent_id (str): the agent id.
            operation_id (str): the operation id.

        Basic Usage:
            >>> from vFense.operations.agent_operations import AgentOperation
            >>> username = '******'
            >>> customer_name = 'default'
            >>> oper = AgentOperation(username, customer_name)
            >>> operation_id = '5dc03727-de89-460d-b2a7-7f766c83d2f1'
            >>> agent_id = '38c1c67e-436f-4652-8cae-f1a2ac2dd4a2'
            >>> oper.add_agent_to_operation(
                    agent_id, operation_id
                )

        Returns:
            36 character UUID of the operation that was created for the agent.
        """
        data_to_insert = {
            OperationPerAgentKey.AgentId: agent_id,
            OperationPerAgentKey.OperationId: operation_id,
            OperationPerAgentKey.CustomerName: self.customer_name,
            OperationPerAgentKey.Status: OperationPerAgentCodes.PendingPickUp,
            OperationPerAgentKey.PickedUpTime: DbTime.begining_of_time(),
            OperationPerAgentKey.ExpiredTime: DbTime.begining_of_time(),
            OperationPerAgentKey.CompletedTime: DbTime.begining_of_time(),
            OperationPerAgentKey.Errors: None
        }

        status_code, count, errors, generated_ids = (
            insert_agent_into_agent_operations(data_to_insert)
        )

        if status_code == DbCodes.Inserted:
            operation_id = generated_ids[0]

        else:
            operation_id = None

        return operation_id
Ejemplo n.º 7
0
    def __init__(self, username, customer_name):
        """
        Args:
            username (str): the name of the user who created the operation.
            customer_name (str): the name of the customer this user is part of.

        Basic Usage:
            >>> from vFense.operations.agent_operations import AgentOperation
            >>> username = '******'
            >>> customer_name = 'default'
            >>> oper = AgentOperation(username, customer_name)
        """
        self.username = username
        self.customer_name = customer_name
        self.now = mktime(datetime.now().timetuple())
        self.db_time = DbTime.time_now()
        self.INIT_COUNT = 0
Ejemplo n.º 8
0
def update_agent(agent_id, system_info, hardware, rebooted, username=None, customer_name=None, uri=None, method=None):
    """Update various aspects of agent
    Args:
        agent_id (str): 36 character uuid of the agent you are updating
        system_info (dict): Dictionary with system related info
        hardware (dict):  List of dictionaries that rpresent the hardware
        rebooted (str): yes or no

    Kwargs:
        user_name (str): The name of the user who called this function.
        customer_name (str): The name of the customer.
        uri (str): The uri that was used to call this function.
        method (str): The HTTP methos that was used to call this function.
    """
    results = {ApiResultKeys.USERNAME: username, ApiResultKeys.URI: uri, ApiResultKeys.HTTP_METHOD: method}
    agent_data = {}
    try:
        now = time()
        agent_orig_info = fetch_agent_info(agent_id)
        if agent_orig_info:
            agent_data[AgentKey.Hardware] = hardware

            for key, value in system_info.items():
                agent_data[key] = value

            agent_data[AgentKey.LastAgentUpdate] = DbTime.epoch_time_to_db_time(now)
            agent_data[AgentKey.HostName] = agent_orig_info.get(AgentKey.HostName, None)
            agent_data[AgentKey.DisplayName] = agent_orig_info.get(AgentKey.DisplayName, None)

            if rebooted == CommonKeys.YES:
                agent_data[AgentKey.NeedsReboot] = CommonKeys.NO

            status_code, count, error, generated_ids = update_agent_data(agent_id, agent_data)

            if status_code == DbCodes.Replaced and count > 0:
                Hardware().add(agent_id, hardware)
                msg = "agent %s updated successfully." % (agent_id)

                results[ApiResultKeys.GENERIC_STATUS_CODE] = GenericCodes.ObjectUpdated
                results[ApiResultKeys.VFENSE_STATUS_CODE] = AgentResultCodes.ResultsUpdated
                results[ApiResultKeys.MESSAGE] = msg
                results[ApiResultKeys.DATA] = [agent_data]
                results[ApiResultKeys.UPDATED_IDS] = [agent_id]

            elif status_code == DbCodes.Unchanged:
                Hardware().add(agent_id, hardware)
                msg = "agent %s unchanged, data is the same." % (agent_id)

                results[ApiResultKeys.GENERIC_STATUS_CODE] = GenericCodes.ObjectUnchanged
                results[ApiResultKeys.VFENSE_STATUS_CODE] = AgentResultCodes.ResultsUpdated
                results[ApiResultKeys.MESSAGE] = msg
                results[ApiResultKeys.DATA] = [agent_data]
                results[ApiResultKeys.UNCHANGED_IDS] = [agent_id]

            elif status_code == DbCodes.Skipped:
                msg = "agent %s does not exist." % (agent_id)

                results[ApiResultKeys.GENERIC_STATUS_CODE] = GenericFailureCodes.InvalidId
                results[ApiResultKeys.VFENSE_STATUS_CODE] = AgentFailureCodes.AgentsDoesNotExist
                results[ApiResultKeys.MESSAGE] = msg
                results[ApiResultKeys.DATA] = [agent_data]

            elif status_code == DbCodes.Errors:
                msg = "operation failed" % (error)

                results[ApiResultKeys.GENERIC_STATUS_CODE] = GenericFailureCodes.FailedToUpdateObject
                results[ApiResultKeys.VFENSE_STATUS_CODE] = AgentFailureResultCodes.ResultsFailedToUpdate
                results[ApiResultKeys.MESSAGE] = msg

        else:
            msg = "agent %s does not exist." % (agent_id)

            results[ApiResultKeys.GENERIC_STATUS_CODE] = GenericFailureCodes.InvalidId
            results[ApiResultKeys.VFENSE_STATUS_CODE] = AgentFailureCodes.AgentsDoesNotExist
            results[ApiResultKeys.MESSAGE] = msg
            results[ApiResultKeys.DATA] = [agent_data]

    except Exception as e:
        logger.exception(e)
        msg = "operation failed" % (error)

        results[ApiResultKeys.GENERIC_STATUS_CODE] = GenericFailureCodes.FailedToUpdateObject
        results[ApiResultKeys.VFENSE_STATUS_CODE] = AgentFailureResultCodes.ResultsFailedToUpdate
        results[ApiResultKeys.MESSAGE] = msg

    return results
Ejemplo n.º 9
0
def add_agent(system_info, hardware, username=None, customer_name=None, uri=None, method=None):
    """Add a new agent to the database
    Args:
        system_info (dict): Dictionary with system related info
        hardware (list):  List of dictionaries that rpresent the hardware

    Kwargs:
        user_name (str): The name of the user who called this function.
        customer_name (str): The name of the customer.
        uri (str): The uri that was used to call this function.
        method (str): The HTTP methos that was used to call this function.

    Basic Usage:
        >>> from vFense.core.agent.agents import add_agent

    Returns:
        Dictionary
    """
    results = {ApiResultKeys.USERNAME: username, ApiResultKeys.URI: uri, ApiResultKeys.HTTP_METHOD: method}
    try:
        now = time()
        agent_data = {}
        agent_data[AgentKey.AgentStatus] = AgentStatusKeys.UP
        agent_data[AgentKey.MachineType] = AgentVirtualKeys.PHYSICAL
        agent_data[AgentKey.Tags] = []
        agent_data[AgentKey.NeedsReboot] = CommonKeys.NO
        agent_data[AgentKey.DisplayName] = None
        agent_data[AgentKey.HostName] = None
        agent_data[AgentKey.CustomerName] = customer_name
        agent_data[AgentKey.Hardware] = hardware

        if not AgentKey.ProductionLevel in system_info:
            agent_data[AgentKey.ProductionLevel] = ProductionLevels.PRODUCTION

        if customer_name != "default":
            cexists = get_customer(customer_name)
            if not cexists and len(customer_name) >= 1:
                customer = Customer(customer_name)

                create_customer(customer, username=username, uri=uri, method=method)

        for key, value in system_info.items():
            agent_data[key] = value

        agent_data[AgentKey.LastAgentUpdate] = DbTime.epoch_time_to_db_time(now)

        object_status, object_count, error, generated_ids = insert_agent_data(agent_data)
        if object_status == DbCodes.Inserted and object_count > 0:
            agent_id = generated_ids.pop()
            Hardware().add(agent_id, agent_data[AgentKey.Hardware])
            data = {
                AgentKey.AgentId: agent_id,
                AgentKey.CustomerName: agent_data[AgentKey.CustomerName],
                AgentKey.ComputerName: agent_data[AgentKey.ComputerName],
                AgentKey.Hardware: agent_data[AgentKey.Hardware],
                AgentKey.Tags: agent_data[AgentKey.Tags],
                AgentKey.OsCode: agent_data[AgentKey.OsCode],
                AgentKey.OsString: agent_data[AgentKey.OsString],
            }
            msg = "new agent_operation succeeded"
            generic_status_code = GenericCodes.ObjectCreated
            vfense_status_code = AgentResultCodes.NewAgentSucceeded
            results[ApiResultKeys.GENERIC_STATUS_CODE] = generic_status_code
            results[ApiResultKeys.VFENSE_STATUS_CODE] = vfense_status_code
            results[ApiResultKeys.MESSAGE] = msg
            results[ApiResultKeys.DATA] = [data]
            results[ApiResultKeys.GENERATED_IDS] = [agent_id]

        elif object_status == DbCodes.Errors:
            msg = "new agent operation failed" % (error)
            generic_status_code = GenericFailureCodes.FailedToCreateObject
            vfense_status_code = AgentFailureResultCodes.NewAgentFailed
            results[ApiResultKeys.GENERIC_STATUS_CODE] = generic_status_code
            results[ApiResultKeys.VFENSE_STATUS_CODE] = vfense_status_code
            results[ApiResultKeys.MESSAGE] = msg

    except Exception as e:
        logger.exception(e)
        msg = "new agent operation failed" % (e)
        generic_status_code = GenericFailureCodes.FailedToCreateObject
        vfense_status_code = AgentFailureResultCodes.NewAgentFailed
        results[ApiResultKeys.GENERIC_STATUS_CODE] = generic_status_code
        results[ApiResultKeys.VFENSE_STATUS_CODE] = vfense_status_code
        results[ApiResultKeys.MESSAGE] = msg

    return results
Ejemplo n.º 10
0
    def create_operation(
            self, operation, plugin, agent_ids,
            tag_id, cpu_throttle=None, net_throttle=None,
            restart=None, performed_on=vFenseObjects.AGENT,
        ):
        """Create the base operation. Here is where the
            operation_id is generated. 
        Args:
            operation (str): The operation (install_os_apps, reboot, etc..).
            plugin (str): The plugin this operation is from (rv, core, ra, erc..).
            agent_ids (list): List of agent ids, this operation is being performed on.
            tag_id (str): The tag id, that this operation is being performed on.

        Kwargs:
            cpu_throttle (str): The default is normal, do not throttle.
            net_throttle (int): The default is 0, do not throttle.
            restart (str): The default is none, do not restart.
            performed_on (str): The default is agent.

        Basic Usage:
            >>> from vFense.operations.agent_operations import AgentOperation
            >>> username = '******'
            >>> customer_name = 'default'
            >>> oper = AgentOperation(username, customer_name)
            >>> operation = 'reboot'
            >>> plugin = 'core'
            >>> agent_ids = ['38c1c67e-436f-4652-8cae-f1a2ac2dd4a2']
            >>> tag_id = None
            >>> performed_on = 'agent'
            >>> oper.create_operation(operation, plugin, agent_ids, tag_id)

        Returns:
            String The 36 character UUID of the operation that was created.
            6c0209d5-b350-48b7-808a-158ddacb6940
        """

        number_of_agents = len(agent_ids)
        keys_to_insert = (
            {
                AgentOperationKey.Plugin: plugin,
                AgentOperationKey.Operation: operation,
                AgentOperationKey.OperationStatus: (
                    AgentOperationCodes.ResultsIncomplete
                ),
                AgentOperationKey.CustomerName: self.customer_name,
                AgentOperationKey.CreatedBy: self.username,
                AgentOperationKey.ActionPerformedOn: performed_on,
                AgentOperationKey.TagId: tag_id,
                AgentOperationKey.AgentIds: agent_ids,
                AgentOperationKey.AgentsTotalCount: number_of_agents,
                AgentOperationKey.AgentsExpiredCount: self.INIT_COUNT,
                AgentOperationKey.AgentsPendingResultsCount: self.INIT_COUNT,
                AgentOperationKey.AgentsPendingPickUpCount: number_of_agents,
                AgentOperationKey.AgentsFailedCount: self.INIT_COUNT,
                AgentOperationKey.AgentsCompletedCount: self.INIT_COUNT,
                AgentOperationKey.AgentsCompletedWithErrorsCount: (
                    self.INIT_COUNT
                ),
                AgentOperationKey.CreatedTime: self.db_time,
                AgentOperationKey.UpdatedTime: self.db_time,
                AgentOperationKey.CompletedTime: DbTime.begining_of_time(),
                AgentOperationKey.Restart: restart,
                AgentOperationKey.CpuThrottle: cpu_throttle,
                AgentOperationKey.NetThrottle: net_throttle,
            }
        )
        status_code, count, errors, generated_ids = (
            insert_into_agent_operations(keys_to_insert)
        )
        if status_code == DbCodes.Inserted:
            operation_id = generated_ids[0]

        else:
            operation_id = None

        return operation_id
Ejemplo n.º 11
0
    def add_agent_to_install_operation(self, agent_id, operation_id,
                                       applications):
        """Add an install operation for an agent
        Args:
            agent_id (str): the agent id.
            operation_id (str): the operation id.
            applications (list): List of application dictionairies.

        Basic Usage:
            >>> from vFense.operations.agent_operations import AgentOperation
            >>> username = '******'
            >>> customer_name = 'default'
            >>> oper = AgentOperation(username, customer_name)
            >>> operation_id = '5dc03727-de89-460d-b2a7-7f766c83d2f1'
            >>> agent_id = '38c1c67e-436f-4652-8cae-f1a2ac2dd4a2'
            >>> applications = [
                    {
                        'app_id': '70d462913faad1ecaa85eda4c448a607164fe39414c8be44405e7ab4f7f8467c',
                        'app_name': 'linux-firmware'
                    }
                ]
            >>> oper.add_agent_to_install_operation(
                    agent_id, operation_id, applications
                )

        Returns:
            Boolean
        """
        completed = False
        operation_data = {
            OperationPerAgentKey.AgentId: agent_id,
            OperationPerAgentKey.OperationId: operation_id,
            OperationPerAgentKey.CustomerName: self.customer_name,
            OperationPerAgentKey.Status: OperationPerAgentCodes.PendingPickUp,
            OperationPerAgentKey.PickedUpTime: DbTime.begining_of_time(),
            OperationPerAgentKey.ExpiredTime: DbTime.begining_of_time(),
            OperationPerAgentKey.CompletedTime: DbTime.begining_of_time(),
            OperationPerAgentKey.AppsTotalCount: len(applications),
            OperationPerAgentKey.AppsPendingCount: len(applications),
            OperationPerAgentKey.AppsFailedCount: self.INIT_COUNT,
            OperationPerAgentKey.AppsCompletedCount: self.INIT_COUNT,
            OperationPerAgentKey.Errors: None
        }

        status_code, count, errors, generated_ids = (
            insert_agent_into_agent_operations(operation_data))
        if status_code == DbCodes.Inserted:
            apps = []
            for app in applications:
                apps.append({
                    OperationPerAppKey.AgentId:
                    agent_id,
                    OperationPerAppKey.OperationId:
                    operation_id,
                    OperationPerAppKey.CustomerName:
                    self.customer_name,
                    OperationPerAppKey.Results:
                    (AgentOperationCodes.ResultsPending),
                    OperationPerAppKey.ResultsReceivedTime:
                    (DbTime.begining_of_time()),
                    OperationPerAppKey.AppId:
                    app[OperationPerAppKey.AppId],
                    OperationPerAppKey.AppName:
                    (app[OperationPerAppKey.AppName]),
                    OperationPerAppKey.AppVersion:
                    (app[OperationPerAppKey.AppVersion]),
                    OperationPerAppKey.AppsRemoved: [],
                    OperationPerAppKey.Errors:
                    None
                })

            status_code, count, errors, generated_ids = (
                insert_app_into_agent_operations(apps))
            if status_code == DbCodes.Inserted:
                completed = True

        return completed
Ejemplo n.º 12
0
def add_or_update_apps_per_agent(agent_id, app_dict_list, now=None,
        delete_afterwards=True, collection=AppCollections.AppsPerAgent):

    """Add or update apps for an agent.

    Args:
        agent_id (str): The 36 character UUID of the agent.
        app_dict_list (list): List of dictionaries.

    Kwargs:
        now (float|int): The time in epoch
            default = None
        collection (str): The name of the collection this is applied too.
            default = apps_per_agent

    Basic Usage:
        >>> from vFense.plugins.patching._db import add_or_update_apps_per_agent
        >>> collection = 'apps_per_agent'
        >>> now = 1399075090.83746
        >>> agent_id = '78211125-3c1e-476a-98b6-ea7f683142b3'
        >>> delete_unused_apps = True
        >>> app_dict_list = [
                {
                    "status": "installed",
                    "install_date": 1397697799,
                    "app_id": "c71c32209119ad585dd77e67c082f57f1d18395763a5fb5728c02631d511df5c",
                    "update": 5014,
                    "dependencies": [],
                    "agent_id": "78211125-3c1e-476a-98b6-ea7f683142b3",
                    "last_modified_time": 1398997520,
                    "id": "000182347981c7b54577817fd93aa6cab39477c6dc59fd2dd8ba32e15914b28f",
                    "customer_name": "default"
                }
            ]
        >>> add_or_update_apps_per_agent(
                app_dict_list, now,
                delete_unused_apps,
                collection
            )

    Returns:
        Tuple
        >>> (insert_count, updated_count, deleted_count)

    """
    updated = 0
    inserted = 0
    deleted = 0

    status_code, count, _, _ = (
        update_apps_per_agent(app_dict_list, collection)
    )

    if isinstance(count, list):
        if len(count) > 1:
            inserted = count[0]
            updated = count[1]

    else:
        if status_code == DbCodes.Replaced:
            updated = count
        elif status_code == DbCodes.Inserted:
            inserted = count

    if delete_afterwards:
        if not now:
            now = DbTime.time_now()
        else:
            if isinstance(now, float) or isinstance(now, int):
                now = DbTime.epoch_time_to_db_time(now)

        status_code, count, _, _ = (
            delete_apps_per_agent_older_than(agent_id, now, collection)
        )

        deleted = count

    return inserted, updated, deleted
Ejemplo n.º 13
0
def update_agent(agent_id,
                 system_info,
                 hardware,
                 rebooted,
                 username=None,
                 customer_name=None,
                 uri=None,
                 method=None):
    """Update various aspects of agent
    Args:
        agent_id (str): 36 character uuid of the agent you are updating
        system_info (dict): Dictionary with system related info
        hardware (dict):  List of dictionaries that rpresent the hardware
        rebooted (str): yes or no

    Kwargs:
        user_name (str): The name of the user who called this function.
        customer_name (str): The name of the customer.
        uri (str): The uri that was used to call this function.
        method (str): The HTTP methos that was used to call this function.
    """
    results = {
        ApiResultKeys.USERNAME: username,
        ApiResultKeys.URI: uri,
        ApiResultKeys.HTTP_METHOD: method
    }
    agent_data = {}
    try:
        now = time()
        agent_orig_info = fetch_agent_info(agent_id)
        if agent_orig_info:
            agent_data[AgentKey.Hardware] = hardware

            for key, value in system_info.items():
                agent_data[key] = value

            agent_data[AgentKey.LastAgentUpdate] = (
                DbTime.epoch_time_to_db_time(now))
            agent_data[AgentKey.HostName] = (agent_orig_info.get(
                AgentKey.HostName, None))
            agent_data[AgentKey.DisplayName] = (agent_orig_info.get(
                AgentKey.DisplayName, None))

            if rebooted == CommonKeys.YES:
                agent_data[AgentKey.NeedsReboot] = CommonKeys.NO

            status_code, count, error, generated_ids = (update_agent_data(
                agent_id, agent_data))

            if status_code == DbCodes.Replaced and count > 0:
                Hardware().add(agent_id, hardware)
                msg = 'agent %s updated successfully.' % (agent_id)

                results[ApiResultKeys.GENERIC_STATUS_CODE] = \
                    GenericCodes.ObjectUpdated
                results[ApiResultKeys.VFENSE_STATUS_CODE] = \
                    AgentResultCodes.ResultsUpdated
                results[ApiResultKeys.MESSAGE] = msg
                results[ApiResultKeys.DATA] = [agent_data]
                results[ApiResultKeys.UPDATED_IDS] = [agent_id]

            elif status_code == DbCodes.Unchanged:
                Hardware().add(agent_id, hardware)
                msg = 'agent %s unchanged, data is the same.' % (agent_id)

                results[ApiResultKeys.GENERIC_STATUS_CODE] = \
                    GenericCodes.ObjectUnchanged
                results[ApiResultKeys.VFENSE_STATUS_CODE] = \
                    AgentResultCodes.ResultsUpdated
                results[ApiResultKeys.MESSAGE] = msg
                results[ApiResultKeys.DATA] = [agent_data]
                results[ApiResultKeys.UNCHANGED_IDS] = [agent_id]

            elif status_code == DbCodes.Skipped:
                msg = 'agent %s does not exist.' % (agent_id)

                results[ApiResultKeys.GENERIC_STATUS_CODE] = \
                    GenericFailureCodes.InvalidId
                results[ApiResultKeys.VFENSE_STATUS_CODE] = \
                    AgentFailureCodes.AgentsDoesNotExist
                results[ApiResultKeys.MESSAGE] = msg
                results[ApiResultKeys.DATA] = [agent_data]

            elif status_code == DbCodes.Errors:
                msg = 'operation failed' % (error)

                results[ApiResultKeys.GENERIC_STATUS_CODE] = \
                    GenericFailureCodes.FailedToUpdateObject
                results[ApiResultKeys.VFENSE_STATUS_CODE] = \
                    AgentFailureResultCodes.ResultsFailedToUpdate
                results[ApiResultKeys.MESSAGE] = msg

        else:
            msg = 'agent %s does not exist.' % (agent_id)

            results[ApiResultKeys.GENERIC_STATUS_CODE] = \
                    GenericFailureCodes.InvalidId
            results[ApiResultKeys.VFENSE_STATUS_CODE] = \
                    AgentFailureCodes.AgentsDoesNotExist
            results[ApiResultKeys.MESSAGE] = msg
            results[ApiResultKeys.DATA] = [agent_data]

    except Exception as e:
        logger.exception(e)
        msg = 'operation failed' % (error)

        results[ApiResultKeys.GENERIC_STATUS_CODE] = \
            GenericFailureCodes.FailedToUpdateObject
        results[ApiResultKeys.VFENSE_STATUS_CODE] = \
            AgentFailureResultCodes.ResultsFailedToUpdate
        results[ApiResultKeys.MESSAGE] = msg

    return results
Ejemplo n.º 14
0
def add_agent(system_info,
              hardware,
              username=None,
              customer_name=None,
              uri=None,
              method=None):
    """Add a new agent to the database
    Args:
        system_info (dict): Dictionary with system related info
        hardware (list):  List of dictionaries that rpresent the hardware

    Kwargs:
        user_name (str): The name of the user who called this function.
        customer_name (str): The name of the customer.
        uri (str): The uri that was used to call this function.
        method (str): The HTTP methos that was used to call this function.

    Basic Usage:
        >>> from vFense.core.agent.agents import add_agent

    Returns:
        Dictionary
    """
    results = {
        ApiResultKeys.USERNAME: username,
        ApiResultKeys.URI: uri,
        ApiResultKeys.HTTP_METHOD: method
    }
    try:
        now = time()
        agent_data = {}
        agent_data[AgentKey.AgentStatus] = AgentStatusKeys.UP
        agent_data[AgentKey.MachineType] = AgentVirtualKeys.PHYSICAL
        agent_data[AgentKey.Tags] = []
        agent_data[AgentKey.NeedsReboot] = CommonKeys.NO
        agent_data[AgentKey.DisplayName] = None
        agent_data[AgentKey.HostName] = None
        agent_data[AgentKey.CustomerName] = customer_name
        agent_data[AgentKey.Hardware] = hardware

        if not AgentKey.ProductionLevel in system_info:
            agent_data[AgentKey.ProductionLevel] = ProductionLevels.PRODUCTION

        if customer_name != 'default':
            cexists = get_customer(customer_name)
            if not cexists and len(customer_name) >= 1:
                customer = Customer(customer_name)

                create_customer(customer,
                                username=username,
                                uri=uri,
                                method=method)

        for key, value in system_info.items():
            agent_data[key] = value

        agent_data[AgentKey.LastAgentUpdate] = (
            DbTime.epoch_time_to_db_time(now))

        object_status, object_count, error, generated_ids = (
            insert_agent_data(agent_data))
        if object_status == DbCodes.Inserted and object_count > 0:
            agent_id = generated_ids.pop()
            Hardware().add(agent_id, agent_data[AgentKey.Hardware])
            data = {
                AgentKey.AgentId: agent_id,
                AgentKey.CustomerName: agent_data[AgentKey.CustomerName],
                AgentKey.ComputerName: agent_data[AgentKey.ComputerName],
                AgentKey.Hardware: agent_data[AgentKey.Hardware],
                AgentKey.Tags: agent_data[AgentKey.Tags],
                AgentKey.OsCode: agent_data[AgentKey.OsCode],
                AgentKey.OsString: agent_data[AgentKey.OsString],
            }
            msg = 'new agent_operation succeeded'
            generic_status_code = GenericCodes.ObjectCreated
            vfense_status_code = AgentResultCodes.NewAgentSucceeded
            results[ApiResultKeys.GENERIC_STATUS_CODE] = generic_status_code
            results[ApiResultKeys.VFENSE_STATUS_CODE] = vfense_status_code
            results[ApiResultKeys.MESSAGE] = msg
            results[ApiResultKeys.DATA] = [data]
            results[ApiResultKeys.GENERATED_IDS] = [agent_id]

        elif object_status == DbCodes.Errors:
            msg = 'new agent operation failed' % (error)
            generic_status_code = GenericFailureCodes.FailedToCreateObject
            vfense_status_code = AgentFailureResultCodes.NewAgentFailed
            results[ApiResultKeys.GENERIC_STATUS_CODE] = generic_status_code
            results[ApiResultKeys.VFENSE_STATUS_CODE] = vfense_status_code
            results[ApiResultKeys.MESSAGE] = msg

    except Exception as e:
        logger.exception(e)
        msg = 'new agent operation failed' % (e)
        generic_status_code = GenericFailureCodes.FailedToCreateObject
        vfense_status_code = AgentFailureResultCodes.NewAgentFailed
        results[ApiResultKeys.GENERIC_STATUS_CODE] = generic_status_code
        results[ApiResultKeys.VFENSE_STATUS_CODE] = vfense_status_code
        results[ApiResultKeys.MESSAGE] = msg

    return results
Ejemplo n.º 15
0
    def add_agent_to_install_operation(
            self, agent_id, operation_id, applications
        ):
        """Add an install operation for an agent
        Args:
            agent_id (str): the agent id.
            operation_id (str): the operation id.
            applications (list): List of application dictionairies.

        Basic Usage:
            >>> from vFense.operations.agent_operations import AgentOperation
            >>> username = '******'
            >>> customer_name = 'default'
            >>> oper = AgentOperation(username, customer_name)
            >>> operation_id = '5dc03727-de89-460d-b2a7-7f766c83d2f1'
            >>> agent_id = '38c1c67e-436f-4652-8cae-f1a2ac2dd4a2'
            >>> applications = [
                    {
                        'app_id': '70d462913faad1ecaa85eda4c448a607164fe39414c8be44405e7ab4f7f8467c',
                        'app_name': 'linux-firmware'
                    }
                ]
            >>> oper.add_agent_to_install_operation(
                    agent_id, operation_id, applications
                )

        Returns:
            Boolean
        """
        completed = False
        operation_data = {
            OperationPerAgentKey.AgentId: agent_id,
            OperationPerAgentKey.OperationId: operation_id,
            OperationPerAgentKey.CustomerName: self.customer_name,
            OperationPerAgentKey.Status: OperationPerAgentCodes.PendingPickUp,
            OperationPerAgentKey.PickedUpTime: DbTime.begining_of_time(),
            OperationPerAgentKey.ExpiredTime: DbTime.begining_of_time(),
            OperationPerAgentKey.CompletedTime: DbTime.begining_of_time(),
            OperationPerAgentKey.AppsTotalCount: len(applications),
            OperationPerAgentKey.AppsPendingCount: len(applications),
            OperationPerAgentKey.AppsFailedCount: self.INIT_COUNT,
            OperationPerAgentKey.AppsCompletedCount: self.INIT_COUNT,
            OperationPerAgentKey.Errors: None
        }

        status_code, count, errors, generated_ids = (
            insert_agent_into_agent_operations(operation_data)
        )
        if status_code == DbCodes.Inserted:
            apps = []
            for app in applications:
                apps.append(
                    {
                        OperationPerAppKey.AgentId: agent_id,
                        OperationPerAppKey.OperationId: operation_id,
                        OperationPerAppKey.CustomerName: self.customer_name,
                        OperationPerAppKey.Results: (
                            AgentOperationCodes.ResultsPending
                        ),
                        OperationPerAppKey.ResultsReceivedTime: (
                            DbTime.begining_of_time()
                        ),
                        OperationPerAppKey.AppId: app[OperationPerAppKey.AppId],
                        OperationPerAppKey.AppName: (
                            app[OperationPerAppKey.AppName]
                        ),
                        OperationPerAppKey.AppVersion: (
                            app[OperationPerAppKey.AppVersion]
                        ),
                        OperationPerAppKey.AppsRemoved: [],
                        OperationPerAppKey.Errors: None
                    }
                )

            status_code, count, errors, generated_ids = (
                insert_app_into_agent_operations(apps)
            )
            if status_code == DbCodes.Inserted:
                completed = True

        return completed