Beispiel #1
0
def retrieve_state_of_app(app_name, authtoken):
    """
    Single function to encapsulate all app_type state retrieval behaviour. This function:
        1. Attempts to retrieve the record of the app from the kvstore
        2. Creates a new record if one does not already exist

    :param app_name: Name of app in kvstore
    :param authtoken: System level auth token (in case new record needs to be created)
    :return:
    """

    # Attempts to retrieve the record of the app from the kvstore
    kvstore = KvStore(constants.APPLICATION_TYPES_COLLECTION_NAME,
                      authtoken,
                      owner=NOBODY)
    r, app_record = kvstore.get_items_by_query({'application_name': app_name})
    app_record = json.loads(app_record)

    # Creates a new record if one does not already exist
    if not app_record:
        kvstore.insert_single_item({
            'application_name': app_name,
            'application_enabled': False
        })
        return False
    return app_record[0][APPLICATION_ENABLED_LABEL]
def get_devices_for_user(user, authtoken):
    """
    Gets devices belonging to a user from the kvstore
    :param user: Username to retrieve devices for
    :param authtoken: Authorization token to supply to the kvstore interface
    :return: List of devices
    """
    kvstore = KvStore(constants.REGISTERED_DEVICES_COLLECTION_NAME,
                      authtoken,
                      owner=user)
    _, devices_record = kvstore.get_items_by_query(query={},
                                                   sort="device_name")
    LOGGER.debug("user={}, devices={}".format(user, devices_record))
    return json.loads(devices_record)
Beispiel #3
0
def set_state_of_app(app_name, authtoken, system_authtoken, new_state):
    """
    Updates whether the specified app is enabled or not. This function:
        1. Validates the app_type for correctness
        2. If app is being disabled, delete all registered devices
        3. Attempts to retrieve the record of the app from the kvstore
        4. Updates or creates the new kvstore entry depending if one exists already
        5. Returns the state of the app_type

    :param app_name: Name of app in kvstore
    :param authtoken: User's authorization token
    :param system_authtoken: System authorization token
    :param new_state: Boolean signifying whether to enable the app
    :return: Success message
    """

    # Validates the app_type for correctness
    if app_name not in APP_TYPES:
        raise Errors.SpacebridgeRestError(
            'Error: Invalid app_type=%s' % app_name, 400)

    # If app is being disabled, delete all registered devices
    if not new_state:
        delete_all_devices_of_type(app_name, authtoken, system_authtoken)

    # Attempts to retrieve the record of the app from the kvstore
    kvstore = KvStore(constants.APPLICATION_TYPES_COLLECTION_NAME,
                      authtoken,
                      owner=NOBODY)
    r, app_record = kvstore.get_items_by_query({'application_name': app_name})
    app_record = json.loads(app_record)
    new_app = {'application_name': app_name, 'application_enabled': new_state}

    # Updates or creates the new kvstore entry depending if one exists already
    if app_record:
        kvstore.update_item_by_key(app_record[0]['_key'], new_app)
    else:
        kvstore.insert_single_item(new_app)

    result_string = 'Application app_type=%s is now new_state=%s' % (
        app_name, 'enabled' if new_state else 'disabled')

    LOGGER.info(result_string)

    # Returns the state of the app_type
    return {
        'payload': result_string,
        'status': 200,
    }
Beispiel #4
0
    def get(self, request):
        """
        Lists one or more subscriptions based on provided json/query payload parameters, OR key provided on path

        Request Parameters
            users                   optional list of user to fetch subscriptions for
            subscription_types      optional list of subscription types to filter on
            device_ids              optional list of device_ids to filter on

            You can either pass these in the json body, or pass them in like
            https://localhost:8089/services/ssg/subscription/?users=user1&users=user2

        Returns:
            list of subscriptions found

            Example:
                [
                    {
                        "device_id": "3",
                        "expired_time": "12345678",
                        "last_update_time": "123456",
                        "shard_id": "shard",
                        "subscription_key": "keyy",
                        "subscription_type": "Splunk TV",
                        "ttl_seconds": "10",
                        "user": "******",
                        "version": 2,
                        "visualization_id": "",
                        "_user": "******",
                        "_key": "5f04e4d1ed7a6aab3e6f2e91"
                    }
                ]
        """
        session_key = request[constants.SESSION][constants.AUTHTOKEN]
        path = request.get(PATH_INFO)
        kvstore_object = KVStore(
            collection=constants.SUBSCRIPTIONS_COLLECTION_NAME,
            session_key=session_key)

        if path:  # search using path as key
            LOGGER.debug('Fetching subscription with key %s', path)
            try:
                response_header, response = kvstore_object.get_item_by_key(
                    path)
            except splunk.RESTException as e:
                if e.statusCode == HTTPStatus.NOT_FOUND:
                    return {
                        constants.PAYLOAD: {
                            'Error': 'Not found'
                        },
                        constants.STATUS: HTTPStatus.NOT_FOUND,
                    }
                raise e

        else:  # use json parameters or search for all
            payload = json.loads(request.get(constants.PAYLOAD, '{}'))
            query_params = request.get(constants.QUERY)
            users = payload.get(USERS)
            subscription_types = payload.get(SUBSCRIPTION_TYPES)
            device_ids = payload.get(DEVICE_IDS)

            # if not in json, try to pull from query params
            if not users and query_params:
                users = get_list_from_query(query_params, USERS)
            if not subscription_types and query_params:
                subscription_types = get_list_from_query(
                    query_params, SUBSCRIPTION_TYPES)
            if not device_ids and query_params:
                device_ids = get_list_from_query(query_params, DEVICE_IDS)

            query = {}
            if users:
                query = build_containedin_clause(constants.USER, users)
            if subscription_types:
                query = {
                    constants.AND_OPERATOR: [
                        build_containedin_clause(constants.SUBSCRIPTION_TYPE,
                                                 subscription_types), query
                    ]
                }
            if device_ids:
                query = {
                    constants.AND_OPERATOR: [
                        build_containedin_clause(constants.DEVICE_ID,
                                                 device_ids), query
                    ]
                }
            if query:
                LOGGER.debug('Fetching subscription(s) with query %s', query)
                response_header, response = kvstore_object.get_items_by_query(
                    query)
            else:
                LOGGER.debug('Fetching all subscriptions')
                response_header, response = kvstore_object.get_all_items()

        payload = json.loads(response)
        return {
            constants.PAYLOAD: payload,
            constants.STATUS: response_header.status,
        }