示例#1
0
def present(name,
            type,
            url,
            access=None,
            user=None,
            password=None,
            database=None,
            basic_auth=None,
            basic_auth_user=None,
            basic_auth_password=None,
            tls_auth=None,
            json_data=None,
            is_default=None,
            with_credentials=None,
            type_logo_url=None,
            orgname=None,
            profile='grafana'):
    '''
    Ensure that a data source is present.

    name
        Name of the data source.

    type
        Type of the datasource ('graphite', 'influxdb' etc.).

    access
        Use proxy or direct. Default: proxy

    url
        The URL to the data source API.

    user
        Optional - user to authenticate with the data source.

    password
        Optional - password to authenticate with the data source.

    database
        Optional - database to use with the data source.

    basic_auth
        Optional - set to True to use HTTP basic auth to authenticate with the
        data source.

    basic_auth_user
        Optional - HTTP basic auth username.

    basic_auth_password
        Optional - HTTP basic auth password.

    json_data
        Optional - additional json data to post (eg. "timeInterval").

    is_default
        Optional - set data source as default.

    with_credentials
        Optional - Whether credentials such as cookies or auth headers should
        be sent with cross-site requests.

    type_logo_url
        Optional - Logo to use for this datasource.

    orgname
        Name of the organization in which the data source should be present.

    profile
        Configuration profile used to connect to the Grafana instance.
        Default is 'grafana'.
    '''
    if isinstance(profile, string_types):
        profile = __salt__['config.option'](profile)

    ret = {'name': name, 'result': None, 'comment': None, 'changes': None}
    datasource = __salt__['grafana4.get_datasource'](name, orgname, profile)
    data = _get_json_data(name=name,
                          type=type,
                          url=url,
                          access=access,
                          user=user,
                          password=password,
                          database=database,
                          basicAuth=basic_auth,
                          basicAuthUser=basic_auth_user,
                          basicAuthPassword=basic_auth_password,
                          tlsAuth=tls_auth,
                          jsonData=json_data,
                          isDefault=is_default,
                          withCredentials=with_credentials,
                          typeLogoUrl=type_logo_url,
                          defaults=datasource)

    if not datasource:
        __salt__['grafana4.create_datasource'](profile=profile, **data)
        datasource = __salt__['grafana4.get_datasource'](name, profile=profile)
        ret['result'] = True
        ret['comment'] = 'New data source {0} added'.format(name)
        ret['changes'] = data
        return ret

    # At this stage, the datasource exists; however, the object provided by
    # Grafana may lack some null keys compared to our "data" dict:
    for key in data:
        if key not in datasource:
            datasource[key] = None

    if data == datasource:
        ret['changes'] = {}
        ret['comment'] = 'Data source {0} already up-to-date'.format(name)
        return ret

    __salt__['grafana4.update_datasource'](datasource['id'],
                                           profile=profile,
                                           **data)
    ret['result'] = True
    ret['changes'] = deep_diff(datasource, data, ignore=['id', 'orgId'])
    ret['comment'] = 'Data source {0} updated'.format(name)
    return ret
示例#2
0
def present(name,
            password,
            email=None,
            is_admin=False,
            fullname=None,
            theme=None,
            default_organization=None,
            organizations=None,
            profile='grafana'):
    '''
    Ensure that a user is present.

    name
        Name of the user.

    password
        Password of the user.

    email
        Optional - Email of the user.

    is_admin
        Optional - Set user as admin user. Default: False

    fullname
        Optional - Full name of the user.

    theme
        Optional - Selected theme of the user.

    default_organization
        Optional - Set user's default organization

    organizations
        Optional - List of viewer member organizations or pairs of organization and role that the user belongs to.

    profile
        Configuration profile used to connect to the Grafana instance.
        Default is 'grafana'.


    Here is an example for using default_organization and organizations parameters. The user will be added as
    a viewer to ReadonlyOrg, as an editor to TestOrg and as an admin to AdminOrg. When she logs on, TestOrg
    will be the default. The state will fail if any organisation is unknown or invalid roles are defined.
        .. code-block:: yaml

            add_grafana_test_user:
              grafana4_user.present:
                - name: test
                - password: 1234567890
                - fullname: 'Test User'
                - default_organization: TestOrg
                - organizations:
                  - ReadonlyOrg
                  - TestOrg: Editor
                  - Staging: Admin
    '''
    if isinstance(profile, string_types):
        profile = __salt__['config.option'](profile)

    ret = {'name': name, 'result': None, 'comment': None, 'changes': {}}
    user = __salt__['grafana4.get_user'](name, profile)
    create = not user

    if create:
        if __opts__['test']:
            ret['comment'] = 'User {0} will be created'.format(name)
            return ret
        __salt__['grafana4.create_user'](login=name,
                                         password=password,
                                         email=email,
                                         name=fullname,
                                         profile=profile)
        user = __salt__['grafana4.get_user'](name, profile)
        ret['changes']['new'] = user

    user_data = __salt__['grafana4.get_user_data'](user['id'], profile=profile)

    if default_organization:
        try:
            org_id = __salt__['grafana4.get_org'](default_organization,
                                                  profile)['id']
        except HTTPError as e:
            ret['comment'] = 'Error while looking up user {}\'s default grafana org {}: {}'.format(
                name, default_organization, e)
            ret['result'] = False
            return ret
    new_data = _get_json_data(login=name,
                              email=email,
                              name=fullname,
                              theme=theme,
                              orgId=org_id if default_organization else None,
                              defaults=user_data)
    old_data = _get_json_data(login=None,
                              email=None,
                              name=None,
                              theme=None,
                              orgId=None,
                              defaults=user_data)
    if organizations:
        ret = _update_user_organizations(name, user['id'], organizations, ret,
                                         profile)
        if 'result' in ret and ret['result'] is False:
            return ret

    if new_data != old_data:
        if __opts__['test']:
            ret['comment'] = 'User {0} will be updated'.format(name)
            dictupdate.update(ret['changes'], deep_diff(old_data, new_data))
            return ret
        __salt__['grafana4.update_user'](user['id'],
                                         profile=profile,
                                         orgid=org_id,
                                         **new_data)
        dictupdate.update(
            ret['changes'],
            deep_diff(user_data,
                      __salt__['grafana4.get_user_data'](user['id'])))

    if user['isAdmin'] != is_admin:
        if __opts__['test']:
            ret['comment'] = 'User {0} isAdmin status will be updated'.format(
                name)
            return ret
        __salt__['grafana4.update_user_permissions'](user['id'],
                                                     isGrafanaAdmin=is_admin,
                                                     profile=profile)
        dictupdate.update(
            ret['changes'],
            deep_diff(user, __salt__['grafana4.get_user'](name, profile)))

    ret['result'] = True
    if create:
        ret['changes'] = ret['changes']['new']
        ret['comment'] = 'New user {0} added'.format(name)
    else:
        if ret['changes']:
            ret['comment'] = 'User {0} updated'.format(name)
        else:
            ret['changes'] = {}
            ret['comment'] = 'User {0} already up-to-date'.format(name)

    return ret
示例#3
0
def present(name,
            password,
            email,
            is_admin=False,
            fullname=None,
            theme=None,
            profile="grafana"):
    """
    Ensure that a user is present.

    name
        Name of the user.

    password
        Password of the user.

    email
        Email of the user.

    is_admin
        Optional - Set user as admin user. Default: False

    fullname
        Optional - Full name of the user.

    theme
        Optional - Selected theme of the user.

    profile
        Configuration profile used to connect to the Grafana instance.
        Default is 'grafana'.
    """
    if isinstance(profile, string_types):
        profile = __salt__["config.option"](profile)

    ret = {"name": name, "result": None, "comment": None, "changes": {}}
    user = __salt__["grafana4.get_user"](name, profile)
    create = not user

    if create:
        if __opts__["test"]:
            ret["comment"] = "User {0} will be created".format(name)
            return ret
        __salt__["grafana4.create_user"](login=name,
                                         password=password,
                                         email=email,
                                         name=fullname,
                                         profile=profile)
        user = __salt__["grafana4.get_user"](name, profile)
        ret["changes"]["new"] = user

    user_data = __salt__["grafana4.get_user_data"](user["id"], profile=profile)
    data = _get_json_data(login=name,
                          email=email,
                          name=fullname,
                          theme=theme,
                          defaults=user_data)
    if data != _get_json_data(
            login=None, email=None, name=None, theme=None, defaults=user_data):
        if __opts__["test"]:
            ret["comment"] = "User {0} will be updated".format(name)
            return ret
        __salt__["grafana4.update_user"](user["id"], profile=profile, **data)
        dictupdate.update(
            ret["changes"],
            deep_diff(user_data,
                      __salt__["grafana4.get_user_data"](user["id"])),
        )

    if user["isAdmin"] != is_admin:
        if __opts__["test"]:
            ret["comment"] = "User {0} isAdmin status will be updated".format(
                name)
            return ret
        __salt__["grafana4.update_user_permissions"](user["id"],
                                                     isGrafanaAdmin=is_admin,
                                                     profile=profile)
        dictupdate.update(
            ret["changes"],
            deep_diff(user, __salt__["grafana4.get_user"](name, profile)),
        )

    ret["result"] = True
    if create:
        ret["changes"] = ret["changes"]["new"]
        ret["comment"] = "New user {0} added".format(name)
    else:
        if ret["changes"]:
            ret["comment"] = "User {0} updated".format(name)
        else:
            ret["changes"] = {}
            ret["comment"] = "User {0} already up-to-date".format(name)

    return ret
示例#4
0
def present(name,
            users=None,
            theme=None,
            home_dashboard_id=None,
            timezone=None,
            address1=None,
            address2=None,
            city=None,
            zip_code=None,
            address_state=None,
            country=None,
            profile='grafana'):
    '''
    Ensure that an organization is present.

    name
        Name of the org.

    users
        Optional - Dict of user/role associated with the org. Example:

        .. code-block:: yaml

            users:
              foo: Viewer
              bar: Editor

    theme
        Optional - Selected theme for the org.

    home_dashboard_id
        Optional - Home dashboard for the org.

    timezone
        Optional - Timezone for the org (one of: "browser", "utc", or "").

    address1
        Optional - address1 of the org.

    address2
        Optional - address2 of the org.

    city
        Optional - city of the org.

    zip_code
        Optional - zip_code of the org.

    address_state
        Optional - state of the org.

    country
        Optional - country of the org.

    profile
        Configuration profile used to connect to the Grafana instance.
        Default is 'grafana'.
    '''
    if isinstance(profile, string_types):
        profile = __salt__['config.option'](profile)

    ret = {'name': name, 'result': None, 'comment': None, 'changes': {}}
    create = False
    try:
        org = __salt__['grafana4.get_org'](name, profile)
    except HTTPError as e:
        if e.response.status_code == 404:
            create = True
        else:
            raise

    if create:
        if __opts__['test']:
            ret['comment'] = 'Org {0} will be created'.format(name)
            return ret
        __salt__['grafana4.create_org'](profile=profile, name=name)
        org = __salt__['grafana4.get_org'](name, profile)
        ret['changes'] = org
        ret['comment'] = 'New org {0} added'.format(name)

    data = _get_json_data(address1=address1, address2=address2,
        city=city, zipCode=zip_code, state=address_state, country=country,
        defaults=org['address'])
    if data != org['address']:
        if __opts__['test']:
            ret['comment'] = 'Org {0} address will be updated'.format(name)
            return ret
        __salt__['grafana4.update_org_address'](name, profile=profile, **data)
        if create:
            dictupdate.update(ret['changes']['address'], data)
        else:
            dictupdate.update(ret['changes'], deep_diff(org['address'], data))

    prefs = __salt__['grafana4.get_org_prefs'](name, profile=profile)
    data = _get_json_data(theme=theme, homeDashboardId=home_dashboard_id,
        timezone=timezone, defaults=prefs)
    if data != prefs:
        if __opts__['test']:
            ret['comment'] = 'Org {0} prefs will be updated'.format(name)
            return ret
        __salt__['grafana4.update_org_prefs'](name, profile=profile, **data)
        if create:
            dictupdate.update(ret['changes'], data)
        else:
            dictupdate.update(ret['changes'], deep_diff(prefs, data))

    if users:
        db_users = {}
        for item in __salt__['grafana4.get_org_users'](name, profile=profile):
            db_users[item['login']] = {
                'userId': item['userId'],
                'role': item['role'],
                }
        for username, role in users.items():
            if username in db_users:
                if role is False:
                    if __opts__['test']:
                        ret['comment'] = 'Org {0} user {1} will be ' \
                                'deleted'.format(name, username)
                        return ret
                    __salt__['grafana4.delete_org_user'](
                        db_users[username]['userId'], profile=profile)
                elif role != db_users[username]['role']:
                    if __opts__['test']:
                        ret['comment'] = 'Org {0} user {1} role will be ' \
                                'updated'.format(name, username)
                        return ret
                    __salt__['grafana4.update_org_user'](
                        db_users[username]['userId'], loginOrEmail=username,
                        role=role, profile=profile)
            elif role:
                if __opts__['test']:
                    ret['comment'] = 'Org {0} user {1} will be created'.format(
                            name, username)
                    return ret
                __salt__['grafana4.create_org_user'](
                    loginOrEmail=username, role=role, profile=profile)

        new_db_users = {}
        for item in __salt__['grafana4.get_org_users'](name, profile=profile):
            new_db_users[item['login']] = {
                'userId': item['userId'],
                'role': item['role'],
                }
        if create:
            dictupdate.update(ret['changes'], new_db_users)
        else:
            dictupdate.update(ret['changes'], deep_diff(db_users, new_db_users))

    ret['result'] = True
    if not create:
        if ret['changes']:
            ret['comment'] = 'Org {0} updated'.format(name)
        else:
            ret['changes'] = {}
            ret['comment'] = 'Org {0} already up-to-date'.format(name)

    return ret
示例#5
0
def present(
    name,
    users=None,
    theme=None,
    home_dashboard_id=None,
    timezone=None,
    address1=None,
    address2=None,
    city=None,
    zip_code=None,
    address_state=None,
    country=None,
    profile="grafana",
):
    """
    Ensure that an organization is present.

    name
        Name of the org.

    users
        Optional - Dict of user/role associated with the org. Example:

        .. code-block:: yaml

            users:
              foo: Viewer
              bar: Editor

    theme
        Optional - Selected theme for the org.

    home_dashboard_id
        Optional - Home dashboard for the org.

    timezone
        Optional - Timezone for the org (one of: "browser", "utc", or "").

    address1
        Optional - address1 of the org.

    address2
        Optional - address2 of the org.

    city
        Optional - city of the org.

    zip_code
        Optional - zip_code of the org.

    address_state
        Optional - state of the org.

    country
        Optional - country of the org.

    profile
        Configuration profile used to connect to the Grafana instance.
        Default is 'grafana'.
    """
    if isinstance(profile, str):
        profile = __salt__["config.option"](profile)

    ret = {"name": name, "result": None, "comment": None, "changes": {}}
    create = False
    try:
        org = __salt__["grafana4.get_org"](name, profile)
    except HTTPError as e:
        if e.response.status_code == 404:
            create = True
        else:
            raise

    if create:
        if __opts__["test"]:
            ret["comment"] = "Org {} will be created".format(name)
            return ret
        __salt__["grafana4.create_org"](profile=profile, name=name)
        org = __salt__["grafana4.get_org"](name, profile)
        ret["changes"] = org
        ret["comment"] = "New org {} added".format(name)

    data = _get_json_data(
        address1=address1,
        address2=address2,
        city=city,
        zipCode=zip_code,
        state=address_state,
        country=country,
        defaults=org["address"],
    )
    if data != org["address"]:
        if __opts__["test"]:
            ret["comment"] = "Org {} address will be updated".format(name)
            return ret
        __salt__["grafana4.update_org_address"](name, profile=profile, **data)
        if create:
            dictupdate.update(ret["changes"]["address"], data)
        else:
            dictupdate.update(ret["changes"], deep_diff(org["address"], data))

    prefs = __salt__["grafana4.get_org_prefs"](name, profile=profile)
    data = _get_json_data(
        theme=theme,
        homeDashboardId=home_dashboard_id,
        timezone=timezone,
        defaults=prefs,
    )
    if data != prefs:
        if __opts__["test"]:
            ret["comment"] = "Org {} prefs will be updated".format(name)
            return ret
        __salt__["grafana4.update_org_prefs"](name, profile=profile, **data)
        if create:
            dictupdate.update(ret["changes"], data)
        else:
            dictupdate.update(ret["changes"], deep_diff(prefs, data))

    if users:
        db_users = {}
        for item in __salt__["grafana4.get_org_users"](name, profile=profile):
            db_users[item["login"]] = {
                "userId": item["userId"],
                "role": item["role"],
            }
        for username, role in users.items():
            if username in db_users:
                if role is False:
                    if __opts__["test"]:
                        ret["comment"] = "Org {} user {} will be deleted".format(
                            name, username
                        )
                        return ret
                    __salt__["grafana4.delete_org_user"](
                        db_users[username]["userId"], profile=profile
                    )
                elif role != db_users[username]["role"]:
                    if __opts__["test"]:
                        ret["comment"] = "Org {} user {} role will be updated".format(
                            name, username
                        )
                        return ret
                    __salt__["grafana4.update_org_user"](
                        db_users[username]["userId"],
                        loginOrEmail=username,
                        role=role,
                        profile=profile,
                    )
            elif role:
                if __opts__["test"]:
                    ret["comment"] = "Org {} user {} will be created".format(
                        name, username
                    )
                    return ret
                __salt__["grafana4.create_org_user"](
                    loginOrEmail=username, role=role, profile=profile
                )

        new_db_users = {}
        for item in __salt__["grafana4.get_org_users"](name, profile=profile):
            new_db_users[item["login"]] = {
                "userId": item["userId"],
                "role": item["role"],
            }
        if create:
            dictupdate.update(ret["changes"], new_db_users)
        else:
            dictupdate.update(ret["changes"], deep_diff(db_users, new_db_users))

    ret["result"] = True
    if not create:
        if ret["changes"]:
            ret["comment"] = "Org {} updated".format(name)
        else:
            ret["changes"] = {}
            ret["comment"] = "Org {} already up-to-date".format(name)

    return ret
示例#6
0
def present(name,
            password,
            email,
            is_admin=False,
            fullname=None,
            theme=None,
            profile='grafana'):
    '''
    Ensure that a user is present.

    name
        Name of the user.

    password
        Password of the user.

    email
        Email of the user.

    is_admin
        Optional - Set user as admin user. Default: False

    fullname
        Optional - Full name of the user.

    theme
        Optional - Selected theme of the user.

    profile
        Configuration profile used to connect to the Grafana instance.
        Default is 'grafana'.
    '''
    if isinstance(profile, string_types):
        profile = __salt__['config.option'](profile)

    ret = {'name': name, 'result': None, 'comment': None, 'changes': {}}
    user = __salt__['grafana4.get_user'](name, profile)
    create = not user

    if create:
        __salt__['grafana4.create_user'](login=name,
                                         password=password,
                                         email=email,
                                         name=fullname,
                                         profile=profile)
        user = __salt__['grafana4.get_user'](name, profile)
        ret['changes']['new'] = user

    user_data = __salt__['grafana4.get_user_data'](user['id'])
    data = _get_json_data(login=name,
                          email=email,
                          name=fullname,
                          theme=theme,
                          defaults=user_data)
    if data != _get_json_data(
            login=None, email=None, name=None, theme=None, defaults=user_data):
        __salt__['grafana4.update_user'](user['id'], profile=profile, **data)
        dictupdate.update(
            ret['changes'],
            deep_diff(user_data,
                      __salt__['grafana4.get_user_data'](user['id'])))

    if user['isAdmin'] != is_admin:
        __salt__['grafana4.update_user_permissions'](user['id'],
                                                     isGrafanaAdmin=is_admin,
                                                     profile=profile)
        dictupdate.update(
            ret['changes'],
            deep_diff(user, __salt__['grafana4.get_user'](name, profile)))

    ret['result'] = True
    if create:
        ret['changes'] = ret['changes']['new']
        ret['comment'] = 'New user {0} added'.format(name)
    else:
        if ret['changes']:
            ret['comment'] = 'User {0} updated'.format(name)
        else:
            ret['changes'] = None
            ret['comment'] = 'User {0} already up-to-date'.format(name)

    return ret