Merge remote-tracking branch 'origin/dev' into dev

This commit is contained in:
Matvey Kukuy 2022-06-13 16:02:07 +03:00
commit 464fbcae9f
105 changed files with 2792 additions and 2263 deletions

View file

@ -124,161 +124,7 @@ extra_hosts:
### Slack application setup
This instruction is also applicable if you set up self-hosted OnCall.
1. Start a [localtunnel](https://github.com/localtunnel/localtunnel) reverse proxy to make oncall engine api accessible to slack (if you don't have OnCall backend accessible from https),
```bash
# Choose the unique prefix instead of pretty-turkey-83
# Localtunnel will generate an url, e.g. https://pretty-turkey-83.loca.lt
# it is referred as <ONCALL_ENGINE_PUBLIC_URL> below
lt --port 8000 -s pretty-turkey-83 --print-requests
```
2. [Create a Slack Workspace](https://slack.com/create) for development.
3. Go to https://api.slack.com/apps and click Create New App button
4. Select `From an app manifest` option and choose the right workspace
5. Copy and paste the following block with the correct <YOUR_BOT_NAME> and <ONCALL_ENGINE_PUBLIC_URL> fields
<details>
<summary>Click to expand!</summary>
```yaml
_metadata:
major_version: 1
minor_version: 1
display_information:
name: <YOUR_BOT_NAME>
features:
app_home:
home_tab_enabled: true
messages_tab_enabled: true
messages_tab_read_only_enabled: false
bot_user:
display_name: <YOUR_BOT_NAME>
always_online: true
shortcuts:
- name: Create a new incident
type: message
callback_id: incident_create
description: Creates a new OnCall incident
- name: Add to postmortem
type: message
callback_id: add_postmortem
description: Add this message to postmortem
slash_commands:
- command: /oncall
url: <ONCALL_ENGINE_PUBLIC_URL>/slack/interactive_api_endpoint/
description: oncall
should_escape: false
oauth_config:
redirect_urls:
- <ONCALL_ENGINE_PUBLIC_URL>/api/internal/v1/complete/slack-install-free/
- <ONCALL_ENGINE_PUBLIC_URL>/api/internal/v1/complete/slack-login/
scopes:
user:
- channels:read
- chat:write
- identify
- users.profile:read
bot:
- app_mentions:read
- channels:history
- channels:read
- chat:write
- chat:write.customize
- chat:write.public
- commands
- files:write
- groups:history
- groups:read
- im:history
- im:read
- im:write
- mpim:history
- mpim:read
- mpim:write
- reactions:write
- team:read
- usergroups:read
- usergroups:write
- users.profile:read
- users:read
- users:read.email
- users:write
settings:
event_subscriptions:
request_url: <ONCALL_ENGINE_PUBLIC_URL>/slack/event_api_endpoint/
bot_events:
- app_home_opened
- app_mention
- channel_archive
- channel_created
- channel_deleted
- channel_rename
- channel_unarchive
- member_joined_channel
- message.channels
- message.im
- subteam_created
- subteam_members_changed
- subteam_updated
- user_change
interactivity:
is_enabled: true
request_url: <ONCALL_ENGINE_PUBLIC_URL>/slack/interactive_api_endpoint/
org_deploy_enabled: false
socket_mode_enabled: false
```
</details>
6. Click `Install to workspace` button to generate the credentials
6. Populate the environment with variables related to Slack
In your `.env` file, fill out the following variables:
```
SLACK_CLIENT_OAUTH_ID = Basic Information -> App Credentials -> Client ID
SLACK_CLIENT_OAUTH_SECRET = Basic Information -> App Credentials -> Client Secret
SLACK_API_TOKEN = OAuth & Permissions -> Bot User OAuth Token
SLACK_INSTALL_RETURN_REDIRECT_HOST = https://pretty-turkey-83.loca.lt
```
Don't forget to export variables from the `.env` file and restart the server!
7. Edit `grafana-plugin/grafana-plugin.yml` to set `onCallApiUrl` fields with localtunnel url
```
onCallApiUrl: https://pretty-turkey-83.loca.lt
```
or set BASE_URL Env variable through web interface.
8. Edit grafana-plugin/src/plugin.json to add `Bypass-Tunnel-Reminder` header section for all existing routes
> this headers required for the local development only, otherwise localtunnel blocks requests from grafana plugin, An alternative to this is you can modify your user-agent in your browser to bypass the tunnel warning, it only filters the common browsers.
```
{
"path": ...,
...
"headers": [
...
{
"name": "Bypass-Tunnel-Reminder",
"content": "True"
}
]
},
```
9. Rebuild the plugin
```
yarn watch
```
10. Restart grafana instance
11. All set! Go to Slack and check if your application is functional.
For Slack app configuration check our docs: https://grafana.com/docs/grafana-cloud/oncall/open-source/#slack-setup
## Troubleshooting

View file

@ -11,7 +11,7 @@ Developer-friendly, incident response with brilliant Slack integration.
## Getting Started
We prepared multiple environments: [production](PRODUCTION.md), [developer](DEVELOPER.md) and hobby:
We prepared multiple environments: [production](https://grafana.com/docs/grafana-cloud/oncall/open-source/#production-environment), [developer](DEVELOPER.md) and hobby:
1. Download docker-compose.yaml:
```bash

View file

@ -1,5 +1,5 @@
IMAGE = grafana/docs-base:latest
CONTENT_PATH = /hugo/content/docs/amixr/latest
CONTENT_PATH = /hugo/content/docs/oncall/latest
PORT = 3002:3002
.PHONY: pull

View file

@ -4,5 +4,5 @@ Source for documentation at https://grafana.com/docs/amixr/
## Preview the website
Run `make docs`. This launches a preview of the website with the current grafana docs at `http://localhost:3002/docs/amixr/` which will refresh automatically when changes are made to content in the `sources` directory.
Run `make docs`. This launches a preview of the website with the current grafana docs at `http://localhost:3002/docs/oncall/latest/` which will refresh automatically when changes are made to content in the `sources` directory.
Make sure Docker is running.

View file

@ -1,9 +1,18 @@
+++
title = "Grafana OnCall"
keywords = ["Grafana Cloud", "Alerts", "Notifications", "on-call", "amixr", "OnCall", "irm"]
weight = 1000
aliases = ["/docs/grafana-cloud/oncall/"]
+++
---
aliases:
- /docs/grafana-cloud/oncall/
- /docs/oncall/latest/
keywords:
- Grafana Cloud
- Alerts
- Notifications
- on-call
- amixr
- OnCall
- irm
title: Grafana OnCall
weight: 1000
---
# Grafana OnCall
@ -13,4 +22,4 @@ When you integrate an alert monitoring system with Grafana OnCall, the alerts wi
Follow these links to learn more:
{{< section >}}
{{< section >}}

View file

@ -1,15 +1,61 @@
+++
title = "On-call calendar scheduling"
description = ""
keywords = ["Grafana", "oncall", "on-call", "calendar"]
aliases = []
weight = 1100
+++
---
aliases:
- /docs/oncall/latest/calendar-schedules/
description: ""
keywords:
- Grafana
- oncall
- on-call
- calendar
title: Configure and manage on-call schedules
weight: 900
---
# Use calendars to create on-call schedules
# Configure and manage on-call schedules
Grafana OnCall allows you to use any calendar service that uses the iCal format to create customized on-call schedules for team members. Using Grafana OnCall, you can create a primary calendar that acts as a read-only schedule, and an override calendar that allows all team members to modify schedules as they change.
To learn more about creating on-call calendars, see the following topics:
{{< section >}}
# Configure and manage on-call schedules
You can use any calendar with an iCal address to schedule on-call times for users. During these times, notifications configured in escalation chains with the **Notify users from an on-call schedule** setting will be sent to the the person scheduled. You can also schedule multiple users for overlapping times, and assign prioritization labels for the user that you would like to notify.
When you create a schedule, you will be able to select a Slack channel, associated with your OnCall account, that will notify users when there are errors or notifications regarding the assigned on-call shifts.
## Create an on-call schedule calendar
Create a primary calendar and an optional override calendar to schedule on-call shifts for team members.
1. In the **Scheduling** section of Grafana OnCall, click **+ Create schedule**.
1. Give the schedule a name.
1. Create a new calendar in your calendar service and locate the secret iCal URL. For example, in a Google calendar, this URL can be found in **Settings > Settings for my calendars > Integrate calendar**.
1. Copy the secret iCal URL. In OnCall, paste it into the **Primary schedule for iCal URL** field.
The permissions you set when you create the calendar determine who can modify the calendar.
1. Click **Create Schedule**.
1. Schedule on-call times for team members.
Use the Grafana username of team members as the event name to schedule their on-call times. You can take advantage of all of the features of your calendar service.
1. Create overlapping schedules (optional).
When you create schedules that overlap, you can prioritize a schedule by adding a level marker. For example, if users AliceGrafana and BobGrafana have overlapping schedules, but BobGrafana is the primary contact, you would name his event `[L1] BobGrafana`, AliceGrafana maintains the default `[L0]` status, and would not receive notifications during the overlapping time. You can prioritize up to and including a level 9 prioritization, or `[L9]`.
# Create an override calendar (optional)
You can use an override calendar to allow team members to schedule on-call duties that will override the primary schedule. An override option allows flexibility without modifying the primary schedule. Events scheduled on the override calendar will always override overlapping events on the primary calendar.
1. Create a new calendar using the same calendar service you used to create the primary calendar.
Be sure to set permissions that allow team members to edit the calendar.
1. In the scheduling section of Grafana OnCall, select the primary calendar you want to override.
1. Click **Edit**.
1. Enter the secret iCal URL in the **Overrides schedule iCal URL** field and click **Update**.

View file

@ -1,13 +0,0 @@
+++
title = "About Grafana OnCall calendar scheduling"
description = ""
keywords = ["Grafana", "oncall", "on-call", "calendar"]
aliases = []
weight = 100
+++
# About Grafana OnCall scheduling
You can use any calendar with an iCal address to schedule on-call times for users. During these times, notifications configured in escalation chains with the **Notify users from an on-call schedule** setting will be sent to the the person scheduled. You can also schedule multiple users for overlapping times, and assign prioritization labels for the user that you would like to notify.
When you create a schedule, you will be able to select a Slack channel, associated with your OnCall account, that will notify users when there are errors or notifications regarding the assigned on-call shifts.

View file

@ -1,44 +0,0 @@
+++
title = "Create an on-call schedule calendar"
description = ""
keywords = ["Grafana", "oncall", "on-call", "calendar"]
aliases = []
weight = 300
+++
# Create an on-call schedule calendar
Create a primary calendar and an optional override calendar to schedule on-call shifts for team members.
1. In the **Scheduling** section of Grafana OnCall, click **+ Create schedule**.
1. Give the schedule a name.
1. Create a new calendar in your calendar service and locate the secret iCal URL. For example, in a Google calendar, this URL can be found in **Settings > Settings for my calendars > Integrate calendar**.
1. Copy the secret iCal URL. In OnCall, paste it into the **Primary schedule for iCal URL** field.
The permissions you set when you create the calendar determine who can modify the calendar.
1. Click **Create Schedule**.
1. Schedule on-call times for team members.
Use the Grafana username of team members as the event name to schedule their on-call times. You can take advantage of all of the features of your calendar service.
1. Create overlapping schedules (optional).
When you create schedules that overlap, you can prioritize a schedule by adding a level marker. For example, if users AliceGrafana and BobGrafana have overlapping schedules, but BobGrafana is the primary contact, you would name his event `[L1] BobGrafana`, AliceGrafana maintains the default `[L0]` status, and would not receive notifications during the overlapping time. You can prioritize up to and including a level 9 prioritization, or `[L9]`.
# Create an override calendar (optional)
You can use an override calendar to allow team members to schedule on-call duties that will override the primary schedule. An override option allows flexibility without modifying the primary schedule. Events scheduled on the override calendar will always override overlapping events on the primary calendar.
1. Create a new calendar using the same calendar service you used to create the primary calendar.
Be sure to set permissions that allow team members to edit the calendar.
1. In the scheduling section of Grafana OnCall, select the primary calendar you want to override.
1. Click **Edit**.
1. Enter the secret iCal URL in the **Overrides schedule iCal URL** field and click **Update**.

View file

@ -1,13 +1,22 @@
+++
title = "Messaging application configuration"
keywords = ["Grafana Cloud", "Alerts", "Notifications", "on-call", "amixr", "oncall", "slack"]
weight = 700
+++
---
aliases:
- /docs/oncall/latest/chat-options/
keywords:
- Grafana Cloud
- Alerts
- Notifications
- on-call
- amixr
- oncall
- slack
title: Connect ChatOps to Grafana OnCall
weight: 700
---
# Messaging application configuration
# Connect ChatOps to Grafana OnCall
Grafana OnCall directly supports the export of alert notifications to some popular messaging applications like Slack and Telegram. You can use outgoing webhooks to applications that aren't directly supported. For information on configuring outgoing webhooks, see [Send alert group notifications by webhook]({{< relref "../integrations/webhooks/configure-outgoing-webhooks.md" >}}).
To configure supported messaging apps, see the following topics:
{{< section >}}
{{< section >}}

View file

@ -1,20 +1,30 @@
+++
title = "Configure Slack for Grafana OnCall"
keywords = ["Grafana Cloud", "Alerts", "Notifications", "on-call", "amixr", "oncall", "slack"]
weight = 100
+++
---
aliases:
- /docs/oncall/latest/chat-options/configure-slack/
keywords:
- Grafana Cloud
- Alerts
- Notifications
- on-call
- amixr
- oncall
- slack
title: Connect Slack to Grafana OnCall
weight: 100
---
# Configure Slack for Grafana OnCall
Grafana OnCall integrates closely with your Slack workspace to deliver alert group notifications to individuals, groups, and team members.
# Connect Slack to Grafana OnCall
Grafana OnCall integrates closely with your Slack workspace to deliver alert group notifications to individuals, groups, and team members.
## Connect to Slack
Connect your organization's Slack workspace to your Grafana OnCall instance.
>**NOTE:** Only Grafana users with the administrator role can configure OnCall settings.
> **NOTE:** Only Grafana users with the administrator role can configure OnCall settings.
1. In OnCall, click on the **ChatOps** tab and select Slack in the side menu.
1. Click **Install Slack integration**.
1. Click **Install Slack integration**.
1. Read the notice and click the button to proceed to the Slack website.
1. Sign in to your organization's workspace.
1. Click **Allow** to allow OnCall to access Slack.
@ -22,12 +32,13 @@ Connect your organization's Slack workspace to your Grafana OnCall instance.
## Configure Slack in OnCall
In the Slack settings for Grafana OnCall, administrators can set a default Slack channel for notifications and opt to set reminders for acknowledged alerts that can timeout and revert an alert group to the unacknowledged state.
In the Slack settings for Grafana OnCall, administrators can set a default Slack channel for notifications and opt to set reminders for acknowledged alerts that can timeout and revert an alert group to the unacknowledged state.
1. In OnCall, click on the **ChatOps** tab and select Slack in the side menu.
1. In the first dropdown menu, select a default Slack channel.
When you set up escalation policies to notify Slack channels of incoming alerts, the default will be the one you set here. You will still have the option to select from all the channels available in your organization.
When you set up escalation policies to notify Slack channels of incoming alerts, the default will be the one you set here. You will still have the option to select from all the channels available in your organization.
1. In **Additional settings** you can choose how to remind users of acknowledged but unresolved alert groups. You can also select whether and or when to automatically revoke the "acknowledged" status from an alert group to an unacknowledged state.
## Slack settings for on-call calendar scheduling notifications
Admins can configure settings in Slack to notify people and groups about on-call schedules. When an on-call shift notification is sent to a person or channel, click the gear button to access **Notification preferences**. Use the options to configure the behavior of future shift notifications.
Admins can configure settings in Slack to notify people and groups about on-call schedules. When an on-call shift notification is sent to a person or channel, click the gear button to access **Notification preferences**. Use the options to configure the behavior of future shift notifications.

View file

@ -1,12 +1,21 @@
+++
title = "Configure Telegram for Grafana OnCall"
keywords = ["Grafana Cloud", "Alerts", "Notifications", "on-call", "amixr", "oncall", "telegram"]
weight = 300
+++
---
aliases:
- /docs/oncall/latest/chat-options/configure-telegram/
keywords:
- Grafana Cloud
- Alerts
- Notifications
- on-call
- amixr
- oncall
- telegram
title: Connect Telegram to Grafana OnCall
weight: 300
---
# Configure Telegram for Grafana OnCall
# Connect Telegram to Grafana OnCall
You can use Telegram to deliver alert group notifications to a dedicated channel, and allow users to perform notification actions.
You can use Telegram to deliver alert group notifications to a dedicated channel, and allow users to perform notification actions.
Each alert group notification is assigned a dedicated discussion. Users can perform notification actions (acknowledge, resolve, silence), create reports, and discuss alerts in the comments section of the discussions.
@ -14,19 +23,19 @@ Each alert group notification is assigned a dedicated discussion. Users can perf
Connect your organization's Telegram account to your Grafana OnCall instance by following the instructions provided in OnCall. You can use the following steps as a reference.
>**NOTE:** Only Grafana users with the administrator role can configure OnCall settings.
> **NOTE:** Only Grafana users with the administrator role can configure OnCall settings.
1. In OnCall, click on the **ChatOps** tab and select Telegram in the side menu.
1. Click **Connect Telegram channel** and follow the instructions, mirrored here for reference. A unique verification code will be generated that you must use to activate the channel.
1. In your team Telegram account, create a new channel, and set it to **Private**.
1. In your team Telegram account, create a new channel, and set it to **Private**.
1. In **Manage Channel**, make sure **Sign messages** is enabled.
1. Create a new discussion group.
This group handles alert actions and comments.
1. Add the discussion group to the channel.
In **Manage Channel**, click **Discussion** to find and add the new group.
1. In OnCall, click the link to the OnCall bot to add it to your contacts.
1. In Telegram, add the bot to your channel as an Admin. Allow it to **Post Messages**.
1. Add the bot to the discussion group.
This group handles alert actions and comments.
1. Add the discussion group to the channel.
In **Manage Channel**, click **Discussion** to find and add the new group.
1. In OnCall, click the link to the OnCall bot to add it to your contacts.
1. In Telegram, add the bot to your channel as an Admin. Allow it to **Post Messages**.
1. Add the bot to the discussion group.
1. In OnCall, send the provided verification code to the channel.
1. Make sure users connect to Telegram in their OnCall user profile.
@ -36,4 +45,4 @@ Connect your organization's Telegram account to your Grafana OnCall instance by
1. Click **Connect automatically** for the bot to message you and to bring up your telegram account.
1. Click **Start** when the OnCall bot messages you.
If you want to connect manually, you can click the URL provided and then **SEND MESSAGE**. In your Telegram account, click **Start**.
If you want to connect manually, you can click the URL provided and then **SEND MESSAGE**. In your Telegram account, click **Start**.

View file

@ -1,121 +0,0 @@
+++
title = "Getting started with Grafana OnCall"
keywords = ["Grafana Cloud", "Alerts", "Notifications", "on-call"]
aliases = ["/docs/grafana-cloud/oncall/configure-notifications"]
draft = true
+++
# Configure users, notifications, and on-call schedules
These procedures introduce you to the configuration of user settings, how to set up escalation policies, and how to use your calendar service for on-call scheduling.
## Before you begin
You must have a Grafana Cloud account and be connected to a data source with alerts configured.
Each supported integration and the associated monitoring system has a slightly different configuration method. These methods will not be explained in this guide, however, you can follow the online instructions provided when adding an integration.
## Configure user notification policies
You can configure how each user will receive notifications when they are assigned in escalation policies.
1. Find users.
Select the **Users** tab and use the browser to search for a user in your organization.
1. Configure user settings.
Add and verify a phone number and a Slack username if you want to deliver notifications using these mediums.
<br>
>**NOTE:** To edit a user's username, email, or role, you must do so in the **Users** tab in the **Configuration** menu of your Grafana instance.
1. Configure notification settings.
You can configure the notification medium and frequency for each user. **Important Notifications** are specified in escalation steps.
## Connect to integration data sources
You use Grafana OnCall to connect to the monitoring services of your data sources listed in the Grafana OnCall **Integrations** section.
1. Connect to a data source with configured alerts.
In Grafana OnCall, click on the **Integrations** tab and click **+ New integration for receiving alerts**.
1. Select an integration from the provided options.
If you want to use an integration that is not listed, you must use webhooks.
1. Configure your integration.
Each integration has a different method of connecting to Grafana OnCall. For example, if you want to connect to your Grafana data source, select Grafana and follow the instructions.
## Configure escalation policies
You can use **escalation chains** to determine ordered escalation procedures. Configuring escalation chains allows you to set up a chain of incident notification actions that trigger if certain conditions that you specify are not met.
1. Click on the integration tile for which you want to define escalation policies.
The **Escalations** section for the notification is in the pane to the right of the list of notifications.
You can click **Change alert template and grouping** to customize the look of the alert. You can also do this by clicking the **Settings** (gear) icon in the integration tile.
1. Create an escalation chain.
In the escalation pane, click the **escalate to** menu to choose from previously added escalation chains, or create a new one by clicking **Create a new**. This will be the name of the escalation policy you define.
1. Add escalation steps.
Click **Add escalation step** to choose from a set of actions and specify their triggering conditions. By default, the first step is to notify a slack channel or user. Specify users or channels or toggle the switch to turn this step off.
To mark an escalation as **Important**, select the option from the step **Start** dropdown menu. User notification policies can be separately defined for **Important** and **Default** escalations.
1. Add a route.
To add a route, click **Add Route**.
You can set up a single route and specify notification escalation steps, or you can add multiple routes, each with its own configuration.
Each route added to an escalation policy follows an `IF`, `ELSE IF`, and `ELSE` path and depends on the type of alert you specify using a regular expression that matches content in the payload body of the alert. You can also specify where to send the notification for each route.
For example, you can send notifications for alert incidents with `\"severity\": \"critical\"` in the payload to an escalation chain called `Bob_OnCall`. You can create a different route for alerts with the payload `\"namespace\" *: *\"synthetic-monitoring-dev-.*\"` and select a escalation chain called `NotifySecurity`.
You can set up escalation steps for each route in a chain.
>**NOTE:** When you modify an escalation chain or a route, it will modify that escalation chain across all integrations that use it.
## Use calendars to configure on-call schedules
You can use any calendar with an iCal address to schedule on-call times for users. During these times, notifications configured in escalation chains with the **Notify users from an on-call schedule** setting will be sent to the the person scheduled. You can also schedule multiple users for overlapping times, and assign prioritization labels for the user that you would like to notify.
1. In the **Scheduling** section of Grafana OnCall, click **+ Create schedule**.
1. Give the schedule a name.
1. Create a new calendar in your calendar service and locate the secret iCal URL. For example, in a Google calendar, this URL can be found in **Settings > Settings for my calendars > Integrate calendar**.
1. Copy the secret iCal URL. In OnCall, paste it into the **Primary schedule for iCal URL** field.
The permissions you set for the calendar determine who can modify the calendar.
1. Click **Create Schedule**.
1. Schedule on-call times for team members.
Use the usersname of team members as the event name to schedule their on-call times. You can take advantage of all of the features of your calendar service.
1. (Optional) Create overlapping schedules.
When you create schedules that overlap, you can prioritize a schedule by adding a level marker. For example, if users AliceGrafana and BobGrafana have overlapping schedules, but BobGrafana is the primary contact, you would name his event `[L1] BobGrafana`, AliceGrafana maintains the default `[L0]` status, and would not receive notifications during the overlapping time. You can prioritize up to and including level 9, or `[L9]`.
### (Optional) Create an override calendar.
You can use an override calendar to allow team members to schedule on-call duties that will override the primary schedule. An override option allows flexibility without modifying the primary schedule. Events scheduled on the override calendar will always override overlapping events on the primary calendar.
1. Create a new calendar using the same calendar service you used to create the primary calendar.
Be sure to set permissions that allow team members to edit the calendar.
1. In the scheduling section of Grafana OnCall, select the primary calendar you want to override.
1. Click **Edit**.
1. Enter the secret iCal URL in the **Overrides schedule iCal URL** field and click **Update**.

View file

@ -1,38 +1,47 @@
+++
title = "Configure user settings"
keywords = ["Grafana Cloud", "Alerts", "Notifications", "on-call", "amixr", "oncall", "integrations"]
weight = 900
+++
---
aliases:
- /docs/oncall/latest/configure-user-settings/
keywords:
- Grafana Cloud
- Alerts
- Notifications
- on-call
- amixr
- oncall
- integrations
title: Manage users and teams for Grafana OnCall
weight: 1100
---
# User settings for Grafana OnCall
# Manage users and teams for Grafana OnCall
Grafana OnCall is configured based on the teams you've created on the organization level of your Grafana instance, in **Configuration > Teams**. Administrators can create a different configuration for each team, and can navigate between team configurations in the **Select Team** dropdown menu in the **Incidents** section of Grafana OnCall.
Grafana OnCall is configured based on the teams you've created on the organization level of your Grafana instance, in **Configuration > Teams**. Administrators can create a different configuration for each team, and can navigate between team configurations in the **Select Team** dropdown menu in the **Incidents** section of Grafana OnCall.
Users can edit their contact information, but user permissions are assigned at the Cloud portal level.
## Configure user notification policies
Administrators can configure how each user will receive notifications when they are are scheduled to receive them in escalation chains. Users can verify phone numbers and email addresses.
Administrators can configure how each user will receive notifications when they are are scheduled to receive them in escalation chains. Users can verify phone numbers and email addresses.
>**NOTE**: You cannot add users or manage permissions in Grafana OnCall. Most user settings are found on the organizational level of your Grafana instance in **Configuration > Users**.
> **NOTE**: You cannot add users or manage permissions in Grafana OnCall. Most user settings are found on the organizational level of your Grafana instance in **Configuration > Users**.
1. Find users.
Select the **Users** tab and use the browser to search for a user in the team associated with the OnCall configuration.
Select the **Users** tab and use the browser to search for a user in the team associated with the OnCall configuration.
1. Configure user settings.
Add and verify a phone number, a Slack username, and a Telegram account if you want to receive notifications using these mediums.
Add and verify a phone number, a Slack username, and a Telegram account if you want to receive notifications using these mediums.
>**NOTE:** To edit a user's profile username, email, or role, you must do so in the **Users** tab in the **Configuration** menu of your Grafana instance.
> **NOTE:** To edit a user's profile username, email, or role, you must do so in the **Users** tab in the **Configuration** menu of your Grafana instance.
1. Configure notification settings.
Specify the notification medium and frequency for each user. Notification steps will be followed in the order they are listed.
The settings you specify in **Default Notifications** dictate how a user is notified for most escalation thresholds.
**Important Notifications** are labeled in escalation chains. If an escalation event is marked as an important notification, it will bypass **Default Notification** settings and notify the user by the method specified.
Specify the notification medium and frequency for each user. Notification steps will be followed in the order they are listed.
The settings you specify in **Default Notifications** dictate how a user is notified for most escalation thresholds.
**Important Notifications** are labeled in escalation chains. If an escalation event is marked as an important notification, it will bypass **Default Notification** settings and notify the user by the method specified.
## Configure Telegram user settings in OnCall
@ -45,4 +54,4 @@ If you want to connect manually, you can click the URL provided and then **SEND
## Configure Slack user settings in OnCall
1. In your profile, find the Slack setting and click **Connect**.
1. Follow the instructions to verify your account.
1. Follow the instructions to verify your account.

View file

@ -1,13 +1,22 @@
+++
title = "Escalation policies"
keywords = ["Grafana Cloud", "Alerts", "Notifications", "on-call", "amixr", "oncall", "integrations"]
weight = 500
+++
---
aliases:
- /docs/oncall/latest/escalation-policies/
keywords:
- Grafana Cloud
- Alerts
- Notifications
- on-call
- amixr
- oncall
- integrations
title: Escalation Chains and Routes
weight: 500
---
# Grafana OnCall escalation policies
# Escalation Chains and Routes for Grafana OnCall
Administrators can create escalation policies to automatically send alert group notifications to recipients. These policies define how, where, and when to send notifications.
See the following topics for more information:
{{< section >}}
{{< section >}}

View file

@ -1,22 +1,34 @@
+++
title = "About escalation policies"
keywords = ["Grafana Cloud", "Alerts", "Notifications", "on-call", "amixr", "oncall", "integrations"]
weight = 100
+++
---
aliases:
- /docs/oncall/latest/escalation-policies/configure-escalation-chains/
keywords:
- Grafana Cloud
- Alerts
- Notifications
- on-call
- amixr
- oncall
- integrations
title: Configure and manage Escalation Chains
weight: 100
---
# About escalation policies
# Configure and manage Escalation Chains
Escalation policies dictate how users and groups are notified when an alert notification is created. They can be very simple, or very complex. You can define as many escalation configurations for an integration as you need, and you can send notifications for certain alerts to a designated place when certain conditions are met, or not met.
Escalation policies dictate how users and groups are notified when an alert notification is created. They can be very simple, or very complex. You can define as many escalation configurations for an integration as you need, and you can send notifications for certain alerts to a designated place when certain conditions are met, or not met.
Escalation policies have three main parts:
* User settings, where a user sets up their preferred or required notification method.
* An **escalation chain**, which can have one or more steps that are followed in order when a notification is triggered.
* A **route**, that allows administrators to manage notifications by flagging expressions in an alert payload.
- User settings, where a user sets up their preferred or required notification method.
- An **escalation chain**, which can have one or more steps that are followed in order when a notification is triggered.
- A **route**, that allows administrators to manage notifications by flagging expressions in an alert payload.
## Escalation chains
An escalation chain can have many steps, or only one step. For example, steps can be configured to notify multiple users in some order, notify users that are scheduled for on-call shifts, ping groups in Slack, use outgoing webhooks to integrate with other services, such as JIRA, and do a number of other automated notification tasks.
## Routes
An escalation workflow can employ **routes** that administrators can configure to filter alerts by regular expressions in their payloads. Notifications for these alerts can be sent to individuals, or they can make use of a new or existing escalation chain.
To learn how to configure escalation chains and routes, see [Configure escalation policies]({{< relref "configure-escalation-policies">}}).
To learn how to configure escalation chains and routes, see [Configure escalation policies]({{< relref "configure-escalation-policies">}}).

View file

@ -1,42 +0,0 @@
+++
title = "Configure escalation policies"
keywords = ["Grafana Cloud", "Alerts", "Notifications", "on-call", "amixr", "oncall", "integrations"]
weight = 300
+++
# Configure escalation policies
Set up escalation chains and routes to configure escalation behavior for alert group notifications.
## Configure escalation chains
You can create and edit escalation chains in two places: within **Integrations**, by clicking on an integration tile, and in **Escalation Chains**. The following steps are for the **Integrations** workflow, but are generally applicable in both situations.
You can use **escalation chains** and **routes** to determine ordered escalation procedures. Escalation chains allow you to set up a series of alert group notification actions that trigger if certain conditions that you specify are met or not met.
1. Click on the integration tile for which you want to define escalation policies.
The **Escalations** section for the notification is in the pane to the right of the list of notifications.
You can click **Change alert template and grouping** to customize the look of the alert. You can also do this by clicking the **Settings** (gear) icon in the integration tile.
1. Create an escalation chain.
In the escalation pane, click **Escalate to** to choose from previously added escalation chains, or create a new one by clicking **Make a copy** or **Create a new chain**. This will be the name of the escalation policy you define.
1. Add escalation steps.
Click **Add escalation step** to choose from a set of actions and specify their triggering conditions. By default, the first step is to notify a slack channel or user. Specify users or channels or toggle the switch to turn this step off.
To mark an escalation as **Important**, select the option from the step **Start** dropdown menu. User notification policies can be separately defined for **Important** and **Default** escalations.
## Create a route
To add a route, click **Add Route**.
You can set up a single route and specify notification escalation steps, or you can add multiple routes, each with its own configuration.
Each route added to an escalation policy follows an `IF`, `ELSE IF`, or `ELSE` path and depends on the type of alert you specify using a regular expression that matches content in the payload body of the alert. You can also specify where to send the notification for each route.
For example, you can send notifications for alerts with `\"severity\": \"critical\"` in the payload to an escalation chain called `Bob_OnCall`. You can create a different route for alerts with the payload `\"namespace\" *: *\"synthetic-monitoring-dev-.*\"` and select a escalation chain called `NotifySecurity`.
You can set up escalation steps for each route in a chain.
>**NOTE:** When you modify an escalation chain or a route, it will modify that escalation chain across all integrations that use it.

View file

@ -0,0 +1,53 @@
---
aliases:
- /docs/oncall/latest/escalation-policies/configure-routes/
keywords:
- Grafana Cloud
- Alerts
- Notifications
- on-call
- amixr
- oncall
- integrations
title: Configure and manage Routes
weight: 300
---
# Configure and manage Routes
Set up escalation chains and routes to configure escalation behavior for alert group notifications.
## Configure escalation chains
You can create and edit escalation chains in two places: within **Integrations**, by clicking on an integration tile, and in **Escalation Chains**. The following steps are for the **Integrations** workflow, but are generally applicable in both situations.
You can use **escalation chains** and **routes** to determine ordered escalation procedures. Escalation chains allow you to set up a series of alert group notification actions that trigger if certain conditions that you specify are met or not met.
1. Click on the integration tile for which you want to define escalation policies.
The **Escalations** section for the notification is in the pane to the right of the list of notifications.
You can click **Change alert template and grouping** to customize the look of the alert. You can also do this by clicking the **Settings** (gear) icon in the integration tile.
1. Create an escalation chain.
In the escalation pane, click **Escalate to** to choose from previously added escalation chains, or create a new one by clicking **Make a copy** or **Create a new chain**. This will be the name of the escalation policy you define.
1. Add escalation steps.
Click **Add escalation step** to choose from a set of actions and specify their triggering conditions. By default, the first step is to notify a slack channel or user. Specify users or channels or toggle the switch to turn this step off.
To mark an escalation as **Important**, select the option from the step **Start** dropdown menu. User notification policies can be separately defined for **Important** and **Default** escalations.
## Create a route
To add a route, click **Add Route**.
You can set up a single route and specify notification escalation steps, or you can add multiple routes, each with its own configuration.
Each route added to an escalation policy follows an `IF`, `ELSE IF`, or `ELSE` path and depends on the type of alert you specify using a regular expression that matches content in the payload body of the alert. You can also specify where to send the notification for each route.
For example, you can send notifications for alerts with `\"severity\": \"critical\"` in the payload to an escalation chain called `Bob_OnCall`. You can create a different route for alerts with the payload `\"namespace\" *: *\"synthetic-monitoring-dev-.*\"` and select a escalation chain called `NotifySecurity`.
You can set up escalation steps for each route in a chain.
> **NOTE:** When you modify an escalation chain or a route, it will modify that escalation chain across all integrations that use it.

View file

@ -0,0 +1,127 @@
---
aliases:
- /docs/grafana-cloud/oncall/getting-started/
- /docs/oncall/latest/getting-started/
keywords:
- Grafana Cloud
- Alerts
- Notifications
- on-call
title: Getting started with Grafana OnCall
weight: 100
---
# Getting started with Grafana OnCall
These procedures introduce you to the configuration of user settings, how to set up escalation policies, and how to use your calendar service for on-call scheduling.
## Before you begin
You must have a [Grafana Cloud](https://grafana.com/products/cloud/) account or [Open Source Grafana OnCall]({{< relref " open-source.md" >}})
Each supported integration and the associated monitoring system has a slightly different configuration method. These methods will not be explained in this guide, however, you can follow the online instructions provided when adding an integration.
## Configure user notification policies
You can configure how each user will receive notifications when they are assigned in escalation policies.
1. Find users.
Select the **Users** tab and use the browser to search for a user in your organization.
1. Configure user settings.
Add and verify a phone number and a Slack username if you want to deliver notifications using these mediums.
<br>
> **NOTE:** To edit a user's username, email, or role, you must do so in the **Users** tab in the **Configuration** menu of your Grafana instance.
1. Configure notification settings.
You can configure the notification medium and frequency for each user. **Important Notifications** are specified in escalation steps.
## Connect to integration data sources
You use Grafana OnCall to connect to the monitoring services of your alert sources listed in the Grafana OnCall **Integrations** section.
1. Connect to a alert source with configured alerts.
In Grafana OnCall, click on the **Integrations** tab and click **+ New integration for receiving alerts**.
1. Select an integration from the provided options.
If you want to use an integration that is not listed, you must use webhooks.
1. Configure your integration.
Each integration has a different method of connecting to Grafana OnCall. For example, if you want to connect to your Grafana alert source, select Grafana and follow the instructions.
## Configure escalation policies
You can use **escalation chains** to determine ordered escalation procedures. Configuring escalation chains allows you to set up a chain of incident notification actions that trigger if certain conditions that you specify are not met.
1. Click on the integration tile for which you want to define escalation policies.
The **Escalations** section for the notification is in the pane to the right of the list of notifications.
You can click **Change alert template and grouping** to customize the look of the alert. You can also do this by clicking the **Settings** (gear) icon in the integration tile.
1. Create an escalation chain.
In the escalation pane, click the **escalate to** menu to choose from previously added escalation chains, or create a new one by clicking **Create a new**. This will be the name of the escalation policy you define.
1. Add escalation steps.
Click **Add escalation step** to choose from a set of actions and specify their triggering conditions. By default, the first step is to notify a slack channel or user. Specify users or channels or toggle the switch to turn this step off.
To mark an escalation as **Important**, select the option from the step **Start** dropdown menu. User notification policies can be separately defined for **Important** and **Default** escalations.
1. Add a route.
To add a route, click **Add Route**.
You can set up a single route and specify notification escalation steps, or you can add multiple routes, each with its own configuration.
Each route added to an escalation policy follows an `IF`, `ELSE IF`, and `ELSE` path and depends on the type of alert you specify using a regular expression that matches content in the payload body of the alert. You can also specify where to send the notification for each route.
For example, you can send notifications for alert incidents with `\"severity\": \"critical\"` in the payload to an escalation chain called `Bob_OnCall`. You can create a different route for alerts with the payload `\"namespace\" *: *\"synthetic-monitoring-dev-.*\"` and select a escalation chain called `NotifySecurity`.
You can set up escalation steps for each route in a chain.
> **NOTE:** When you modify an escalation chain or a route, it will modify that escalation chain across all integrations that use it.
## Use calendars to configure on-call schedules
You can use any calendar with an iCal address to schedule on-call times for users. During these times, notifications configured in escalation chains with the **Notify users from an on-call schedule** setting will be sent to the the person scheduled. You can also schedule multiple users for overlapping times, and assign prioritization labels for the user that you would like to notify.
1. In the **Scheduling** section of Grafana OnCall, click **+ Create schedule**.
1. Give the schedule a name.
1. Create a new calendar in your calendar service and locate the secret iCal URL. For example, in a Google calendar, this URL can be found in **Settings > Settings for my calendars > Integrate calendar**.
1. Copy the secret iCal URL. In OnCall, paste it into the **Primary schedule for iCal URL** field.
The permissions you set for the calendar determine who can modify the calendar.
1. Click **Create Schedule**.
1. Schedule on-call times for team members.
Use the usersname of team members as the event name to schedule their on-call times. You can take advantage of all of the features of your calendar service.
1. (Optional) Create overlapping schedules.
When you create schedules that overlap, you can prioritize a schedule by adding a level marker. For example, if users AliceGrafana and BobGrafana have overlapping schedules, but BobGrafana is the primary contact, you would name his event `[L1] BobGrafana`, AliceGrafana maintains the default `[L0]` status, and would not receive notifications during the overlapping time. You can prioritize up to and including level 9, or `[L9]`.
### (Optional) Create an override calendar.
You can use an override calendar to allow team members to schedule on-call duties that will override the primary schedule. An override option allows flexibility without modifying the primary schedule. Events scheduled on the override calendar will always override overlapping events on the primary calendar.
1. Create a new calendar using the same calendar service you used to create the primary calendar.
Be sure to set permissions that allow team members to edit the calendar.
1. In the scheduling section of Grafana OnCall, select the primary calendar you want to override.
1. Click **Edit**.
1. Enter the secret iCal URL in the **Overrides schedule iCal URL** field and click **Update**.

View file

@ -1,11 +1,85 @@
+++
title = "Connect to Grafana OnCall"
keywords = ["Grafana Cloud", "Alerts", "Notifications", "on-call", "amixr", "oncall", "integrations"]
weight = 100
aliases = ["/docs/grafana-cloud/oncall/integrations/"]
+++
---
aliases:
- /docs/grafana-cloud/oncall/integrations/
- /docs/oncall/latest/integrations/
keywords:
- Grafana Cloud
- Alerts
- Notifications
- on-call
- amixr
- oncall
- integrations
title: Connect to Grafana OnCall
weight: 300
---
# Connect to Grafana OnCall
There are many alert sources that Grafana OnCall directly supports. Those that aren't listed in the integrations menu in OnCall can be connected using webhooks and configured with custom templates. To configure integrations that are directly supported, follow the instructions provided after selecting a data source in the **Integrations** tab in Grafana OnCall. To review general instructions, and also specific integration instructions for some popular integration options, see the following topics:
Integrations allow you to connect monitoring systems of your choice to send alerts to Grafana OnCall. Regardless of where your alerts originate, you can configure alerts to be sent to Grafana OnCall for alert escalation and notification. Grafana OnCall receives alerts in JSON format via a POST request, OnCall then parses alert data using preconfigured alert templates to determine alert grouping, apply routes, and determine correct escalation.
There are many integrations that are directly supported by Grafana OnCall. Those that arent currently listed in the Integrations menu can be connected using the webhook integration and configured alert templates.
## Configure and manage integrations
You can configure and manage your integrations from the **Integrations** tab in Grafana OnCall. The following sections describe how to configure and customize your integrations to ensure alerts are treated appropriately.
### Connect an integration to Grafana OnCall
To configure an integration for Grafana OnCall:
1. In Grafana OnCall, navigate to the **Integrations** tab and click **+ New integration for receiving alerts**.
2. Select an integration from the provided options, if the integration you want isnt listed, then select **Webhook**.
3. Follow the configuration steps on the integration settings page.
4. Complete any necessary configurations in your tool to send alerts to Grafana OnCall.
### Manage Grafana OnCall integrations
To manage existing integrations, navigate to the **Integrations** tab in Grafana OnCall and select the integration you want to manage.
#### Customize alert templates and grouping
To customize the alert template for an integration:
1. Select an integration from your list of enabled integrations in the **Integrations** tab.
2. Click **Change alert template and grouping**.
3. Select a template to edit from the **Edit template for** dropdown menu.
4. Edit alert templates as needed to customize the fields and content rendered for an alert.
To customize alert grouping for an integration:
1. Click **Change alert template and grouping**.
2. Select **Alert Behavior** from the dropdown menu next to **Edit template for**.
3. Edit the **grouping id**, **acknowledge condition**, and **resolve condition** templates as needed to customize your alert behavior.
For more information on alert templates, see [Configure alerts in Grafana OnCall]({{< relref " ../create-custom-templates/" >}})
#### Add Routes
To add a route to an integration using regular expression:
1. Select an integration from your list of enabled integrations in the **Integrations** tab.
2. Click **+ Add Route**.
3. Use python style regex to match on your alert content.
4. Click **Create Route**.
5. Select an escalation chain for “**IF** alert payload matches regex” and “**ELSE**” to specify where to route each type of alert.
To learn more about routes, refer to [Configure and manage Routes]({{< relref " ../configure-routes/" >}})
#### Edit integration name
To edit the name of an integration:
1. Navigate to the **Integrations** tab, select an integration from the list of enabled integrations.
2. Click the **pencil icon** next to the integration name.
3. Provide a new name and click **Update**.
#### Delete integration
To delete an integration:
1. Select an integration from your list of enabled integrations in the **Integrations** tab.
2. Click the **trash can** icon next to the selected integration.
3. Confirm by clicking **Delete**.
{{< section >}}

View file

@ -1,58 +0,0 @@
+++
title = "Configure alert notifications with Alertmanager"
keywords = ["Grafana Cloud", "Alerts", "Notifications", "on-call", "Alertmanager", "Prometheus"]
aliases = ["/docs/grafana-cloud/oncall/integrations/add-alertmanager/"]
weight = 500
+++
# Alertmanager (Prometheus)
The Alertmanager integration handles alerts sent by client applications such as the Prometheus server.
Grafana OnCall provides<!--[grouping](#alertmanager-grouping-amp-oncall-grouping)--> grouping abilities when processing alerts from Alertmanager, including initial deduplicating, grouping, and routing the alerts to Grafana OnCall.
## Connect Alertmanager to Grafana OnCall
You must have an Admin role to connect to Grafana OnCall.
1. Navigate to the **Integrations** tab in Grafana OnCall.
1. Click on the Alertmanager icon.
1. Follow the instructions that display in the dialog box to find a unique integration URL in the monitoring configuration.
<!--![123](../_images/connect-new-monitoring.png)-->
## Configure Alertmanager
Update the `receivers` section of your Alertmanager configuration to use a unique integration URL:
```
route:
receiver: 'oncall'
group_by: [alertname, datacenter, app]
receivers:
- name: 'oncall'
webhook_configs:
- url: <integation-url>
send_resolved: true
```
## Configure grouping with Alertmanager and Grafana OnCall
You can use the grouping mechanics of Alertmanager and Grafana OnCall to configure settings for groups of alert notifications.
Alertmanager offers three grouping settings:
- `group_by` provides two options, `instance` or `job`.
- `group_wait` sets the length of time to initially wait before sending a notification for a particular group of alerts. For example, `group_wait` can be set to 45s.
Setting a high value for `group_wait` reduces alert noise and minimizes interruption, but it may introduce longer delays in receiving alert notifications. To set an appropriate wait time, consider whether the group of alerts will be the same as those previously sent.
- `group_interval` sets the length of time to wait before sending notifications about new alerts that have been added to a group of alerts that have been previously alerted on. This setting is usually set to five minutes or more.
During high alert volume periods, Alertmanager will send alerts at each `group_interval`, which can mean a lot of distraction. Grafana OnCall grouping will help manage this in the following ways:
- Grafana OnCall groups alerts based on the first label of each alert.
- Grafana OnCall marks an incident as resolved only when the amount of grouped alerts with state `resolved` equals the amount of alerts with state `firing`.

View file

@ -1,60 +0,0 @@
+++
title = "Configure alert notifications with Grafana Alerting"
keywords = ["Grafana Cloud", "Alerts", "Notifications", "on-call", "Prometheus"]
aliases = ["/docs/grafana-cloud/oncall/integrations/add-grafana-alerting/"]
weight = 300
+++
# Connect Grafana Alerting to Grafana OnCall
You must have the Admin role assigned to connect to Grafana OnCall.
1. Navigate to the **Integrations** tab in Grafana OnCall.
1. Click on the Grafana logo.
1. Follow the instructions that display in the dialog box to find a unique integration URL in the monitoring configuration.
## Grafana installations
Grafana OnCall can be set up using two methods:
- Grafana Alerting: Grafana OnCall is connected to the same Grafana instance being used to manage Grafana OnCall.
- Grafana (External): Grafana OnCall is connected to one or more Grafana instances separate from the one being used to manage Grafana OnCall.
### Grafana Cloud Alerting
Use the following method if you are connecting Grafana OnCall with alerts coming from the same Grafana instance from which Grafana OnCall is being managed.
1. In Grafana OnCall, navigate to the **Integrations** tab and select **New Integration for receiving alerts**.
1. Click **Quick connect** in the **Grafana Alerting** tile. This will automatically create the integration in Grafana OnCall as well as the required contact point in Alerting.
>**Note:** You must connect the contact point with a notification policy. For more information, see [Contact points in Grafana Alerting](https://grafana.com/docs/grafana/latest/alerting/unified-alerting/contact-points/)
1. Determine the escalation chain for the new integration by either selecting an existing one or by creating a new chain. For more information on creating escalation chains, see: [Configure alert notifications with Grafana OnCall]({{< relref "../configure-notifications" >}})..
1. In Grafana Cloud Alerting, navigate to **Alerting > Contact Points** and find a contact point with a name matching the integration you created in Grafana OnCall.
1. Click the **Edit** (pencil) icon, then click **Test**. This will send an alert to Grafana OnCall.
### Grafana (External)
Connect Grafana OnCall with alerts coming from an instance of Grafana different from the one on which Grafana OnCall is being managed:
1. In Grafana OnCall, navigate to the **Integrations** tab and select **New Integration for receiving alerts**.
1. Select the **Grafana** tile.
1. View and save the URL needed to connect.
1. Determine the escalation chain for the new integration by either selecting an existing one or by creating a new chain. For more information on creating escalation chains, see: [Configure alert notifications with Grafana OnCall]({{< relref "../configure-notifications/" >}}).
1. Go to the other Grafana instance to connect to Grafana OnCall and navigate to **Alerting > Contact Points**.
1. Select **New Contact Point**.
1. Choose the contact point type `webhook`, then paste the URL generated in step 3 into the URL field.
>**Note:** You must connect the contact point with a notification policy. For more information, see [Contact points in Grafana Alerting](https://grafana.com/docs/grafana/latest/alerting/unified-alerting/contact-points/).
1. Click the **Edit** (pencil) icon, then click **Test**. This will send an alert to Grafana OnCall.

View file

@ -1,22 +0,0 @@
+++
title = "Integrate with data sources"
keywords = ["Grafana Cloud", "Alerts", "Notifications", "on-call", "Alertmanager", "Prometheus"]
aliases = ["/docs/grafana-cloud/oncall/integrations/add-integration/"]
weight = 100
+++
# Integrate with data sources
Grafana OnCall can connect directly to the monitoring services of your data sources listed in the Grafana OnCall **Integrations** section.
1. Connect to a data source with configured alerts.
In Grafana OnCall, click on the **Integrations** tab and click **+ New integration for receiving alerts**.
1. Select an integration from the provided options.
If you want to use an integration that is not listed, you must use webhooks. To learn more about using webhooks see [Integrate with webhooks]({{< relref "/integrations/webhooks/add-webhook-integration/" >}}).
1. Configure your integration.
Each integration has a different method of connecting to Grafana OnCall. For example, if you want to connect to your Grafana data source, select Grafana and follow the instructions.

View file

@ -0,0 +1,58 @@
---
aliases:
- /docs/oncall/latest/integrations/add-webhook-integration/
keywords:
- Grafana Cloud
- Alerts
- Notifications
- on-call
- Alertmanager
- Prometheus
title: Webhook integration for Grafana OnCall
weight: 700
---
# Configure Webhook integrations for Grafana OnCall
Grafana OnCall directly supports many integrations, those that arent currently listed in the Integrations menu can be connected using the webhook integration and configured alert templates.
With the webhook integration, you can connect to any alert source that isn't listed in the **Create Integration** page.
There are two available formats, **Webhook** and **Formatted Webhook**.
- **Webhook** will pull all of the raw JSON payload and display it in the manner that it's received.
- **Formatted Webhook** can be used if the alert payload sent by your monitoring service is formatted in a way that OnCall recognizes.
The following fields are recognized, but none are required:
- `alert_uid`: a unique alert ID for grouping.
- `title`: a title.
- `image_url`: a URL for an image attached to alert.
- `state`: either `ok` or `alerting`. Helpful for auto-resolving.
- `link_to_upstream_details`: link back to your monitoring system.
- `message`: alert details.
To configure a webhook integration:
1. In the **Integrations** tab, click **+ New integration for receiving alerts**.
2. Select either **Webhook** or **Formatted Webhook** integration.
3. Follow the configuration steps in the **How to connect** section of the integration settings.
4. Use the unique webhook URL to complete any configuration in your monitoring service to send POST requests. Use any http client, e.g. curl to send POST requests with any payload.
For example:
```json
curl -X POST \
https://a-prod-us-central-0.grafana.net/integrations/v1/formatted_webhook/m12xmIjOcgwH74UF8CN4dk0Dh/ \
-H 'Content-Type: Application/json' \
-d '{
"alert_uid": "08d6891a-835c-e661-39fa-96b6a9e26552",
"title": "The whole system is down",
"image_url": "https://upload.wikimedia.org/wikipedia/commons/e/ee/Grumpy_Cat_by_Gage_Skidmore.jpg",
"state": "alerting",
"link_to_upstream_details": "https://en.wikipedia.org/wiki/Downtime",
"message": "Smth happened. Oh no!"
}'
```
To learn how to use custom alert templates for formatted webhooks, see [Configure alerts in Grafana OnCall]({{< relref "../create-custom-templates/" >}}).

View file

@ -0,0 +1,26 @@
---
aliases:
- /docs/grafana-cloud/oncall/integrations/add-integration/
- /docs/oncall/latest/integrations/available-integrations /
keywords:
- Grafana Cloud
- Alerts
- Notifications
- on-call
- Alertmanager
- Prometheus
title: Currently available integrations for Grafana OnCall
weight: 100
---
# Currently available integrations
Grafana OnCall can connect directly to the monitoring services where your alerts originate. All currently available integrations are listed in the Grafana OnCall **Create Integration** section.
If the integration you're looking for isn't currently listed, see [Configure Webhook integrations for Grafana OnCall]({{< relref " ../add-webhook-integration/" >}}) to integration your monitoring system with Grafana OnCall.
> **Note:** Some integrations are available for Grafana Cloud instances only. See individual integration guides for more information.
The following integrations are currently available for Grafana OnCall and have documentation:
{{< section >}}

View file

@ -0,0 +1,67 @@
---
aliases:
- /docs/grafana-cloud/oncall/available-integrations/add-alertmanager/
- /docs/oncall/latest/integrations/available-integrations /add-alertmanager/
keywords:
- Grafana Cloud
- Alerts
- Notifications
- on-call
- Alertmanager
- Prometheus
title: Connect Alert Manager to Grafana OnCall
weight: 300
---
# Connect AlertManager to Grafana OnCall
The AlertManager integration for Grafana OnCall handles alerts sent by client applications such as the Prometheus server.
Grafana OnCall provides<!--[grouping](#alertmanager-grouping-amp-oncall-grouping)--> grouping abilities when processing alerts from Alert Manager, including initial deduplicating, grouping, and routing the alerts to Grafana OnCall.
## Configure AlertManager integration for Grafana OnCall
You must have an Admin role to create integrations in Grafana OnCall.
1. In the **Integrations** tab, click **+ New integration for receiving alerts**.
2. Select **AlertManager** from the list of available integrations.
3. Follow the instructions in the **How to connect** window to get your unique integration URL and identify next steps.
<!--![123](../_images/connect-new-monitoring.png)-->
## Configure AlertManager
Update the `receivers` section of your Alertmanager configuration to use a unique integration URL:
```
route:
receiver: 'oncall'
group_by: [alertname, datacenter, app]
receivers:
- name: 'oncall'
webhook_configs:
- url: <integation-url>
send_resolved: true
```
## Configure grouping with AlertManager and Grafana OnCall
You can use the alert grouping mechanics of AlertManager and Grafana OnCall to configure your alert grouping preferences.
AlertManager offers three alert grouping options:
- `group_by` provides two options, `instance` or `job`.
- `group_wait` sets the length of time to initially wait before sending a notification for a particular group of alerts. For example, `group_wait` can be set to 45s.
Setting a high value for `group_wait` reduces alert noise and minimizes interruption, but it may introduce delays in receiving alert notifications. To set an appropriate wait time, consider whether the group of alerts will be the same as those previously sent.
- `group_interval` sets the length of time to wait before sending notifications about new alerts that have been added to a group of alerts that have been previously alerted on. This setting is usually set to five minutes or more.
During high alert volume periods, AlertManager will send alerts at each `group_interval`, which can mean a lot of distraction. Grafana OnCall grouping will help manage this in the following ways:
- Grafana OnCall groups alerts based on the first label of each alert.
- Grafana OnCall marks an incident as resolved only when the amount of grouped alerts with state `resolved` equals the amount of alerts with state `firing`.

View file

@ -0,0 +1,69 @@
---
aliases:
- /docs/grafana-cloud/oncall/integrations/add-grafana-alerting/
- /docs/oncall/latest/integrations/available-integrations /add-grafana-alerting/
keywords:
- Grafana Cloud
- Alerts
- Notifications
- on-call
- Prometheus
title: Connect Grafana Alerting to Grafana OnCall
weight: 100
---
# Connect Grafana Alerting to Grafana OnCall
Grafana Alerting for Grafana OnCall can be set up using two methods:
- Grafana Alerting: Grafana OnCall is connected to the same Grafana instance being used to manage Grafana OnCall.
- Grafana (Other Grafana): Grafana OnCall is connected to one or more Grafana instances separate from the one being used to manage Grafana OnCall.
## Configure Grafana Alerting for Grafana OnCall
You must have an Admin role to create integrations in Grafana OnCall.
1. In the **Integrations** tab, click **+ New integration for receiving alerts**.
2. Select **Grafana Alerting** by clicking the **Quick connect** button or select **Grafana (Other Grafana)** from the integrations list.
3. Follow the configuration steps that display in the **How to connect** window to retrieve your unique integration URL and complete any necessary configurations.
### Configure Grafana Cloud Alerting
Use the following method if you are connecting Grafana OnCall with alerts coming from the same Grafana instance from which Grafana OnCall is being managed.
1. In Grafana OnCall, navigate to the **Integrations** tab and select **New Integration for receiving alerts**.
1. Click **Quick connect** in the **Grafana Alerting** tile. This will automatically create the integration in Grafana OnCall as well as the required contact point in Alerting.
> **Note:** You must connect the contact point with a notification policy. For more information, see [Contact points in Grafana Alerting](https://grafana.com/docs/grafana/latest/alerting/unified-alerting/contact-points/)
1. Determine the escalation chain for the new integration by either selecting an existing one or by creating a new escalation chain.
1. In Grafana Cloud Alerting, navigate to **Alerting > Contact Points** and find a contact point with a name matching the integration you created in Grafana OnCall.
1. Click the **Edit** (pencil) icon, then click **Test**. This will send a test alert to Grafana OnCall.
### Configure Grafana (Other Grafana)
Connect Grafana OnCall with alerts coming from a Grafana instance that is different from the instance that Grafana OnCall is being managed:
1. In Grafana OnCall, navigate to the **Integrations** tab and select **New Integration for receiving alerts**.
2. Select the **Grafana (Other Grafana)** tile.
3. Follow the configuration steps that display in the **How to connect** window to retrieve your unique integration URL and complete any necessary configurations.
4. Determine the escalation chain for the new integration by either selecting an existing one or by creating a new escalation chain.
5. Go to the other Grafana instance to connect to Grafana OnCall and navigate to **Alerting > Contact Points**.
6. Select **New Contact Point**.
7. Choose the contact point type `webhook`, then paste the URL generated in step 3 into the URL field.
> **Note:** You must connect the contact point with a notification policy. For more information, see [Contact points in Grafana Alerting](https://grafana.com/docs/grafana/latest/alerting/unified-alerting/contact-points/).
8. Click the **Edit** (pencil) icon, then click **Test**. This will send a test alert to Grafana OnCall.

View file

@ -1,99 +1,114 @@
+++
title = "Configure alert notifications with Zabbix"
keywords = ["Grafana Cloud", "Alerts", "Notifications", "on-call", "Zabbix"]
weight = 700
+++
---
aliases:
- /docs/oncall/latest/integrations/available-integrations /add-zabbix/
keywords:
- Grafana Cloud
- Alerts
- Notifications
- on-call
- Zabbix
title: Connect Zabbix to Grafana OnCall
weight: 500
---
# Connect Zabbix to Grafana OnCall
Zabbix is an open-source monitoring software tool for diverse IT components, including networks, servers, virtual machines, and cloud services. Zabbix provides monitoring for metrics such as network utilization, CPU load, and disk space consumption.
To connect Grafana OnCall with Zabbix using the following procedure, you must have an Admin role assigned.
## Configure Zabbix integration for Grafana OnCall
1. Navigate to the **Integrations** tab in Grafana OnCall.
1. Follow the instructions that display in the dialog box to use a unique integration URL in the monitoring configuration.
This integration is available for Grafana Cloud OnCall. You must have an Admin role to create integrations in Grafana OnCall.
1. In the **Integrations** tab, click **+ New integration for receiving alerts**.
2. Select **Zabbix** from the list of available integrations
3. Follow the instructions in the **How to connect** window to get your unique integration URL and review next steps.
<!--![123](../_images/connect-new-monitoring.png)-->
## Configure the Zabbix server
1. Deploy a Zabbix playground if you don't have one set up:
```bash
docker run --name zabbix-appliance -t \
-p 10051:10051 \
-p 80:80 \
-d zabbix/zabbix-appliance:latest
```
```bash
docker run --name zabbix-appliance -t \
-p 10051:10051 \
-p 80:80 \
-d zabbix/zabbix-appliance:latest
```
1. Establish an ssh connection to a Zabbix server.
```bash
docker exec -it zabbix-appliance bash
```
```bash
docker exec -it zabbix-appliance bash
```
1. Place the [grafana_oncall.sh](#grafana_oncallsh-script) script in the `AlertScriptsPath` directory specified within the Zabbix server configuration file (zabbix_server.conf).
```bash
grep AlertScriptsPath /etc/zabbix/zabbix_server.conf
```
>**Note:** The script must be executable by the user running the zabbix_server binary (usually "zabbix") on the Zabbix server. For example, `chmod +x grafana_oncall.sh`
```bash
grep AlertScriptsPath /etc/zabbix/zabbix_server.conf
```
``` bash
ls -lh /usr/lib/zabbix/alertscripts/grafana_oncall.sh
-rw-r--r-- 1 root root 1.5K Jun 6 07:52 /usr/lib/zabbix/alertscripts/grafana_oncall.sh
```
> **Note:** The script must be executable by the user running the zabbix_server binary (usually "zabbix") on the Zabbix server. For example, `chmod +x grafana_oncall.sh`
```bash
ls -lh /usr/lib/zabbix/alertscripts/grafana_oncall.sh
-rw-r--r-- 1 root root 1.5K Jun 6 07:52 /usr/lib/zabbix/alertscripts/grafana_oncall.sh
```
## Configure Zabbix alerts
Within Zabbix web interface, do the following:
1. In a browser, open localhost:80.
1. Navigate to **Adminitstration > Media Types > Create Media Type**.
<!--![](../_images/zabbix-1.png)-->
<!--![](../_images/zabbix-1.png)-->
1. Create a Media Type with the following fields.
* Name: Grafana OnCall
* Type: script
* Script parameters:
* {ALERT.SENDTO}
* {ALERT.SUBJECT}
* {ALERT.MESSAGE}
<!--![](../_images/zabbix-2.png)-->
- Name: Grafana OnCall
- Type: script
- Script parameters:
- {ALERT.SENDTO}
- {ALERT.SUBJECT}
- {ALERT.MESSAGE}
<!--![](../_images/zabbix-2.png)-->
### Set the {ALERT.SEND_TO} value
To send alerts to Grafana OnCall, the {ALERT.SEND_TO} value must be set in the [user media configuration](https://www.zabbix.com/documentation/3.4/manual/config/notifications/media/script#user_media).
1. In the web UI, navigate to **Administration > Users** and open the **user properties** form.
1. In the web UI, navigate to **Administration > Users** and open the **user properties** form.
1. In the **Media** tab, click **Add** and copy the link from Grafana OnCall in the `Send to` field.
<!--![](../_images/zabbix-7.png)-->
<!--![](../_images/zabbix-7.png)-->
1. Click **Test** in the last column to send a test alert to Grafana OnCall.
<!--![](../_images/zabbix-3.png)-->
<!--![](../_images/zabbix-3.png)-->
1. Specify **Send to** OnCall using the unique integration URL from the above step in the testing window that opens.
Create a test message with a body and optional subject and click **Test**.
<!--![](../_images/zabbix-4.png)
WHERE DID SLACK COME FROM?! 1. View the Grafana OnCall incident that appears in the Slack channel.
![](../_images/zabbix-5.png)-->
Create a test message with a body and optional subject and click **Test**.
<!--![](../_images/zabbix-4.png)
WHERE DID SLACK COME FROM?! 1. View the Grafana OnCall incident that appears in the Slack channel.
![](../_images/zabbix-5.png)-->
## Grouping and auto-resolve of Zabbix notifications
Grafana OnCall provides grouping and auto-resolve of Zabbix notifications.
Use the following procedure to configure grouping and auto-resolve.
1. Provide a parameter as an identifier for group differentiation to Grafana OnCall.
1. Provide a parameter as an identifier for group differentiation to Grafana OnCall.
1. Append that variable to the subject of the action as `ONCALL_GROUP: ID`, where `ID` is any of the Zabbix [macros](https://www.zabbix.com/documentation/4.2/manual/appendix/macros/supported_by_location).
For example, `{EVENT.ID}`. The Grafana OnCall script [grafana_oncall.sh](#grafana_oncallsh-script) extracts this event and passes the `alert_uid` to Grafana OnCall.
1. Append that variable to the subject of the action as `ONCALL_GROUP: ID`, where `ID` is any of the Zabbix [macros](https://www.zabbix.com/documentation/4.2/manual/appendix/macros/supported_by_location).
For example, `{EVENT.ID}`. The Grafana OnCall script [grafana_oncall.sh](#grafana_oncallsh-script) extracts this event and passes the `alert_uid` to Grafana OnCall.
1. To enable auto-resolve within Grafana Oncall, the "Resolved" keyword is required in the **Default subject** field in **Recovered operations**.
<!--![](../_images/zabbix-6.png)-->
<!--![](../_images/zabbix-6.png)-->
## grafana_oncall.sh script
```bash
#!/bin/bash
# This is the modification of original ericos's shell script.
@ -134,4 +149,5 @@ return=$(curl $url -d "${payload}" -H "Content-Type: application/json" -X POST)
```
## More Information
For more information on Zabbix scripts, see [scripts for notifications](https://www.zabbix.com/documentation/4.2/manual/config/notifications/media/script).
For more information on Zabbix scripts, see [scripts for notifications](https://www.zabbix.com/documentation/4.2/manual/config/notifications/media/script).

View file

@ -0,0 +1,51 @@
---
aliases:
- /docs/oncall/latest/integrations/configure-outgoing-webhooks/
keywords:
- Grafana Cloud
- Alerts
- Notifications
- on-call
- amixr
- webhooks
title: Configure outgoing webhooks for Grafana OnCall
weight: 500
---
# Configure outgoing webhooks for Grafana OnCall
Outgoing webhooks allow you to send alert details to a specified URL from Grafana OnCall. Once an outgoing webhook is configured, you can use it as a notification method in escalation chains.
To automatically send alert data to a destination URL via outgoing webhook:
1. In Grafana OnCall, navigate to **Outgoing Webhooks** and click **+ Create**.
This is also the place to edit and delete existing outgoing webhooks.
2. Provide a name for your outgoing webhook and enter the destination URL.
3. If the destination requires authentication, enter your credentials.
You can enter a username and password (HTTP) or an authorization header formatted in JSON.
4. Configure the webhook payload in the **Data** field.
5. Click **Create Webhook**.
The format you use to call the variables must match the structure of how the fields are nested in the alert payload. The **Data** field can use the following four variables to auto-populate the webhook payload with information about the first alert in the alert group:
- `{{ alert_title }}`
- `{{ alert_message }}`
- `{{ alert_url }}`
- `{{ alert_payload }}`
<br>
`alert_payload` is always the first level of any variable you want to call.
The following is an example of an entry in the **Data** field that might return an alert name and description.
```json
{
"name": "{{ alert_payload.labels.alertname }}",
"message": "{{ alert_payload.annotations.description }}"
}
```
> **NOTE:** If you receive an error message and cannot create an outgoing webhook, verify that your JSON is formatted correctly.

View file

@ -0,0 +1,160 @@
---
aliases:
- /docs/oncall/latest/integrations/create-custom-templates/
keywords:
- Grafana Cloud
- Alerts
- Notifications
- on-call
- Jinja
title: Configure alerts in Grafana OnCall
weight: 300
---
# Configure alerts in Grafana OnCall
Grafana OnCall can integrate with any monitoring systems that can send alerts using webhooks with JSON payloads. By default, webhooks deliver raw JSON payloads. When Grafana OnCall receives an alert and parses its payload, a default pre configured alert template is applied to modify the alert payload to be more human readable. These alert templates are customizable for any integration.
See Format alerts with alert templates in this document to learn more about how to customize alert templates.
## Alert Behavior
Once Grafana OnCall receives an alert, the following occurs, based on the alert content:
- Default or customized alert templates are applied to deliver the most useful alert fields with the most valuable information, in a readable format.
- Alerts are grouped based on your alert grouping configurations, combining similar or related alerts to reduce alert noise.
- Alerts automatically resolve if an alert from the monitoring system matches the resolve condition for that alert.
## Alert payload
Alerts received by Grafana OnCall contain metadata as keys and values in a JSON object. The following is an example of an alert from Grafana OnCall:
```json
{
"dashboardId": 1,
"title": "[Alerting] Panel Title alert",
"message": "Notification Message",
"evalMatches": [
{
"value": 1,
"metric": "Count",
"tags": {}
}
],
"imageUrl": "https://grafana.com/static/assets/img/blog/mixed_styles.png",
"orgId": 1,
"panelId": 2,
"ruleId": 1,
"ruleName": "Panel Title alert",
"ruleUrl": "http://localhost:3000/d/hZ7BuVbWz/test-dashboard?fullscreen\u0026edit\u0026tab=alert\u0026panelId=2\u0026orgId=1",
"state": "alerting",
"tags": {
"tag name": "tag value"
}
}
```
In Grafana OnCall every alert and alert group has the following fields:
- `Title`, `message` and `image url`
- `Grouping Id`
- `Resolve Signal`
The JSON payload is converted. For example:
- `{{ payload.title }}` -> Title
- `{{ payload.message }}` -> Message
- `{{ payload.imageUrl }}` -> Image Url
The result is that each field of the alert in OnCall is now mapped to the JSON payload keys. This also true for the alert behavior:
- `{{ payload.ruleId }}` -> Grouping Id
- `{{ 1 if payload.state == 'OK' else 0 }}` -> Resolve Signal
Grafana OnCall provides a pre configured default Jinja template for supported integrations. If your monitoring system is not in the Grafana OnCall integrations list, you can create a generic `webhook` integration, send an alert, and configure your templates.
## Customize alerts with alert templates
Alert templates allow you to format any alert fields recognized by Grafana OnCall. You can customize default alert templates for all the different ways you receive your alerts such as web, slack, SMS, and email. For more advanced customization, use Jinja templates.
As a best practice, add _Playbooks_, _Useful links_, or _Checklists_ to the alert message.
To customize alert templates in Grafana OnCall:
1. Navigate to the **Integrations** tab, select the integration, then click **Change alert template and grouping**.
2. In Alert Templates, select a template from the **Edit template for** dropdown.
3. Edit the Appearances template as needed:
- `Title`, `Message`, `Image url` for Web
- `Title`, `Message`, `Image url` for Slack
- `Title` used for SMS
- `Title` used for Phone
- `Title`, `Message` used for Email
4. Edit the alert behavior as needed:
- `Grouping Id` - This output groups other alerts into a single alert group.
- `Acknowledge Condition` - The output should be `ok`, `true`, or `1` to auto-acknowledge the alert group. For example, `{{ 1 if payload.state == 'OK' else 0 }}`.
- `Resolve Condition` - The output should be `ok`, `true` or `1` to auto-resolve the alert group. For example, `{{ 1 if payload.state == 'OK' else 0 }}`.
- `Source Link` - Used to customize the URL link to provide as the "source" of the alert.
## Advanced Jinja templates
Grafana OnCall uses [Jinja templating language](http://jinja.pocoo.org/docs/2.10/) to format alert groups for the Web, Slack, phone calls, SMS messages, and more because the JSON format is not easily readable by humans. As a result, you can decide what you want to see when an alert group is triggered as well as how it should be presented.
Jinja2 offers simple but multi-faceted functionality by using loops, conditions, functions, and more.
> **NOTE:** Every alert from a monitoring system comes in the key/value format.
Grafana OnCall has rules about which of the keys match to: `__title`, `message`, `image`, `grouping`, and `auto-resolve__`.
### Loops
Monitoring systems can send an array of values. In this example, you can use Jinja to iterate and format the alert using a Grafana example:
```.jinja2
*Values:*
{% for evalMatch in payload.evalMatches -%}
`{{ evalMatch['metric'] }}: '{{ evalMatch['value'] -}}'`{{ " " }}
{%- endfor %}
```
### Conditions
You can add instructions if an alert comes from a specified Grafana alert rule:
````jinja2
{% if payload.ruleId == '1' -%}
*Alert TODOs*
1. Get acess to the container
```
kubectl port-forward service/example 3000:80
```
2. Check for the exception.
3. Open the container and reload caches.
4. Click Custom Button `Send to Jira`
{%- endif -%}
````
### Built-in Jinja functions
Jinja2 includes built-in functions that can also be used in Grafana OnCall. For example:
```.jinja2
{{ payload | tojson_pretty }}
```
Built-in functions:
- `abs`
- `capitalize`
- `trim`
- You can see the full list of Jinja built-in functions on github [here](https://github.com/pallets/jinja/blob/3915eb5c2a7e2e4d49ebdf0ecb167ea9c21c60b2/src/jinja2/filters.py#L1307)
### Functions added by Grafana OnCall
- `time` - current time
- `tojson_pretty` - JSON prettified
- `iso8601_to_time` - converts time from iso8601 (`2015-02-17T18:30:20.000Z`) to datetime
- `datetimeformat` - converts time from datetime to the given format (`%H:%M / %d-%m-%Y` by default)

View file

@ -1,12 +0,0 @@
+++
title = "Use webhooks to send and receive alerts"
keywords = ["Grafana Cloud", "Alerts", "Notifications", "on-call", "Alertmanager", "Prometheus"]
weight = 900
+++
# Use webhooks to send and receive alerts
You can use webhooks to send alert group notifications, and also to receive alerts in the event that the data source for for the alerts is not directly supported by Grafana OnCall. You can also use custom templates to format your alerts.
Follow these links to learn more about using webhooks for OnCall alert notifications:
{{< section >}}

View file

@ -1,39 +0,0 @@
+++
title = "Webhook integration"
keywords = ["Grafana Cloud", "Alerts", "Notifications", "on-call", "Alertmanager", "Prometheus"]
weight = 100
+++
# Integrate with your data source using webhooks
Grafana OnCall directly supports integrations from many data sources, but you can connect to any data source that isn't listed in the **Create Integration** page by using webhooks.
1. In **Integrations**, click **+ New integration for receiving alerts**.
1. Select a webhook format.
There are two available formats. **Webhook** and **Formatted Webhook**.
* **Webhook** will pull all of the raw JSON information and display it in the manner that it is received.
* **Formatted Webhook** can be used if the body of the alerts sent by your monitoring service are formatted in a way that OnCall can read. The following fields are recognized, but none are required:
* `alert_uid`: a unique alert ID for grouping.
* `title`: a title.
* `image_url`: a URL for an image attached to alert.
* `state`: either `ok` or `alerting`. Helpful for auto-resolving.
* `link_to_upstream_details`: link back to your monitoring system.
* `message`: alert details.
To learn how to use custom alert templates for formatted webhooks, see [Configure custom alert templates]({{< relref "../create-custom-templates/" >}}).
1. Use the unique webhook URL for requests. For example:
```json
curl -X POST \
https://a-prod-us-central-0.grafana.net/integrations/v1/formatted_webhook/m12xmIjOcgwH74UF8CN4dk0Dh/ \
-H 'Content-Type: Application/json' \
-d '{
"alert_uid": "08d6891a-835c-e661-39fa-96b6a9e26552",
"title": "The whole system is down",
"image_url": "https://upload.wikimedia.org/wikipedia/commons/e/ee/Grumpy_Cat_by_Gage_Skidmore.jpg",
"state": "alerting",
"link_to_upstream_details": "https://en.wikipedia.org/wiki/Downtime",
"message": "Smth happened. Oh no!"
}'
```

View file

@ -1,39 +0,0 @@
+++
title = "Send alert notifications by webhook"
keywords = ["Grafana Cloud", "Alerts", "Notifications", "on-call", "amixr", "webhooks"]
weight = 500
+++
# Send alert group notifications by webhook
You can configure outgoing webhooks to send alerts to destination. Once a webhook is created, you can choose the webhook as a notification method in escalation steps.
1. In Grafana OnCall, navigate to **Outgoing Webhooks** and click **+ Create**.
This is also the place to edit and delete existing webhooks.
1. Name your webhook and enter the destination URL.
1. If the destination requires authentication, enter your credentials.
You can enter a username and password (HTTP) or an authorization header formatted in JSON.
1. Configure the webhook payload in the **Data** field.
You can use four variables to automate the body of your webhook. The format you use to call the variables must match the structure of how the fields are nested in your alert payload. The **Data** field can use the following four variables to auto-populate the webhook payload with information about the first alert in the alert group:
- `{{ alert_title }}`
- `{{ alert_message }}`
- `{{ alert_url }}`
- `{{ alert_payload }}`
<br>
`alert_payload` is always the first level of any variable you want to call.
The following is an example of an entry in the **Data** field that might return an alert name and description.
```json
{
"name": "{{ alert_payload.labels.alertname }}",
"message": "{{ alert_payload.annotations.description }}"
}
```
>**NOTE:** If you get an error message and cannot create a webhook, make sure your JSON is formatted correctly.
1. Click **Create Webhook**.

View file

@ -1,149 +0,0 @@
+++
title = "Format alerts with templates"
keywords = ["Grafana Cloud", "Alerts", "Notifications", "on-call", "Jinja"]
weight = 300
+++
# Format alerts with templates
Grafana OnCall works with over one thousand alert monitoring systems. Almost any monitoring system can send alerts using webhooks with JSON payloads.
By default, webhooks will deliver raw JSON. To modify the payload to be more human-readable, you can format your alerts fields that OnCall recognizes. You can use Jinja templates for more advanced customization.
## JSON alerting object
Alerts we receive contain metadata as keys and values in a JSON object. The following is an example of an alert from Grafana:
```json
{
"dashboardId":1,
"title":"[Alerting] Panel Title alert",
"message":"Notification Message",
"evalMatches":[
{
"value":1,
"metric":"Count",
"tags":{}
}
],
"imageUrl":"https://grafana.com/static/assets/img/blog/mixed_styles.png",
"orgId":1,
"panelId":2,
"ruleId":1,
"ruleName":"Panel Title alert",
"ruleUrl":"http://localhost:3000/d/hZ7BuVbWz/test-dashboard?fullscreen\u0026edit\u0026tab=alert\u0026panelId=2\u0026orgId=1",
"state":"alerting",
"tags":{
"tag name":"tag value"
}
}
```
## The alert payload
Once an alert is received by Grafana OnCall, the following occurs, based on the alert content:
1. The most useful information is shown in a readable format.
1. Noise is minimized by grouping alerts, combining similar alerts into a single page.
1. The alert group is resolved if the monitoring system tells Grafana OnCall to do so.
In Grafana OnCall every alert and alert group has the following fields:
- `Title`, `message` and `image url`
- `Grouping Id`
- `Resolve Signal`
The JSON payload is converted. For example:
* `{{ payload.title }}` -> Title
* `{{ payload.message }}` -> Message
* `{{ payload.imageUrl }}` -> Image Url
The result is that each field of the alert in OnCall is now mapped to the JSON payload keys. This also true for the alert behavior:
* `{{ payload.ruleId }}` -> Grouping Id
* `{{ 1 if payload.state == 'OK' else 0 }}` -> Resolve Signal
OnCall has default Jinja templates for the most popular monitoring systems.
If your monitoring system is not in the Grafana OnCAll integrations list you can create the most generic integration `Webhook`, send an alert, and write your own templates.
As a best practice, add `_Playbooks_`, `_Useful links_`, or `_Checklists_` to the alert message.
## How to customize templates
You can customize the default templates in Grafana OnCall by opening the **Settings** window in either the **Integrations** or **Alert Groups** tab:
1. From the **Integrations** tab, select the integration, then click the **Settings** (gear) icon.
<!--![123](../_images/custom-actions-1.png ':size=400')-->
1. From the **Alert Groups** tab, click **Edit rendering, grouping, and other templates**
<!--![123](../_images/custom-actions-2.png ':size=400')-->
1. In **Settings**, select the template to edit from **Edit template for**.
1. Edit the Appearances template as needed:
* `Title`, `Message`, `Image url` for Web
* `Title`, `Message`, `Image url` for Slack
* `Title` used in SMS
* `Title` used in Phone
* `Title`, `Message` used in Email
1. Edit the alert behavior as needed:
* `Grouping Id` - This output groups other alerts into a single alert group.
* `Acknowledge Condition` - The output should be `ok`, `true`, or `1` to auto-acknowledge the alert group. For example, `{{ 1 if payload.state == 'OK' else 0 }}`.
* `Resolve Condition` - The output should be `ok`, `true` or `1` to auto-resolve the alert group. For example, `{{ 1 if payload.state == 'OK' else 0 }}`.
* `Source Link` - Used to customize the URL link to provide as the "source" of the alert.
## Advanced Jinja templates
Grafana OnCall uses [Jinja templating language](http://jinja.pocoo.org/docs/2.10/) to format alert groups for the Web, Slack, phone calls, SMS messages, and more because the JSON format is not easily readable by humans. As a result, you can decide what you want to see when an alert group is triggered as well as how it should be presented.
Jinja2 offers simple but multi-faceted functionality by using loops, conditions, functions, and more.
> **NOTE:** Every alert from a monitoring system comes in the key/value format.
Grafana OnCall has rules about which of the keys match to: `__title`, `message`, `image`, `grouping`, and `auto-resolve__`.
### Loops
Monitoring systems can send an array of values. In this example, you can use Jinja to iterate and format the alert using a Grafana example:
```.jinja2
*Values:*
{% for evalMatch in payload.evalMatches -%}
`{{ evalMatch['metric'] }}: '{{ evalMatch['value'] -}}'`{{ " " }}
{%- endfor %}
```
### Conditions
You can add instructions if an alert comes from a specified Grafana alert rule:
```jinja2
{% if payload.ruleId == '1' -%}
*Alert TODOs*
1. Get acess to the container
```
kubectl port-forward service/example 3000:80
```
2. Check for the exception.
3. Open the container and reload caches.
4. Click Custom Button `Send to Jira`
{%- endif -%}
```
### Built-in Jinja functions
Jinja2 includes built-in functions that can also be used in Grafana OnCall. For example:
```.jinja2
{{ payload | tojson_pretty }}
```
Built-in functions:
* `abs`
* `capitalize`
* `trim`
* You can see the full list of Jinja built-in functions on github [here](https://github.com/pallets/jinja/blob/3915eb5c2a7e2e4d49ebdf0ecb167ea9c21c60b2/src/jinja2/filters.py#L1307)
### Functions added by Grafana OnCall
* `time` - current time
* `tojson_pretty` - JSON prettified
* `iso8601_to_time` - converts time from iso8601 (`2015-02-17T18:30:20.000Z`) to datetime
* `datetimeformat` - converts time from datetime to the given format (`%H:%M / %d-%m-%Y` by default)

View file

@ -1,14 +0,0 @@
+++
title = "Manage alert groups"
description = ""
keywords = ["Grafana", "oncall", "on-call", "calendar", "incidents", "alert groups"]
weight = 300
+++
# Manage alert groups
When you create a new alert integration, alerts are sent from the alert monitoring service of that source to Grafana OnCall. When the first alert is sent, the escalation policies you have in place for that integration determine when and where notifications are sent. Alerts will continue to gather until resolved, forming an alert group. For example, if Juan, an administrator, silences a firing alert group, the alerts will continue to collect in that group until the status is **resolved**. Once this occurs, a new alert will begin the next alert group.
In the **Alert Groups** tab, you can view alert groups by status. Groups are named by the name of the first alert that was fired. When you click on a group, you can view information on all of alerts that have fired, the source of the alerts, and the users assigned in the escalation chain associated with the group. You can also view the timeline of the group, which shows all of the actions associated with the configured escalation policies, and resolution notes.
Administrators can change the status of individual alert groups, or can select multiple groups to edit at once. Alert group status can be changed in the following ways: `acknowledge`, `resolve`, `unresolve`, `restart`, and `silence`.

View file

@ -1,7 +1,9 @@
+++
title = "Grafana OnCall HTTP API reference"
weight = 1300
+++
---
aliases:
- /docs/oncall/latest/oncall-api-reference/
title: Grafana OnCall HTTP API reference
weight: 1300
---
# HTTP API Reference
@ -23,7 +25,7 @@ curl "api_endpoint_here" --header "Authorization: meowmeowmeow"
```
Note that `meowmeowmeow` is a valid key for test purposes.
Replace `meowmeowmeow` with your API key in production.
Replace `meowmeowmeow` with your API key in production.
Grafana OnCall uses API keys to allow access to the API. You can request a new OnCall API key in the API section.
@ -31,33 +33,34 @@ An API key is specific to a user and a Grafana stack. If you want to switch to a
## Pagination
List endpoints such as List Integrations or List Alert Groups return multiple objects.
List endpoints such as List Integrations or List Alert Groups return multiple objects.
The OnCall API returns them in pages. Note that the page size may vary.
The OnCall API returns them in pages. Note that the page size may vary.
| Parameter | Meaning |
|-----------|:-------:|
`count` | The total number of items. It can be `0` if a request does not return any data.
`next` | A link to the next page. It can be `null` if the next page does not contain any data.
`previous` | A link to the previous page. It can be `null` if the previous page does not contain any data.
`results` | The data list. Can be `[]` if a request does not return any data.
| Parameter | Meaning |
| ---------- | :-------------------------------------------------------------------------------------------: |
| `count` | The total number of items. It can be `0` if a request does not return any data. |
| `next` | A link to the next page. It can be `null` if the next page does not contain any data. |
| `previous` | A link to the previous page. It can be `null` if the previous page does not contain any data. |
| `results` | The data list. Can be `[]` if a request does not return any data. |
## Rate Limits
Grafana OnCall provides rate limits to ensure alert group notifications will be delivered to your Slack workspace even when some integrations produce a large number of alerts.
### Monitoring integrations Rate Limits
Rate limited response HTTP status: 429
| Scope | Amount | Time Frame |
|------------------------------|:------:|:----------:|
| Alerts from each integration | 300 | 5 minutes |
| Alerts from the whole team | 500 | 5 minutes |
| ---------------------------- | :----: | :--------: |
| Alerts from each integration | 300 | 5 minutes |
| Alerts from the whole team | 500 | 5 minutes |
## API rate limits
You can reduce or increase rate limits depending on platform status.
| Scope | Amount | Time Frame |
|--------------------------|:------:|:--------:|
| API requests per API key | 300 | 5 minutes |
| ------------------------ | :----: | :--------: |
| API requests per API key | 300 | 5 minutes |

View file

@ -1,8 +1,10 @@
+++
title = "Alert groups HTTP API"
aliases = ["/docs/grafana-cloud/oncall/oncall-api-reference/alertgroups/"]
weight = 400
+++
---
aliases:
- /docs/grafana-cloud/oncall/oncall-api-reference/alertgroups/
- /docs/oncall/latest/oncall-api-reference/alertgroups/
title: Alert groups HTTP API
weight: 400
---
# List alert groups
@ -10,36 +12,36 @@ weight = 400
curl "{{API_URL}}/api/v1/alert_groups/" \
--request GET \
--header "Authorization: meowmeowmeow" \
--header "Content-Type: application/json"
--header "Content-Type: application/json"
```
The above command returns JSON structured in the following way:
```json
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"id": "I68T24C13IFW1",
"integration_id": "CFRPV98RPR1U8",
"route_id": "RIYGUJXCPFHXY",
"alerts_count": 3,
"state": "resolved",
"created_at": "2020-05-19T12:37:01.430444Z",
"resolved_at": "2020-05-19T13:37:01.429805Z",
"acknowledged_at": null,
"title": "Memory above 90% threshold"
}
]
"count": 1,
"next": null,
"previous": null,
"results": [
{
"id": "I68T24C13IFW1",
"integration_id": "CFRPV98RPR1U8",
"route_id": "RIYGUJXCPFHXY",
"alerts_count": 3,
"state": "resolved",
"created_at": "2020-05-19T12:37:01.430444Z",
"resolved_at": "2020-05-19T13:37:01.429805Z",
"acknowledged_at": null,
"title": "Memory above 90% threshold"
}
]
}
```
These available filter parameters should be provided as `GET` arguments:
* `route_id`
* `integration_id`
- `route_id`
- `integration_id`
**HTTP request**
@ -57,12 +59,12 @@ curl "{{API_URL}}/api/v1/alert_groups/I68T24C13IFW1/" \
}'
```
|Parameter | Required | Description |
|--------- |:--------:|:------------|
`mode` | No | Default setting is `wipe`. `wipe` will remove the payload of all Grafana OnCall group alerts. This is useful if you sent sensitive data to OnCall. All metadata will remain. `DELETE` will trigger the removal of alert groups, alerts, and all related metadata. It will also remove alert group notifications in Slack and other destinations.
| Parameter | Required | Description |
| --------- | :------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `mode` | No | Default setting is `wipe`. `wipe` will remove the payload of all Grafana OnCall group alerts. This is useful if you sent sensitive data to OnCall. All metadata will remain. `DELETE` will trigger the removal of alert groups, alerts, and all related metadata. It will also remove alert group notifications in Slack and other destinations. |
>**NOTE:** `DELETE` can take a few moments to delete alert groups because Grafana OnCall interacts with 3rd party APIs such as Slack. Please check objects using `GET` to be sure the data is removed.
> **NOTE:** `DELETE` can take a few moments to delete alert groups because Grafana OnCall interacts with 3rd party APIs such as Slack. Please check objects using `GET` to be sure the data is removed.
**HTTP request**
`DELETE {{API_URL}}/api/v1/alert_groups/<ALERT_GROUP_ID>`
`DELETE {{API_URL}}/api/v1/alert_groups/<ALERT_GROUP_ID>`

View file

@ -1,8 +1,10 @@
+++
title = "Alerts HTTP API"
aliases = ["/docs/grafana-cloud/oncall/oncall-api-reference/alerts"]
weight = 100
+++
---
aliases:
- /docs/grafana-cloud/oncall/oncall-api-reference/alerts/
- /docs/oncall/latest/oncall-api-reference/alerts/
title: Alerts HTTP API
weight: 100
---
# List Alerts
@ -10,101 +12,101 @@ weight = 100
curl "{{API_URL}}/api/v1/alerts/" \
--request GET \
--header "Authorization: meowmeowmeow" \
--header "Content-Type: application/json"
--header "Content-Type: application/json"
```
The above command returns JSON structured in the following way:
```json
{
"count": 3,
"next": null,
"previous": null,
"results": [
{
"id": "AA74DN7T4JQB6",
"alert_group_id": "I68T24C13IFW1",
"created_at": "2020-05-11T20:07:43Z",
"payload": {
"state": "alerting",
"title": "[Alerting] Test notification",
"ruleId": 0,
"message": "Someone is testing the alert notification within Grafana.",
"ruleUrl": "{{API_URL}}/",
"ruleName": "Test notification",
"evalMatches": [
{
"tags": null,
"value": 100,
"metric": "High value"
},
{
"tags": null,
"value": 200,
"metric": "Higher Value"
}
]
}
},
{
"id": "AR9SSYFKE2PV7",
"alert_group_id": "I68T24C13IFW1",
"created_at": "2020-05-11T20:07:54Z",
"payload": {
"state": "alerting",
"title": "[Alerting] Test notification",
"ruleId": 0,
"message": "Someone is testing the alert notification within Grafana.",
"ruleUrl": "{{API_URL}}/",
"ruleName": "Test notification",
"evalMatches": [
{
"tags": null,
"value": 100,
"metric": "High value"
},
{
"tags": null,
"value": 200,
"metric": "Higher Value"
}
]
}
},
{
"id": "AWJQSGEYYUFGH",
"alert_group_id": "I68T24C13IFW1",
"created_at": "2020-05-11T20:07:58Z",
"payload": {
"state": "alerting",
"title": "[Alerting] Test notification",
"ruleId": 0,
"message": "Someone is testing the alert notification within Grafana.",
"ruleUrl": "{{API_URL}}/",
"ruleName": "Test notification",
"evalMatches": [
{
"tags": null,
"value": 100,
"metric": "High value"
},
{
"tags": null,
"value": 200,
"metric": "Higher Value"
}
]
}
}
]
"count": 3,
"next": null,
"previous": null,
"results": [
{
"id": "AA74DN7T4JQB6",
"alert_group_id": "I68T24C13IFW1",
"created_at": "2020-05-11T20:07:43Z",
"payload": {
"state": "alerting",
"title": "[Alerting] Test notification",
"ruleId": 0,
"message": "Someone is testing the alert notification within Grafana.",
"ruleUrl": "{{API_URL}}/",
"ruleName": "Test notification",
"evalMatches": [
{
"tags": null,
"value": 100,
"metric": "High value"
},
{
"tags": null,
"value": 200,
"metric": "Higher Value"
}
]
}
},
{
"id": "AR9SSYFKE2PV7",
"alert_group_id": "I68T24C13IFW1",
"created_at": "2020-05-11T20:07:54Z",
"payload": {
"state": "alerting",
"title": "[Alerting] Test notification",
"ruleId": 0,
"message": "Someone is testing the alert notification within Grafana.",
"ruleUrl": "{{API_URL}}/",
"ruleName": "Test notification",
"evalMatches": [
{
"tags": null,
"value": 100,
"metric": "High value"
},
{
"tags": null,
"value": 200,
"metric": "Higher Value"
}
]
}
},
{
"id": "AWJQSGEYYUFGH",
"alert_group_id": "I68T24C13IFW1",
"created_at": "2020-05-11T20:07:58Z",
"payload": {
"state": "alerting",
"title": "[Alerting] Test notification",
"ruleId": 0,
"message": "Someone is testing the alert notification within Grafana.",
"ruleUrl": "{{API_URL}}/",
"ruleName": "Test notification",
"evalMatches": [
{
"tags": null,
"value": 100,
"metric": "High value"
},
{
"tags": null,
"value": 200,
"metric": "Higher Value"
}
]
}
}
]
}
```
The following available filter parameters should be provided as `GET` arguments:
* `alert_group_id`
* `search`—string-based inclusion search by alert payload
- `alert_group_id`
- `search`—string-based inclusion search by alert payload
**HTTP request**
`GET {{API_URL}}/api/v1/alerts/`
`GET {{API_URL}}/api/v1/alerts/`

View file

@ -1,8 +1,10 @@
+++
title = "Escalation Chains HTTP API"
aliases = ["/docs/grafana-cloud/oncall/oncall-api-reference/escalation_chains"]
weight = 200
+++
---
aliases:
- /docs/grafana-cloud/oncall/oncall-api-reference/escalation_chains/
- /docs/oncall/latest/oncall-api-reference/escalation_chains/
title: Escalation Chains HTTP API
weight: 200
---
# Create an escalation chain
@ -20,16 +22,16 @@ The above command returns JSON structured in the following way:
```json
{
"id": "FWDL7M6N6I9HE",
"name": "example-chain",
"team_id": null
"id": "FWDL7M6N6I9HE",
"name": "example-chain",
"team_id": null
}
```
| Parameter | Required | Description |
|-----------|:--------:|:------------|
| name | yes | Name of the escalation chain |
| team_id | no | ID of the team |
| Parameter | Required | Description |
| --------- | :------: | :--------------------------- |
| name | yes | Name of the escalation chain |
| team_id | no | ID of the team |
**HTTP request**
@ -48,9 +50,9 @@ The above command returns JSON structured in the following way:
```json
{
"id": "F5JU6KJET33FE",
"name": "default",
"team_id": null
"id": "F5JU6KJET33FE",
"name": "default",
"team_id": null
}
```
@ -64,23 +66,23 @@ The above command returns JSON structured in the following way:
curl "{{API_URL}}/api/v1/escalation_chains/" \
--request GET \
--header "Authorization: meowmeowmeow" \
--header "Content-Type: application/json"
--header "Content-Type: application/json"
```
The above command returns JSON structured in the following way:
```json
{
"count": 2,
"next": null,
"previous": null,
"results": [
{
"id": "F5JU6KJET33FE",
"name": "default",
"team_id": null
}
]
"count": 2,
"next": null,
"previous": null,
"results": [
{
"id": "F5JU6KJET33FE",
"name": "default",
"team_id": null
}
]
}
```
@ -99,4 +101,4 @@ curl "{{API_URL}}/api/v1/escalation_chains/F5JU6KJET33FE/" \
**HTTP request**
`DELETE {{API_URL}}/api/v1/escalation_chains/<ESCALATION_CHAIN_ID>/`
`DELETE {{API_URL}}/api/v1/escalation_chains/<ESCALATION_CHAIN_ID>/`

View file

@ -1,8 +1,10 @@
+++
title = "Escalation Policies HTTP API"
aliases = ["/docs/grafana-cloud/oncall/oncall-api-reference/escalation_policies"]
weight = 300
+++
---
aliases:
- /docs/grafana-cloud/oncall/oncall-api-reference/escalation_policies/
- /docs/oncall/latest/oncall-api-reference/escalation_policies/
title: Escalation Policies HTTP API
weight: 300
---
# Create an escalation policy
@ -22,28 +24,28 @@ The above command returns JSON structured in the following way:
```json
{
"id": "E3GA6SJETWWJS",
"escalation_chain_id": "F5JU6KJET33FE",
"position": 0,
"type": "wait",
"duration": 60
"id": "E3GA6SJETWWJS",
"escalation_chain_id": "F5JU6KJET33FE",
"position": 0,
"type": "wait",
"duration": 60
}
```
|Parameter | Required | Description |
|----------|:--------:|:------------|
`escalation_chain_id` | Yes | Each escalation policy is assigned to a specific escalation chain.
`position` | Optional | Escalation policies execute one after another starting from `position=0`. `Position=-1` will put the escalation policy to the end of the list. A new escalation policy created with a position of an existing escalation policy will move the old one (and all following) down in the list.
`type` | Yes | One of: `wait`, `notify_persons`, `notify_person_next_each_time`, `notify_on_call_from_schedule`, `notify_user_group`, `trigger_action`, `resolve`, `notify_whole_channel`, `notify_if_time_from_to`.
`duration` | Optional | The duration, in seconds, when type `wait` is chosen.
`important` | Optional | Default is `false`. Will assign "important" to personal notification rules if `true`. This can be used to distinguish alerts on which you want to be notified immediately by phone. Applicable for types `notify_persons`, `notify_on_call_from_schedule`, and `notify_user_group`.
`action_to_trigger` | If type = `trigger_action` | ID of an action, or webhook.
`group_to_notify` | If type = `notify_user_group` | ID of a `User Group`.
`persons_to_notify` | If type = `notify_persons` | List of user IDs.
`persons_to_notify_next_each_time` | If type = `notify_person_next_each_time` | List of user IDs.
`notify_on_call _from_schedule` | If type = `notify_on_call_from_schedule` | ID of a Schedule.
`notify_if_time_from` | If type = `notify_if_time_from_to` | UTC time represents the beginning of the time period, for example `09:00:00Z`.
`notify_if_time_to` | If type = `notify_if_time_from_to` | UTC time represents the end of the time period, for example `18:00:00Z`.
| Parameter | Required | Description |
| ---------------------------------- | :--------------------------------------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `escalation_chain_id` | Yes | Each escalation policy is assigned to a specific escalation chain. |
| `position` | Optional | Escalation policies execute one after another starting from `position=0`. `Position=-1` will put the escalation policy to the end of the list. A new escalation policy created with a position of an existing escalation policy will move the old one (and all following) down in the list. |
| `type` | Yes | One of: `wait`, `notify_persons`, `notify_person_next_each_time`, `notify_on_call_from_schedule`, `notify_user_group`, `trigger_action`, `resolve`, `notify_whole_channel`, `notify_if_time_from_to`. |
| `duration` | Optional | The duration, in seconds, when type `wait` is chosen. |
| `important` | Optional | Default is `false`. Will assign "important" to personal notification rules if `true`. This can be used to distinguish alerts on which you want to be notified immediately by phone. Applicable for types `notify_persons`, `notify_on_call_from_schedule`, and `notify_user_group`. |
| `action_to_trigger` | If type = `trigger_action` | ID of an action, or webhook. |
| `group_to_notify` | If type = `notify_user_group` | ID of a `User Group`. |
| `persons_to_notify` | If type = `notify_persons` | List of user IDs. |
| `persons_to_notify_next_each_time` | If type = `notify_person_next_each_time` | List of user IDs. |
| `notify_on_call _from_schedule` | If type = `notify_on_call_from_schedule` | ID of a Schedule. |
| `notify_if_time_from` | If type = `notify_if_time_from_to` | UTC time represents the beginning of the time period, for example `09:00:00Z`. |
| `notify_if_time_to` | If type = `notify_if_time_from_to` | UTC time represents the end of the time period, for example `18:00:00Z`. |
**HTTP request**
@ -62,11 +64,11 @@ The above command returns JSON structured in the following way:
```json
{
"id": "E3GA6SJETWWJS",
"escalation_chain_id": "F5JU6KJET33FE",
"position": 0,
"type": "wait",
"duration": 60
"id": "E3GA6SJETWWJS",
"escalation_chain_id": "F5JU6KJET33FE",
"position": 0,
"type": "wait",
"duration": 60
}
```
@ -80,40 +82,38 @@ The above command returns JSON structured in the following way:
curl "{{API_URL}}/api/v1/escalation_policies/" \
--request GET \
--header "Authorization: meowmeowmeow" \
--header "Content-Type: application/json"
--header "Content-Type: application/json"
```
The above command returns JSON structured in the following way:
```json
{
"count": 2,
"next": null,
"previous": null,
"results": [
{
"id": "E3GA6SJETWWJS",
"escalation_chain_id": "F5JU6KJET33FE",
"position": 0,
"type": "wait",
"duration": 60
},
{
"id": "E5JJTU52M5YM4",
"escalation_chain_id": "F5JU6KJET33FE",
"position": 1,
"type": "notify_person_next_each_time",
"persons_to_notify_next_each_time": [
"U4DNY931HHJS5"
]
}
]
"count": 2,
"next": null,
"previous": null,
"results": [
{
"id": "E3GA6SJETWWJS",
"escalation_chain_id": "F5JU6KJET33FE",
"position": 0,
"type": "wait",
"duration": 60
},
{
"id": "E5JJTU52M5YM4",
"escalation_chain_id": "F5JU6KJET33FE",
"position": 1,
"type": "notify_person_next_each_time",
"persons_to_notify_next_each_time": ["U4DNY931HHJS5"]
}
]
}
```
The following available filter parameter should be provided as a `GET` argument:
* `escalation_chain_id`
- `escalation_chain_id`
**HTTP request**
@ -130,4 +130,4 @@ curl "{{API_URL}}/api/v1/escalation_policies/E3GA6SJETWWJS/" \
**HTTP request**
`DELETE {{API_URL}}/api/v1/escalation_policies/<ESCALATION_POLICY_ID>/`
`DELETE {{API_URL}}/api/v1/escalation_policies/<ESCALATION_POLICY_ID>/`

View file

@ -1,8 +1,10 @@
+++
title = "Integrations HTTP API"
aliases = ["/docs/grafana-cloud/oncall/oncall-api-reference/integrations/"]
weight = 500
+++
---
aliases:
- /docs/grafana-cloud/oncall/oncall-api-reference/integrations/
- /docs/oncall/latest/oncall-api-reference/integrations/
title: Integrations HTTP API
weight: 500
---
# Create an integration
@ -20,52 +22,52 @@ The above command returns JSON structured in the following way:
```json
{
"id": "CFRPV98RPR1U8",
"name": "Grafana :blush:",
"team_id": null,
"link": "{{API_URL}}/integrations/v1/grafana/mReAoNwDm0eMwKo1mTeTwYo/",
"type": "grafana",
"default_route": {
"id": "RVBE4RKQSCGJ2",
"escalation_chain_id": "F5JU6KJET33FE",
"slack": {
"channel_id": "CH23212D"
}
},
"templates": {
"grouping_key": null,
"resolve_signal": null,
"slack": {
"title": null,
"message": null,
"image_url": null
},
"web": {
"title": null,
"message": null,
"image_url": null
},
"email": {
"title": null,
"message": null
},
"sms": {
"title": null
},
"phone_call": {
"title": null
},
"telegram": {
"title": null,
"message": null,
"image_url": null
}
"id": "CFRPV98RPR1U8",
"name": "Grafana :blush:",
"team_id": null,
"link": "{{API_URL}}/integrations/v1/grafana/mReAoNwDm0eMwKo1mTeTwYo/",
"type": "grafana",
"default_route": {
"id": "RVBE4RKQSCGJ2",
"escalation_chain_id": "F5JU6KJET33FE",
"slack": {
"channel_id": "CH23212D"
}
},
"templates": {
"grouping_key": null,
"resolve_signal": null,
"slack": {
"title": null,
"message": null,
"image_url": null
},
"web": {
"title": null,
"message": null,
"image_url": null
},
"email": {
"title": null,
"message": null
},
"sms": {
"title": null
},
"phone_call": {
"title": null
},
"telegram": {
"title": null,
"message": null,
"image_url": null
}
}
}
```
Integrations are sources of alerts and alert groups for Grafana OnCall.
For example, to learn how to integrate Grafana OnCall with Alertmanager see [Alertmanager]({{< relref "../integrations/add-alertmanager" >}}).
For example, to learn how to integrate Grafana OnCall with Alertmanager see [Alertmanager]({{< relref "../integrations/add-alertmanager" >}}).
**HTTP request**
@ -84,51 +86,51 @@ The above command returns JSON structured in the following way:
```json
{
"id": "CFRPV98RPR1U8",
"name": "Grafana :blush:",
"team_id": null,
"link": "{{API_URL}}/integrations/v1/grafana/mReAoNwDm0eMwKo1mTeTwYo/",
"type": "grafana",
"default_route": {
"id": "RVBE4RKQSCGJ2",
"escalation_chain_id": "F5JU6KJET33FE",
"slack": {
"channel_id": "CH23212D"
}
},
"templates": {
"grouping_key": null,
"resolve_signal": null,
"slack": {
"title": null,
"message": null,
"image_url": null
},
"web": {
"title": null,
"message": null,
"image_url": null
},
"email": {
"title": null,
"message": null
},
"sms": {
"title": null
},
"phone_call": {
"title": null
},
"telegram": {
"title": null,
"message": null,
"image_url": null
}
"id": "CFRPV98RPR1U8",
"name": "Grafana :blush:",
"team_id": null,
"link": "{{API_URL}}/integrations/v1/grafana/mReAoNwDm0eMwKo1mTeTwYo/",
"type": "grafana",
"default_route": {
"id": "RVBE4RKQSCGJ2",
"escalation_chain_id": "F5JU6KJET33FE",
"slack": {
"channel_id": "CH23212D"
}
},
"templates": {
"grouping_key": null,
"resolve_signal": null,
"slack": {
"title": null,
"message": null,
"image_url": null
},
"web": {
"title": null,
"message": null,
"image_url": null
},
"email": {
"title": null,
"message": null
},
"sms": {
"title": null
},
"phone_call": {
"title": null
},
"telegram": {
"title": null,
"message": null,
"image_url": null
}
}
}
```
This endpoint retrieves an integration. Integrations are sources of alerts and alert groups for Grafana OnCall.
This endpoint retrieves an integration. Integrations are sources of alerts and alert groups for Grafana OnCall.
**HTTP request**
@ -147,54 +149,54 @@ The above command returns JSON structured in the following way:
```json
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"id": "CFRPV98RPR1U8",
"name": "Grafana :blush:",
"team_id": null,
"link": "{{API_URL}}/integrations/v1/grafana/mReAoNwDm0eMwKo1mTeTwYo/",
"type": "grafana",
"default_route": {
"id": "RVBE4RKQSCGJ2",
"escalation_chain_id": "F5JU6KJET33FE",
"slack": {
"channel_id": "CH23212D"
}
},
"templates": {
"grouping_key": null,
"resolve_signal": null,
"slack": {
"title": null,
"message": null,
"image_url": null
},
"web": {
"title": null,
"message": null,
"image_url": null
},
"email": {
"title": null,
"message": null
},
"sms": {
"title": null
},
"phone_call": {
"title": null
},
"telegram": {
"title": null,
"message": null,
"image_url": null
}
}
"count": 1,
"next": null,
"previous": null,
"results": [
{
"id": "CFRPV98RPR1U8",
"name": "Grafana :blush:",
"team_id": null,
"link": "{{API_URL}}/integrations/v1/grafana/mReAoNwDm0eMwKo1mTeTwYo/",
"type": "grafana",
"default_route": {
"id": "RVBE4RKQSCGJ2",
"escalation_chain_id": "F5JU6KJET33FE",
"slack": {
"channel_id": "CH23212D"
}
]
},
"templates": {
"grouping_key": null,
"resolve_signal": null,
"slack": {
"title": null,
"message": null,
"image_url": null
},
"web": {
"title": null,
"message": null,
"image_url": null
},
"email": {
"title": null,
"message": null
},
"sms": {
"title": null
},
"phone_call": {
"title": null
},
"telegram": {
"title": null,
"message": null,
"image_url": null
}
}
}
]
}
```
@ -226,47 +228,47 @@ The above command returns JSON structured in the following way:
```json
{
"id": "CFRPV98RPR1U8",
"name": "Grafana :blush:",
"team_id": null,
"link": "{{API_URL}}/integrations/v1/grafana/mReAoNwDm0eMwKo1mTeTwYo/",
"type": "grafana",
"default_route": {
"id": "RVBE4RKQSCGJ2",
"escalation_chain_id": "F5JU6KJET33FE",
"slack": {
"channel_id": "CH23212D"
}
},
"templates": {
"grouping_key": null,
"resolve_signal": null,
"slack": {
"title": null,
"message": null,
"image_url": null
},
"web": {
"title": null,
"message": null,
"image_url": null
},
"email": {
"title": null,
"message": null
},
"sms": {
"title": null
},
"phone_call": {
"title": null
},
"telegram": {
"title": null,
"message": null,
"image_url": null
}
"id": "CFRPV98RPR1U8",
"name": "Grafana :blush:",
"team_id": null,
"link": "{{API_URL}}/integrations/v1/grafana/mReAoNwDm0eMwKo1mTeTwYo/",
"type": "grafana",
"default_route": {
"id": "RVBE4RKQSCGJ2",
"escalation_chain_id": "F5JU6KJET33FE",
"slack": {
"channel_id": "CH23212D"
}
},
"templates": {
"grouping_key": null,
"resolve_signal": null,
"slack": {
"title": null,
"message": null,
"image_url": null
},
"web": {
"title": null,
"message": null,
"image_url": null
},
"email": {
"title": null,
"message": null
},
"sms": {
"title": null
},
"phone_call": {
"title": null
},
"telegram": {
"title": null,
"message": null,
"image_url": null
}
}
}
```
@ -275,6 +277,7 @@ The above command returns JSON structured in the following way:
`PUT {{API_URL}}/api/v1/integrations/<INTEGRATION_ID>/`
# Delete integration
Deleted integrations will stop recording new alerts from monitoring. Integration removal won't trigger removal of related alert groups or alerts.
```shell

View file

@ -1,8 +1,10 @@
+++
title = "OnCall shifts HTTP API"
aliases = ["/docs/grafana-cloud/oncall/oncall-api-reference/on_call_shifts/"]
weight = 600
+++
---
aliases:
- /docs/grafana-cloud/oncall/oncall-api-reference/on_call_shifts/
- /docs/oncall/latest/oncall-api-reference/on_call_shifts/
title: OnCall shifts HTTP API
weight: 600
---
# Create an OnCall shift
@ -29,38 +31,36 @@ The above command returns JSON structured in the following way:
```json
{
"id": "OH3V5FYQEYJ6M",
"name": "Demo single event",
"type": "single_event",
"team_id": null,
"time_zone": null,
"level": 0,
"start": "2020-09-10T08:00:00",
"duration": 10800,
"users": [
"U4DNY931HHJS5"
]
"id": "OH3V5FYQEYJ6M",
"name": "Demo single event",
"type": "single_event",
"team_id": null,
"time_zone": null,
"level": 0,
"start": "2020-09-10T08:00:00",
"duration": 10800,
"users": ["U4DNY931HHJS5"]
}
```
| Parameter | Unique | Required | Description |
|-----------|:------:|:--------:|:------------|
`name` | Yes | Yes | On-call shift name.
`type` | No | Yes | One of: `single_event`, `recurrent_event`, `rolling_users`.
`team_id` | No | ID of the team.
`time_zone` | No | Optional | On-call shift time zone. Default is local schedule time zone. **This field will override the schedule time zone if changed**. For more information see [time zones](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones).
`level` | No | Optional | Priority level. The higher the value, the higher the priority. If two events overlap in one schedule, Grafana OnCall will choose the event with higher level. For example: Alex is on-call from 8AM till 11AM with level 1, Bob is on-call from 9AM till 11AM with level 2. At 10AM Grafana OnCall will notify Bob. At 8AM OnCall will notify Alex.
`start` | No | Yes | Start time of the on-call shift. This parameter takes a date format as `yyyy-MM-dd'T'HH:mm:ss` (for example "2020-09-05T08:00:00").
`duration` | No | Yes | Duration of the event.
`frequency` | No | If type = `recurrent_event` or `rolling_users` | One of: `daily`, `weekly`, `monthly`.
`interval` | No | Optional | This parameter takes a positive integer that represents the intervals that the recurrence rule repeats.
`week_start` | No | Optional | Start day of the week in iCal format. One of: `SU` (Sunday), `MO` (Monday), `TU` (Tuesday), `WE` (Wednesday), `TH` (Thursday), `FR` (Friday), `SA` (Saturday). Default: `SU`.
`by_day` | No | Optional | List of days in iCal format. Valid values are: `SU`, `MO`, `TU`, `WE`, `TH`, `FR`, `SA`.
`by_month` | No | Optional | List of months. Valid values are `1` to `12`.
`by_monthday` | No | Optional | List of days of the month. Valid values are `1` to `31` or `-31` to `-1`.
`users` | No | Optional | List of on-call users.
`rolling_users` | No | Optional | List of lists with on-call users (for `rolling_users` event type). Grafana OnCall will iterate over lists of users for every time frame specified in `frequency`. For example: there are two lists of users in `rolling_users` : [[Alex, Bob], [Alice]] and `frequency` = `daily` . This means that the first day Alex and Bob will be notified. The next day: Alice. The day after: Alex and Bob again and so on.
`start_rotation_from_user_index` | No | Optional | Index of the list of users in `rolling_users`, from which on-call rotation starts. By default, the start index is `0`
| Parameter | Unique | Required | Description |
| -------------------------------- | :----: | :--------------------------------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name` | Yes | Yes | On-call shift name. |
| `type` | No | Yes | One of: `single_event`, `recurrent_event`, `rolling_users`. |
| `team_id` | No | ID of the team. |
| `time_zone` | No | Optional | On-call shift time zone. Default is local schedule time zone. **This field will override the schedule time zone if changed**. For more information see [time zones](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). |
| `level` | No | Optional | Priority level. The higher the value, the higher the priority. If two events overlap in one schedule, Grafana OnCall will choose the event with higher level. For example: Alex is on-call from 8AM till 11AM with level 1, Bob is on-call from 9AM till 11AM with level 2. At 10AM Grafana OnCall will notify Bob. At 8AM OnCall will notify Alex. |
| `start` | No | Yes | Start time of the on-call shift. This parameter takes a date format as `yyyy-MM-dd'T'HH:mm:ss` (for example "2020-09-05T08:00:00"). |
| `duration` | No | Yes | Duration of the event. |
| `frequency` | No | If type = `recurrent_event` or `rolling_users` | One of: `daily`, `weekly`, `monthly`. |
| `interval` | No | Optional | This parameter takes a positive integer that represents the intervals that the recurrence rule repeats. |
| `week_start` | No | Optional | Start day of the week in iCal format. One of: `SU` (Sunday), `MO` (Monday), `TU` (Tuesday), `WE` (Wednesday), `TH` (Thursday), `FR` (Friday), `SA` (Saturday). Default: `SU`. |
| `by_day` | No | Optional | List of days in iCal format. Valid values are: `SU`, `MO`, `TU`, `WE`, `TH`, `FR`, `SA`. |
| `by_month` | No | Optional | List of months. Valid values are `1` to `12`. |
| `by_monthday` | No | Optional | List of days of the month. Valid values are `1` to `31` or `-31` to `-1`. |
| `users` | No | Optional | List of on-call users. |
| `rolling_users` | No | Optional | List of lists with on-call users (for `rolling_users` event type). Grafana OnCall will iterate over lists of users for every time frame specified in `frequency`. For example: there are two lists of users in `rolling_users` : [[Alex, Bob], [Alice]] and `frequency` = `daily` . This means that the first day Alex and Bob will be notified. The next day: Alice. The day after: Alex and Bob again and so on. |
| `start_rotation_from_user_index` | No | Optional | Index of the list of users in `rolling_users`, from which on-call rotation starts. By default, the start index is `0` |
Please see [RFC 5545](https://tools.ietf.org/html/rfc5545#section-3.3.10) for more information about recurrence rules.
@ -81,17 +81,15 @@ The above command returns JSON structured in the following way:
```json
{
"id": "OH3V5FYQEYJ6M",
"name": "Demo single event",
"type": "single_event",
"team_id": null,
"time_zone": null,
"level": 0,
"start": "2020-09-10T08:00:00",
"duration": 10800,
"users": [
"U4DNY931HHJS5"
]
"id": "OH3V5FYQEYJ6M",
"name": "Demo single event",
"type": "single_event",
"team_id": null,
"time_zone": null,
"level": 0,
"start": "2020-09-10T08:00:00",
"duration": 10800,
"users": ["U4DNY931HHJS5"]
}
```
@ -105,61 +103,53 @@ The above command returns JSON structured in the following way:
curl "{{API_URL}}/api/v1/on_call_shifts/" \
--request GET \
--header "Authorization: meowmeowmeow" \
--header "Content-Type: application/json"
--header "Content-Type: application/json"
```
The above command returns JSON structured in the following way:
```json
{
"count": 2,
"next": null,
"previous": null,
"results": [
{
"id": "OH3V5FYQEYJ6M",
"name": "Demo single event",
"type": "single_event",
"team_id": null,
"time_zone": null,
"level": 0,
"start": "2020-09-10T08:00:00",
"duration": 10800,
"users": [
"U4DNY931HHJS5"
]
},
{
"id": "O9WTH7CKM3KZW",
"name": "Demo recurrent event",
"type": "recurrent_event",
"team_id": null,
"time_zone": null,
"level": 0,
"start": "2020-09-10T16:00:00",
"duration": 10800,
"frequency": "weekly",
"interval": 2,
"week_start": "SU",
"by_day": [
"MO",
"WE",
"FR"
],
"by_month": null,
"by_monthday": null,
"users": [
"U4DNY931HHJS5"
]
}
]
"count": 2,
"next": null,
"previous": null,
"results": [
{
"id": "OH3V5FYQEYJ6M",
"name": "Demo single event",
"type": "single_event",
"team_id": null,
"time_zone": null,
"level": 0,
"start": "2020-09-10T08:00:00",
"duration": 10800,
"users": ["U4DNY931HHJS5"]
},
{
"id": "O9WTH7CKM3KZW",
"name": "Demo recurrent event",
"type": "recurrent_event",
"team_id": null,
"time_zone": null,
"level": 0,
"start": "2020-09-10T16:00:00",
"duration": 10800,
"frequency": "weekly",
"interval": 2,
"week_start": "SU",
"by_day": ["MO", "WE", "FR"],
"by_month": null,
"by_monthday": null,
"users": ["U4DNY931HHJS5"]
}
]
}
```
The following available filter parameters should be provided as `GET` arguments:
* `name` (Exact match)
* `schedule_id` (Exact match)
- `name` (Exact match)
- `schedule_id` (Exact match)
**HTTP request**
@ -188,17 +178,15 @@ The above command returns JSON structured in the following way:
```json
{
"id": "OH3V5FYQEYJ6M",
"name": "Demo single event",
"type": "single_event",
"team_id": null,
"time_zone": null,
"level": 0,
"start": "2020-09-10T08:00:00",
"duration": 10800,
"users": [
"U4DNY931HHJS5"
]
"id": "OH3V5FYQEYJ6M",
"name": "Demo single event",
"type": "single_event",
"team_id": null,
"time_zone": null,
"level": 0,
"start": "2020-09-10T08:00:00",
"duration": 10800,
"users": ["U4DNY931HHJS5"]
}
```
@ -217,4 +205,4 @@ curl "{{API_URL}}/api/v1/on_call_shifts/S3Z477AHDXTMF/" \
**HTTP request**
`DELETE {{API_URL}}/api/v1/on_call_shifts/<ON_CALL_SHIFT_ID>/`
`DELETE {{API_URL}}/api/v1/on_call_shifts/<ON_CALL_SHIFT_ID>/`

View file

@ -1,8 +1,10 @@
+++
title = "Outgoing webhooks HTTP API"
aliases = ["/docs/grafana-cloud/oncall/oncall-api-reference/outgoing_webhooks/"]
weight = 700
+++
---
aliases:
- /docs/grafana-cloud/oncall/oncall-api-reference/outgoing_webhooks/
- /docs/oncall/latest/oncall-api-reference/outgoing_webhooks/
title: Outgoing webhooks HTTP API
weight: 700
---
# Outgoing webhooks (actions)
@ -14,25 +16,25 @@ Used in escalation policies with type `trigger_action`.
curl "{{API_URL}}/api/v1/actions/" \
--request GET \
--header "Authorization: meowmeowmeow" \
--header "Content-Type: application/json"
--header "Content-Type: application/json"
```
The above command returns JSON structured in the following way:
```json
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"id": "KGEFG74LU1D8L",
"name": "Publish alert group notification to JIRA"
}
]
"count": 1,
"next": null,
"previous": null,
"results": [
{
"id": "KGEFG74LU1D8L",
"name": "Publish alert group notification to JIRA"
}
]
}
```
**HTTP request**
`GET {{API_URL}}/api/v1/actions/`
`GET {{API_URL}}/api/v1/actions/`

View file

@ -1,8 +1,10 @@
+++
title = "Personal Notification Rules HTTP API"
aliases = ["/docs/grafana-cloud/oncall/oncall-api-reference/personal_notification_rules/"]
weight = 800
+++
---
aliases:
- /docs/grafana-cloud/oncall/oncall-api-reference/personal_notification_rules/
- /docs/oncall/latest/oncall-api-reference/personal_notification_rules/
title: Personal Notification Rules HTTP API
weight: 800
---
# Post a personal notification rule
@ -21,21 +23,21 @@ The above command returns JSON structured in the following way:
```json
{
"id": "NT79GA9I7E4DJ",
"user_id": "U4DNY931HHJS5",
"position": 0,
"important": false,
"type": "notify_by_sms"
"id": "NT79GA9I7E4DJ",
"user_id": "U4DNY931HHJS5",
"position": 0,
"important": false,
"type": "notify_by_sms"
}
```
| Parameter | Required | Description |
|-----------|:--------:|:------------|
`user_id` | Yes | User ID
`position` | Optional | Personal notification rules execute one after another starting from `position=0`. `Position=-1` will put the escalation policy to the end of the list. A new escalation policy created with a position of an existing escalation policy will move the old one (and all following) down on the list.
`type` | Yes | One of: `wait`, `notify_by_slack`, `notify_by_sms`, `notify_by_phone_call`, `notify_by_telegram`, `notify_by_email`.
`duration` | Optional | A time in secs when type `wait` is chosen for `type`.
`important` | Optional | Boolean value indicates if a rule is "important". Default is `false`.
| Parameter | Required | Description |
| ----------- | :------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `user_id` | Yes | User ID |
| `position` | Optional | Personal notification rules execute one after another starting from `position=0`. `Position=-1` will put the escalation policy to the end of the list. A new escalation policy created with a position of an existing escalation policy will move the old one (and all following) down on the list. |
| `type` | Yes | One of: `wait`, `notify_by_slack`, `notify_by_sms`, `notify_by_phone_call`, `notify_by_telegram`, `notify_by_email`. |
| `duration` | Optional | A time in secs when type `wait` is chosen for `type`. |
| `important` | Optional | Boolean value indicates if a rule is "important". Default is `false`. |
**HTTP request**
@ -47,19 +49,19 @@ The above command returns JSON structured in the following way:
curl "{{API_URL}}/api/v1/personal_notification_rules/ND9EHN5LN1DUU/" \
--request GET \
--header "Authorization: meowmeowmeow" \
--header "Content-Type: application/json"
--header "Content-Type: application/json"
```
The above command returns JSON structured in the following way:
```json
{
"id": "ND9EHN5LN1DUU",
"user_id": "U4DNY931HHJS5",
"position": 1,
"duration": 300,
"important": false,
"type": "wait"
"id": "ND9EHN5LN1DUU",
"user_id": "U4DNY931HHJS5",
"position": 1,
"duration": 300,
"important": false,
"type": "wait"
}
```
@ -67,61 +69,60 @@ The above command returns JSON structured in the following way:
`GET {{API_URL}}/api/v1/personal_notification_rules/<PERSONAL_NOTIFICATION_RULE_ID>/`
# List personal notification rules
```shell
curl "{{API_URL}}/api/v1/personal_notification_rules/" \
--request GET \
--header "Authorization: meowmeowmeow" \
--header "Content-Type: application/json"
--header "Content-Type: application/json"
```
The above command returns JSON structured in the following ways:
```json
{
"count": 4,
"next": null,
"previous": null,
"results": [
{
"id": "NT79GA9I7E4DJ",
"user_id": "U4DNY931HHJS5",
"position": 0,
"important": false,
"type": "notify_by_sms"
},
{
"id": "ND9EHN5LN1DUU",
"user_id": "U4DNY931HHJS5",
"position": 1,
"duration": 300,
"important": false,
"type": "wait"
},
{
"id": "NEF49YQ1HNPDD",
"user_id": "U4DNY931HHJS5",
"position": 2,
"important": false,
"type": "notify_by_phone_call"
},
{
"id": "NWAL6WFJNWDD8",
"user_id": "U4DNY931HHJS5",
"position": 0,
"important": true,
"type": "notify_by_phone_call"
}
]
"count": 4,
"next": null,
"previous": null,
"results": [
{
"id": "NT79GA9I7E4DJ",
"user_id": "U4DNY931HHJS5",
"position": 0,
"important": false,
"type": "notify_by_sms"
},
{
"id": "ND9EHN5LN1DUU",
"user_id": "U4DNY931HHJS5",
"position": 1,
"duration": 300,
"important": false,
"type": "wait"
},
{
"id": "NEF49YQ1HNPDD",
"user_id": "U4DNY931HHJS5",
"position": 2,
"important": false,
"type": "notify_by_phone_call"
},
{
"id": "NWAL6WFJNWDD8",
"user_id": "U4DNY931HHJS5",
"position": 0,
"important": true,
"type": "notify_by_phone_call"
}
]
}
```
The following available filter parameters should be provided as `GET` arguments:
* `user_id`
* `important`
- `user_id`
- `important`
**HTTP Request**
@ -129,7 +130,6 @@ The following available filter parameters should be provided as `GET` arguments:
# Delete a personal notification rule
```shell
curl "{{API_URL}}/api/v1/personal_notification_rules/NWAL6WFJNWDD8/" \
--request DELETE \
@ -139,4 +139,4 @@ curl "{{API_URL}}/api/v1/personal_notification_rules/NWAL6WFJNWDD8/" \
**HTTP request**
`DELETE {{API_URL}}/api/v1/personal_notification_rules/<PERSONAL_NOTIFICATION_RULE_ID>/`
`DELETE {{API_URL}}/api/v1/personal_notification_rules/<PERSONAL_NOTIFICATION_RULE_ID>/`

View file

@ -1,9 +1,11 @@
+++
title = "Postmortem Messages HTTP API"
aliases = ["/docs/grafana-cloud/oncall/oncall-api-reference/postmortem_messages/"]
weight = 900
draft = true
+++
---
aliases:
- /docs/grafana-cloud/oncall/oncall-api-reference/postmortem_messages/
- /docs/oncall/latest/oncall-api-reference/postmortem_messages/
draft: true
title: Postmortem Messages HTTP API
weight: 900
---
# Create a postmortem message
@ -22,14 +24,14 @@ The above command returns JSON structured in the following way:
```json
{
"id": "M4BTQUS3PRHYQ",
"alert_group_id": "I68T24C13IFW1",
"author": "U4DNY931HHJS5",
"source": "web",
"created_at": "2020-06-19T12:40:01.429805Z",
"text": "Demo postmortem message"
"id": "M4BTQUS3PRHYQ",
"alert_group_id": "I68T24C13IFW1",
"author": "U4DNY931HHJS5",
"source": "web",
"created_at": "2020-06-19T12:40:01.429805Z",
"text": "Demo postmortem message"
}
```
```
**HTTP request**
@ -48,12 +50,12 @@ The above command returns JSON structured in the following way:
```json
{
"id": "M4BTQUS3PRHYQ",
"alert_group_id": "I68T24C13IFW1",
"author": "U4DNY931HHJS5",
"source": "web",
"created_at": "2020-06-19T12:40:01.429805Z",
"text": "Demo postmortem message"
"id": "M4BTQUS3PRHYQ",
"alert_group_id": "I68T24C13IFW1",
"author": "U4DNY931HHJS5",
"source": "web",
"created_at": "2020-06-19T12:40:01.429805Z",
"text": "Demo postmortem message"
}
```
@ -74,26 +76,25 @@ The above command returns JSON structured in the following way:
```json
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"id": "M4BTQUS3PRHYQ",
"alert_group_id": "I68T24C13IFW1",
"author": "U4DNY931HHJS5",
"source": "web",
"created_at": "2020-06-19T12:40:01.429805Z",
"text": "Demo postmortem message"
}
]
"count": 1,
"next": null,
"previous": null,
"results": [
{
"id": "M4BTQUS3PRHYQ",
"alert_group_id": "I68T24C13IFW1",
"author": "U4DNY931HHJS5",
"source": "web",
"created_at": "2020-06-19T12:40:01.429805Z",
"text": "Demo postmortem message"
}
]
}
```
The following available filter parameter should be provided as a `GET` argument:
* `alert_group_id`
- `alert_group_id`
**HTTP request**
@ -115,12 +116,12 @@ The above command returns JSON structured in the following way:
```json
{
"id": "M4BTQUS3PRHYQ",
"alert_group_id": "I68T24C13IFW1",
"author": "U4DNY931HHJS5",
"source": "web",
"created_at": "2020-06-19T12:40:01.429805Z",
"text": "Demo postmortem message"
"id": "M4BTQUS3PRHYQ",
"alert_group_id": "I68T24C13IFW1",
"author": "U4DNY931HHJS5",
"source": "web",
"created_at": "2020-06-19T12:40:01.429805Z",
"text": "Demo postmortem message"
}
```
@ -138,4 +139,4 @@ curl "{{API_URL}}/api/v1/postmortem_messages/M4BTQUS3PRHYQ/" \
**HTTP request**
`DELETE {{API_URL}}/api/v1/postmortem_messages/<POSTMORTEM_MESSAGE_ID>/`
`DELETE {{API_URL}}/api/v1/postmortem_messages/<POSTMORTEM_MESSAGE_ID>/`

View file

@ -1,9 +1,11 @@
+++
title = "Postmortem HTTP API"
aliases = ["/docs/grafana-cloud/oncall/oncall-api-reference/postmortems/"]
weight = 1000
draft = true
+++
---
aliases:
- /docs/grafana-cloud/oncall/oncall-api-reference/postmortems/
- /docs/oncall/latest/oncall-api-reference/postmortems/
draft: true
title: Postmortem HTTP API
weight: 1000
---
# Create a postmortem
@ -22,12 +24,12 @@ The above command returns JSON structured in the following way:
```json
{
"id": "P658FE5K87EWZ",
"alert_group_id": "I68T24C13IFW1",
"created_at": "2020-06-19T12:37:01.430444Z",
"text": "Demo postmortem text"
"id": "P658FE5K87EWZ",
"alert_group_id": "I68T24C13IFW1",
"created_at": "2020-06-19T12:37:01.430444Z",
"text": "Demo postmortem text"
}
```
```
**HTTP request**
@ -46,20 +48,20 @@ The above command returns JSON structured in the following way:
```json
{
"id": "P658FE5K87EWZ",
"alert_group_id": "I68T24C13IFW1",
"created_at": "2020-06-19T12:37:01.430444Z",
"text": "Demo postmortem text",
"postmortem_messages": [
{
"id": "M4BTQUS3PRHYQ",
"alert_group_id": "I68T24C13IFW1",
"author": "U4DNY931HHJS5",
"source": "web",
"created_at": "2020-06-19T12:40:01.429805Z",
"text": "Demo postmortem message"
}
]
"id": "P658FE5K87EWZ",
"alert_group_id": "I68T24C13IFW1",
"created_at": "2020-06-19T12:37:01.430444Z",
"text": "Demo postmortem text",
"postmortem_messages": [
{
"id": "M4BTQUS3PRHYQ",
"alert_group_id": "I68T24C13IFW1",
"author": "U4DNY931HHJS5",
"source": "web",
"created_at": "2020-06-19T12:40:01.429805Z",
"text": "Demo postmortem message"
}
]
}
```
@ -80,33 +82,33 @@ The above command returns JSON structured in the following way:
```json
{
"count": 1,
"next": null,
"previous": null,
"results": [
"count": 1,
"next": null,
"previous": null,
"results": [
{
"id": "P658FE5K87EWZ",
"alert_group_id": "I68T24C13IFW1",
"created_at": "2020-06-19T12:37:01.430444Z",
"text": "Demo postmortem text",
"postmortem_messages": [
{
"id": "P658FE5K87EWZ",
"alert_group_id": "I68T24C13IFW1",
"created_at": "2020-06-19T12:37:01.430444Z",
"text": "Demo postmortem text",
"postmortem_messages": [
{
"id": "M4BTQUS3PRHYQ",
"alert_group_id": "I68T24C13IFW1",
"author": "U4DNY931HHJS5",
"source": "web",
"created_at": "2020-06-19T12:40:01.429805Z",
"text": "Demo postmortem message"
}
]
"id": "M4BTQUS3PRHYQ",
"alert_group_id": "I68T24C13IFW1",
"author": "U4DNY931HHJS5",
"source": "web",
"created_at": "2020-06-19T12:40:01.429805Z",
"text": "Demo postmortem message"
}
]
]
}
]
}
```
The following available filter parameter should be provided with a `GET` argument:
* `alert_group_id`
- `alert_group_id`
**HTTP request**
@ -128,10 +130,10 @@ The above command returns JSON structured in the following way:
```json
{
"id": "P658FE5K87EWZ",
"alert_group_id": "I68T24C13IFW1",
"created_at": "2020-06-19T12:37:01.430444Z",
"text": "Demo postmortem text"
"id": "P658FE5K87EWZ",
"alert_group_id": "I68T24C13IFW1",
"created_at": "2020-06-19T12:37:01.430444Z",
"text": "Demo postmortem text"
}
```
@ -149,4 +151,4 @@ curl "{{API_URL}}/api/v1/postmortems/P658FE5K87EWZ/" \
**HTTP request**
`DELETE {{API_URL}}/api/v1/postmortems/<POSTMORTEM_ID>/`
`DELETE {{API_URL}}/api/v1/postmortems/<POSTMORTEM_ID>/`

View file

@ -1,8 +1,10 @@
+++
title = "Routes HTTP API"
aliases = ["/docs/grafana-cloud/oncall/oncall-api-reference/routes/"]
weight = 1100
+++
---
aliases:
- /docs/grafana-cloud/oncall/oncall-api-reference/routes/
- /docs/oncall/latest/oncall-api-reference/routes/
title: Routes HTTP API
weight: 1100
---
# Create a route
@ -26,31 +28,31 @@ The above command returns JSON structured in the following way:
```json
{
"id": "RIYGUJXCPFHXY",
"integration_id": "CFRPV98RPR1U8",
"escalation_chain_id": "F5JU6KJET33FE",
"routing_regex": "us-(east|west)",
"position": 0,
"is_the_last_route": false,
"slack": {
"channel_id": "CH23212D"
}
"id": "RIYGUJXCPFHXY",
"integration_id": "CFRPV98RPR1U8",
"escalation_chain_id": "F5JU6KJET33FE",
"routing_regex": "us-(east|west)",
"position": 0,
"is_the_last_route": false,
"slack": {
"channel_id": "CH23212D"
}
}
```
Routes allow you to direct different alerts to different messenger channels and escalation chains. Useful for:
* Important/non-important alerts
* Alerts for different engineering groups
* Snoozing spam & debugging alerts
- Important/non-important alerts
- Alerts for different engineering groups
- Snoozing spam & debugging alerts
| Parameter | Unique | Required | Description |
|-----------|:------:|:--------:|:------------|
`integration_id` | No | Yes | Each route is assigned to a specific integration.
`escalation_chain_id` | No | Yes | Each route is assigned a specific escalation chain.
`routing_regex` | Yes | Yes | Python Regex query (use https://regex101.com/ for debugging). OnCall chooses the route for an alert in case there is a match inside the whole alert payload.
`position` | Yes | Optional | Route matching is performed one after another starting from position=`0`. Position=`-1` will put the route to the end of the list before `is_the_last_route`. A new route created with a position of an existing route will move the old route (and all following routes) down in the list.
`slack` | Yes | Optional | Dictionary with Slack-specific settings for a route.
| Parameter | Unique | Required | Description |
| --------------------- | :----: | :------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `integration_id` | No | Yes | Each route is assigned to a specific integration. |
| `escalation_chain_id` | No | Yes | Each route is assigned a specific escalation chain. |
| `routing_regex` | Yes | Yes | Python Regex query (use https://regex101.com/ for debugging). OnCall chooses the route for an alert in case there is a match inside the whole alert payload. |
| `position` | Yes | Optional | Route matching is performed one after another starting from position=`0`. Position=`-1` will put the route to the end of the list before `is_the_last_route`. A new route created with a position of an existing route will move the old route (and all following routes) down in the list. |
| `slack` | Yes | Optional | Dictionary with Slack-specific settings for a route. |
**HTTP request**
@ -69,15 +71,15 @@ The above command returns JSON structured in the following way:
```json
{
"id": "RIYGUJXCPFHXY",
"integration_id": "CFRPV98RPR1U8",
"escalation_chain_id": "F5JU6KJET33FE",
"routing_regex": "us-(east|west)",
"position": 0,
"is_the_last_route": false,
"slack": {
"channel_id": "CH23212D"
}
"id": "RIYGUJXCPFHXY",
"integration_id": "CFRPV98RPR1U8",
"escalation_chain_id": "F5JU6KJET33FE",
"routing_regex": "us-(east|west)",
"position": 0,
"is_the_last_route": false,
"slack": {
"channel_id": "CH23212D"
}
}
```
@ -85,7 +87,6 @@ The above command returns JSON structured in the following way:
`GET {{API_URL}}/api/v1/routes/<ROUTE_ID>/`
# List routes
```shell
@ -99,40 +100,40 @@ The above command returns JSON structured in the following way:
```json
{
"count": 2,
"next": null,
"previous": null,
"results": [
{
"id": "RIYGUJXCPFHXY",
"integration_id": "CFRPV98RPR1U8",
"escalation_chain_id": "F5JU6KJET33FE",
"routing_regex": "us-(east|west)",
"position": 0,
"is_the_last_route": false,
"slack": {
"channel_id": "CH23212D"
}
},
{
"id": "RVBE4RKQSCGJ2",
"integration_id": "CFRPV98RPR1U8",
"escalation_chain_id": "F5JU6KJET33FE",
"routing_regex": ".*",
"position": 1,
"is_the_last_route": true,
"slack": {
"channel_id": "CH23212D"
}
}
]
"count": 2,
"next": null,
"previous": null,
"results": [
{
"id": "RIYGUJXCPFHXY",
"integration_id": "CFRPV98RPR1U8",
"escalation_chain_id": "F5JU6KJET33FE",
"routing_regex": "us-(east|west)",
"position": 0,
"is_the_last_route": false,
"slack": {
"channel_id": "CH23212D"
}
},
{
"id": "RVBE4RKQSCGJ2",
"integration_id": "CFRPV98RPR1U8",
"escalation_chain_id": "F5JU6KJET33FE",
"routing_regex": ".*",
"position": 1,
"is_the_last_route": true,
"slack": {
"channel_id": "CH23212D"
}
}
]
}
```
The following available filter parameters should be provided as `GET` arguments:
* `integration_id`
* `routing_regex` (Exact match)
- `integration_id`
- `routing_regex` (Exact match)
**HTTP request**
@ -158,15 +159,15 @@ The above command returns JSON structured in the following way:
```json
{
"id": "RIYGUJXCPFHXY",
"integration_id": "CFRPV98RPR1U8",
"escalation_chain_id": "F5JU6KJET33FE",
"routing_regex": "us-(east|west)",
"position": 0,
"is_the_last_route": false,
"slack": {
"channel_id": "CH23212D"
}
"id": "RIYGUJXCPFHXY",
"integration_id": "CFRPV98RPR1U8",
"escalation_chain_id": "F5JU6KJET33FE",
"routing_regex": "us-(east|west)",
"position": 0,
"is_the_last_route": false,
"slack": {
"channel_id": "CH23212D"
}
}
```
@ -185,4 +186,4 @@ curl "{{API_URL}}/api/v1/routes/RIYGUJXCPFHXY/" \
**HTTP request**
`DELETE {{API_URL}}/api/v1/routes/<ROUTE_ID>/`
`DELETE {{API_URL}}/api/v1/routes/<ROUTE_ID>/`

View file

@ -1,8 +1,10 @@
+++
title = "Schedule HTTP API"
aliases = ["/docs/grafana-cloud/oncall/oncall-api-reference/schedules/"]
weight = 1200
+++
---
aliases:
- /docs/grafana-cloud/oncall/oncall-api-reference/schedules/
- /docs/oncall/latest/oncall-api-reference/schedules/
title: Schedule HTTP API
weight: 1200
---
# Create a schedule
@ -25,32 +27,30 @@ The above command returns JSON structured in the following way:
```json
{
"id": "SBM7DV7BKFUYU",
"name": "Demo schedule iCal",
"type": "ical",
"team_id": null,
"ical_url_primary": "https://example.com/meow_calendar.ics",
"ical_url_overrides": "https://example.com/meow_calendar_overrides.ics",
"on_call_now": [
"U4DNY931HHJS5"
],
"slack": {
"channel_id": "MEOW_SLACK_ID",
"user_group_id": "MEOW_SLACK_ID"
}
"id": "SBM7DV7BKFUYU",
"name": "Demo schedule iCal",
"type": "ical",
"team_id": null,
"ical_url_primary": "https://example.com/meow_calendar.ics",
"ical_url_overrides": "https://example.com/meow_calendar_overrides.ics",
"on_call_now": ["U4DNY931HHJS5"],
"slack": {
"channel_id": "MEOW_SLACK_ID",
"user_group_id": "MEOW_SLACK_ID"
}
}
```
| Parameter | Unique | Required | Description |
|-----------|:------:|:--------:|:------------|
`name` | Yes | Yes | Schedule name.
`type` | No | Yes | Schedule type. May be `ical` (used for iCalendar integration) or `calendar` (used for manually created on-call shifts).
`team_id` | No | No | ID of the team.
`time_zone` | No | Optional | Schedule time zone. Is used for manually added on-call shifts in Schedules with type `calendar`. Default time zone is `UTC`. For more information about time zones, see [time zones](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones).
`ical_url_primary` | No | If type = `ical` | URL of external iCal calendar for schedule with type `ical`.
`ical_url_overrides` | No | Optional | URL of external iCal calendar for schedule with any type. Events from this calendar override events from primary calendar or from on-call shifts.
`slack` | No | Optional | Dictionary with Slack-specific settings for a schedule. Includes `channel_id` and `user_group_id` fields, that take a channel ID and a user group ID from Slack.
`shifts` | No | Optional | List of shifts. Used for manually added on-call shifts in Schedules with type `calendar`.
| Parameter | Unique | Required | Description |
| -------------------- | :----: | :--------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name` | Yes | Yes | Schedule name. |
| `type` | No | Yes | Schedule type. May be `ical` (used for iCalendar integration) or `calendar` (used for manually created on-call shifts). |
| `team_id` | No | No | ID of the team. |
| `time_zone` | No | Optional | Schedule time zone. Is used for manually added on-call shifts in Schedules with type `calendar`. Default time zone is `UTC`. For more information about time zones, see [time zones](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). |
| `ical_url_primary` | No | If type = `ical` | URL of external iCal calendar for schedule with type `ical`. |
| `ical_url_overrides` | No | Optional | URL of external iCal calendar for schedule with any type. Events from this calendar override events from primary calendar or from on-call shifts. |
| `slack` | No | Optional | Dictionary with Slack-specific settings for a schedule. Includes `channel_id` and `user_group_id` fields, that take a channel ID and a user group ID from Slack. |
| `shifts` | No | Optional | List of shifts. Used for manually added on-call shifts in Schedules with type `calendar`. |
**HTTP request**
@ -69,19 +69,17 @@ The above command returns JSON structured in the following way:
```json
{
"id": "SBM7DV7BKFUYU",
"name": "Demo schedule iCal",
"type": "ical",
"team_id": null,
"ical_url_primary": "https://example.com/meow_calendar.ics",
"ical_url_overrides": "https://example.com/meow_calendar_overrides.ics",
"on_call_now": [
"U4DNY931HHJS5"
],
"slack": {
"channel_id": "MEOW_SLACK_ID",
"user_group_id": "MEOW_SLACK_ID"
}
"id": "SBM7DV7BKFUYU",
"name": "Demo schedule iCal",
"type": "ical",
"team_id": null,
"ical_url_primary": "https://example.com/meow_calendar.ics",
"ical_url_overrides": "https://example.com/meow_calendar_overrides.ics",
"on_call_now": ["U4DNY931HHJS5"],
"slack": {
"channel_id": "MEOW_SLACK_ID",
"user_group_id": "MEOW_SLACK_ID"
}
}
```
@ -95,58 +93,51 @@ The above command returns JSON structured in the following way:
curl "{{API_URL}}/api/v1/schedules/" \
--request GET \
--header "Authorization: meowmeowmeow" \
--header "Content-Type: application/json"
--header "Content-Type: application/json"
```
The above command returns JSON structured in the following way:
```json
{
"count": 2,
"next": null,
"previous": null,
"results": [
{
"id": "SBM7DV7BKFUYU",
"name": "Demo schedule iCal",
"type": "ical",
"team_id": null,
"ical_url_primary": "https://example.com/meow_calendar.ics",
"ical_url_overrides": "https://example.com/meow_calendar_overrides.ics",
"on_call_now": [
"U4DNY931HHJS5"
],
"slack": {
"channel_id": "MEOW_SLACK_ID",
"user_group_id": "MEOW_SLACK_ID"
}
},
{
"id": "S3Z477AHDXTMF",
"name": "Demo schedule Calendar",
"type": "calendar",
"team_id": null,
"time_zone": "America/New_York",
"on_call_now": [
"U4DNY931HHJS5"
],
"shifts": [
"OH3V5FYQEYJ6M",
"O9WTH7CKM3KZW"
],
"ical_url_overrides": null,
"slack": {
"channel_id": "MEOW_SLACK_ID",
"user_group_id": "MEOW_SLACK_ID"
}
}
]
"count": 2,
"next": null,
"previous": null,
"results": [
{
"id": "SBM7DV7BKFUYU",
"name": "Demo schedule iCal",
"type": "ical",
"team_id": null,
"ical_url_primary": "https://example.com/meow_calendar.ics",
"ical_url_overrides": "https://example.com/meow_calendar_overrides.ics",
"on_call_now": ["U4DNY931HHJS5"],
"slack": {
"channel_id": "MEOW_SLACK_ID",
"user_group_id": "MEOW_SLACK_ID"
}
},
{
"id": "S3Z477AHDXTMF",
"name": "Demo schedule Calendar",
"type": "calendar",
"team_id": null,
"time_zone": "America/New_York",
"on_call_now": ["U4DNY931HHJS5"],
"shifts": ["OH3V5FYQEYJ6M", "O9WTH7CKM3KZW"],
"ical_url_overrides": null,
"slack": {
"channel_id": "MEOW_SLACK_ID",
"user_group_id": "MEOW_SLACK_ID"
}
}
]
}
```
The following available filter parameter should be provided as a `GET` argument:
* `name` (Exact match)
- `name` (Exact match)
**HTTP request**
@ -172,19 +163,17 @@ The above command returns JSON structured in the following way:
```json
{
"id": "SBM7DV7BKFUYU",
"name": "Demo schedule iCal",
"type": "ical",
"team_id": null,
"ical_url_primary": "https://example.com/meow_calendar.ics",
"ical_url_overrides": "https://example.com/meow_calendar_overrides.ics",
"on_call_now": [
"U4DNY931HHJS5"
],
"slack": {
"channel_id": "MEOW_SLACK_ID",
"user_group_id": "MEOW_SLACK_ID"
}
"id": "SBM7DV7BKFUYU",
"name": "Demo schedule iCal",
"type": "ical",
"team_id": null,
"ical_url_primary": "https://example.com/meow_calendar.ics",
"ical_url_overrides": "https://example.com/meow_calendar_overrides.ics",
"on_call_now": ["U4DNY931HHJS5"],
"slack": {
"channel_id": "MEOW_SLACK_ID",
"user_group_id": "MEOW_SLACK_ID"
}
}
```
@ -203,4 +192,4 @@ curl "{{API_URL}}/api/v1/schedules/SBM7DV7BKFUYU/" \
**HTTP request**
`DELETE {{API_URL}}/api/v1/schedules/<SCHEDULE_ID>/`
`DELETE {{API_URL}}/api/v1/schedules/<SCHEDULE_ID>/`

View file

@ -1,8 +1,10 @@
+++
title = "Slack Channels HTTP API"
aliases = ["/docs/grafana-cloud/oncall/oncall-api-reference/slack_channels/"]
weight = 1300
+++
---
aliases:
- /docs/grafana-cloud/oncall/oncall-api-reference/slack_channels/
- /docs/oncall/latest/oncall-api-reference/slack_channels/
title: Slack Channels HTTP API
weight: 1300
---
# List Slack Channels
@ -10,29 +12,29 @@ weight = 1300
curl "{{API_URL}}/api/v1/slack_channels/" \
--request GET \
--header "Authorization: meowmeowmeow" \
--header "Content-Type: application/json"
--header "Content-Type: application/json"
```
The above command returns JSON structured in the following way:
```json
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"name": "meow_channel",
"slack_id": "MEOW_SLACK_ID"
}
]
"count": 1,
"next": null,
"previous": null,
"results": [
{
"name": "meow_channel",
"slack_id": "MEOW_SLACK_ID"
}
]
}
```
The following available filter parameter should be provided as a `GET` argument:
* `channel_name`
- `channel_name`
**HTTP Request**
`GET {{API_URL}}/api/v1/slack_channels/`
`GET {{API_URL}}/api/v1/slack_channels/`

View file

@ -1,46 +1,49 @@
+++
title = "OnCall User Groups HTTP API"
aliases = ["/docs/grafana-cloud/oncall/oncall-api-reference/user_groups/"]
weight = 1400
+++
---
aliases:
- /docs/grafana-cloud/oncall/oncall-api-reference/user_groups/
- /docs/oncall/latest/oncall-api-reference/user_groups/
title: OnCall User Groups HTTP API
weight: 1400
---
<!--Used in escalation policies with type = `notify_user_group` and in schedules.-->
# List user groups
```shell
curl "{{API_URL}}/api/v1/user_groups/" \
--request GET \
--header "Authorization: meowmeowmeow" \
--header "Content-Type: application/json"
--header "Content-Type: application/json"
```
The above command returns JSON structured in the following way:
```json
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"id": "GPFAPH7J7BKJB",
"type": "slack_based",
"slack": {
"id": "MEOW_SLACK_ID",
"name": "Meow Group",
"handle": "meow_group"
}
}
]
"count": 1,
"next": null,
"previous": null,
"results": [
{
"id": "GPFAPH7J7BKJB",
"type": "slack_based",
"slack": {
"id": "MEOW_SLACK_ID",
"name": "Meow Group",
"handle": "meow_group"
}
}
]
}
```
| Parameter | Unique | Description |
|-----------|:------:|:------------|
`id` | Yes| User Group ID
`type` | No | [Slack-defined user groups](https://slack.com/intl/en-ru/help/articles/212906697-Create-a-user-group)
`slack` | No | Metadata retrieved from Slack.
| Parameter | Unique | Description |
| --------- | :----: | :---------------------------------------------------------------------------------------------------- |
| `id` | Yes | User Group ID |
| `type` | No | [Slack-defined user groups](https://slack.com/intl/en-ru/help/articles/212906697-Create-a-user-group) |
| `slack` | No | Metadata retrieved from Slack. |
**HTTP request**
`GET {{API_URL}}/api/v1/user_groups/`
`GET {{API_URL}}/api/v1/user_groups/`

View file

@ -1,35 +1,37 @@
+++
title = "Grafana OnCall Users HTTP API"
aliases = ["/docs/grafana-cloud/oncall/oncall-api-reference/users/"]
weight = 1500
+++
---
aliases:
- /docs/grafana-cloud/oncall/oncall-api-reference/users/
- /docs/oncall/latest/oncall-api-reference/users/
title: Grafana OnCall Users HTTP API
weight: 1500
---
# Get a user
This endpoint retrieves the user object.
```shell
````shell
```shell
curl "{{API_URL}}/api/v1/users/current/" \
--request GET \
--header "Authorization: meowmeowmeow" \
--header "Content-Type: application/json"
```
````
The above command returns JSON structured in the following way:
```json
{
"id": "U4DNY931HHJS5",
"email": "public-api-demo-user-1@grafana.com",
"slack": [
{
"user_id": "UALEXSLACKDJPK",
"team_id": "TALEXSLACKDJPK"
}
],
"username": "alex",
"role": "admin"
"id": "U4DNY931HHJS5",
"email": "public-api-demo-user-1@grafana.com",
"slack": [
{
"user_id": "UALEXSLACKDJPK",
"team_id": "TALEXSLACKDJPK"
}
],
"username": "alex",
"role": "admin"
}
```
@ -37,15 +39,15 @@ The above command returns JSON structured in the following way:
`GET {{API_URL}}/api/v1/users/<USER_ID>/`
Use `{{API_URL}}/api/v1/users/current` to retrieve the current user.
Use `{{API_URL}}/api/v1/users/current` to retrieve the current user.
| Parameter | Unique | Description |
|-----------|:------:|:------------|
`id` | Yes/org | User ID
`email` | Yes/org | User e-mail
`slack` | Yes/org | List of user IDs from connected Slack. User linking key is e-mail.
`username` | Yes/org | User username
`role` | No | One of: `user`, `observer`, `admin`.
| Parameter | Unique | Description |
| ---------- | :-----: | :----------------------------------------------------------------- |
| `id` | Yes/org | User ID |
| `email` | Yes/org | User e-mail |
| `slack` | Yes/org | List of user IDs from connected Slack. User linking key is e-mail. |
| `username` | Yes/org | User username |
| `role` | No | One of: `user`, `observer`, `admin`. |
# List Users
@ -60,23 +62,23 @@ The above command returns JSON structured in the following way:
```json
{
"count": 1,
"next": null,
"previous": null,
"results": [
"count": 1,
"next": null,
"previous": null,
"results": [
{
"id": "U4DNY931HHJS5",
"email": "public-api-demo-user-1@grafana.com",
"slack": [
{
"id": "U4DNY931HHJS5",
"email": "public-api-demo-user-1@grafana.com",
"slack": [
{
"user_id": "UALEXSLACKDJPK",
"team_id": "TALEXSLACKDJPK"
}
],
"username": "alex",
"role": "admin"
"user_id": "UALEXSLACKDJPK",
"team_id": "TALEXSLACKDJPK"
}
]
],
"username": "alex",
"role": "admin"
}
]
}
```
@ -84,8 +86,8 @@ This endpoint retrieves all users.
The following available filter parameter should be provided as a `GET` argument:
* `username` (Exact match)
- `username` (Exact match)
**HTTP request**
`GET {{API_URL}}/api/v1/users/`
`GET {{API_URL}}/api/v1/users/`

147
docs/sources/open-source.md Normal file
View file

@ -0,0 +1,147 @@
---
aliases:
- /docs/grafana-cloud/oncall/open-source/
- /docs/oncall/latest/open-source/
keywords:
- Open Source
title: Open Source
weight: 100
---
# Open Source
We prepared three environments for OSS users:
- **Hobby** environment for local usage & playing around: [README.md](https://github.com/grafana/oncall#getting-started).
- **Development** environment for contributors: [DEVELOPER.md](https://github.com/grafana/oncall/blob/dev/DEVELOPER.md)
- **Production** environment for reliable cloud installation using Helm: [Production Environment](#production-environment)
## Production Environment
TBD
## Slack Setup
Grafana OnCall Slack integration use a lot of Slack API features:
- Subscription on Slack events requires OnCall to be externally available and provide https endpoint.
- You will need to register new Slack App.
1. Make sure your OnCall is up and running.
2. You need OnCall to be accessible through https. For development purposes we suggest using [localtunnel](https://github.com/localtunnel/localtunnel). For production purposes please consider setting up proper web server with HTTPS termination. For localtunnel:
```bash
# Choose the unique prefix instead of pretty-turkey-83
# Localtunnel will generate an url, e.g. https://pretty-turkey-83.loca.lt
# it is referred as <ONCALL_ENGINE_PUBLIC_URL> below
lt --port 8000 -s pretty-turkey-83 --print-requests
```
3. If you use localtunnel, open your external URL and click "Continue" to allow requests to bypass the warning page.
4. [Create a Slack Workspace](https://slack.com/create) for development, or use your company workspace.
5. Go to https://api.slack.com/apps and click Create New App button
6. Select `From an app manifest` option and choose the right workspace
7. Copy and paste the following block with the correct <YOUR_BOT_NAME> and <ONCALL_ENGINE_PUBLIC_URL> fields
```yaml
_metadata:
major_version: 1
minor_version: 1
display_information:
name: <YOUR_BOT_NAME>
features:
app_home:
home_tab_enabled: true
messages_tab_enabled: true
messages_tab_read_only_enabled: false
bot_user:
display_name: <YOUR_BOT_NAME>
always_online: true
shortcuts:
- name: Create a new incident
type: message
callback_id: incident_create
description: Creates a new OnCall incident
- name: Add to postmortem
type: message
callback_id: add_postmortem
description: Add this message to postmortem
slash_commands:
- command: /oncall
url: <ONCALL_ENGINE_PUBLIC_URL>/slack/interactive_api_endpoint/
description: oncall
should_escape: false
oauth_config:
redirect_urls:
- <ONCALL_ENGINE_PUBLIC_URL>/api/internal/v1/complete/slack-install-free/
- <ONCALL_ENGINE_PUBLIC_URL>/api/internal/v1/complete/slack-login/
scopes:
user:
- channels:read
- chat:write
- identify
- users.profile:read
bot:
- app_mentions:read
- channels:history
- channels:read
- chat:write
- chat:write.customize
- chat:write.public
- commands
- files:write
- groups:history
- groups:read
- im:history
- im:read
- im:write
- mpim:history
- mpim:read
- mpim:write
- reactions:write
- team:read
- usergroups:read
- usergroups:write
- users.profile:read
- users:read
- users:read.email
- users:write
settings:
event_subscriptions:
request_url: <ONCALL_ENGINE_PUBLIC_URL>/slack/event_api_endpoint/
bot_events:
- app_home_opened
- app_mention
- channel_archive
- channel_created
- channel_deleted
- channel_rename
- channel_unarchive
- member_joined_channel
- message.channels
- message.im
- subteam_created
- subteam_members_changed
- subteam_updated
- user_change
interactivity:
is_enabled: true
request_url: <ONCALL_ENGINE_PUBLIC_URL>/slack/interactive_api_endpoint/
org_deploy_enabled: false
socket_mode_enabled: false
```
6. Go to your "OnCall" -> "Env Variables" and set:
```
SLACK_CLIENT_OAUTH_ID = Basic Information -> App Credentials -> Client ID
SLACK_CLIENT_OAUTH_SECRET = Basic Information -> App Credentials -> Client Secret
SLACK_SIGNING_SECRET = Basic Information -> App Credentials -> Signing Secret
SLACK_INSTALL_RETURN_REDIRECT_HOST = << OnCall external URL >>
```
7. Go to "OnCall" -> "ChatOps" -> "Slack" and install Slack Integration
8. All set!

View file

@ -113,20 +113,7 @@ class ChannelFilter(OrderedModel):
return satisfied_filter
def is_satisfying(self, raw_request_data, title, message=None):
AlertReceiveChannel = apps.get_model("alerts", "AlertReceiveChannel")
return (
self.is_default
or self.check_filter(json.dumps(raw_request_data))
or self.check_filter(str(title))
or
# Special case for Amazon SNS
(
self.check_filter(str(message))
if self.alert_receive_channel.integration == AlertReceiveChannel.INTEGRATION_AMAZON_SNS
else False
)
)
return self.is_default or self.check_filter(json.dumps(raw_request_data)) or self.check_filter(str(title))
def check_filter(self, value):
return re.search(self.filtering_term, value)

View file

@ -2,7 +2,7 @@ import pytest
from apps.alerts.incident_appearance.templaters import AlertSlackTemplater
from apps.alerts.models import AlertGroup
from apps.integrations.metadata.configuration import grafana
from config_integrations import grafana
@pytest.mark.django_db

View file

@ -10,9 +10,9 @@ from apps.alerts.incident_appearance.templaters import (
AlertWebTemplater,
)
from apps.alerts.models import Alert, AlertReceiveChannel
from apps.integrations.metadata.configuration import grafana
from common.jinja_templater import jinja_template_env
from common.utils import getattrd
from config_integrations import grafana
@pytest.mark.django_db

View file

@ -1,9 +1,12 @@
from django.conf import settings
from rest_framework import serializers
from apps.api.serializers.telegram import TelegramToUserConnectorSerializer
from apps.base.constants import ADMIN_PERMISSIONS, ALL_ROLES_PERMISSIONS, EDITOR_PERMISSIONS
from apps.base.messaging import get_messaging_backends
from apps.base.models import UserNotificationPolicy
from apps.base.utils import live_settings
from apps.oss_installation.utils import cloud_user_identity_status
from apps.twilioapp.utils import check_phone_number_is_valid
from apps.user_management.models import User
from common.api_helpers.custom_fields import TeamPrimaryKeyRelatedField
@ -30,6 +33,7 @@ class UserSerializer(DynamicFieldsModelSerializer, EagerLoadingMixin):
permissions = serializers.SerializerMethodField()
notification_chain_verbal = serializers.SerializerMethodField()
cloud_connection_status = serializers.SerializerMethodField()
SELECT_RELATED = ["telegram_verification_code", "telegram_connection", "organization", "slack_user_identity"]
@ -50,6 +54,7 @@ class UserSerializer(DynamicFieldsModelSerializer, EagerLoadingMixin):
"messaging_backends",
"permissions",
"notification_chain_verbal",
"cloud_connection_status",
]
read_only_fields = [
"email",
@ -88,6 +93,15 @@ class UserSerializer(DynamicFieldsModelSerializer, EagerLoadingMixin):
default, important = UserNotificationPolicy.get_short_verbals_for_user(user=obj)
return {"default": " - ".join(default), "important": " - ".join(important)}
def get_cloud_connection_status(self, obj):
if settings.OSS_INSTALLATION and live_settings.GRAFANA_CLOUD_NOTIFICATIONS_ENABLED:
connector = self.context.get("connector", None)
identities = self.context.get("cloud_identities", {})
identity = identities.get(obj.email, None)
status, _ = cloud_user_identity_status(connector, identity)
return status
return None
class UserHiddenFieldsSerializer(UserSerializer):
available_for_all_roles_fields = [

View file

@ -75,6 +75,7 @@ def test_update_user_cant_change_email_and_username(
"user": admin.username,
}
},
"cloud_connection_status": 0,
"permissions": ADMIN_PERMISSIONS,
"notification_chain_verbal": {"default": "", "important": ""},
"slack_user_identity": None,
@ -124,6 +125,7 @@ def test_list_users(
"notification_chain_verbal": {"default": "", "important": ""},
"slack_user_identity": None,
"avatar": admin.avatar_url,
"cloud_connection_status": 0,
},
{
"pk": editor.public_primary_key,
@ -144,6 +146,7 @@ def test_list_users(
"notification_chain_verbal": {"default": "", "important": ""},
"slack_user_identity": None,
"avatar": editor.avatar_url,
"cloud_connection_status": 0,
},
],
}

View file

@ -12,6 +12,7 @@ from apps.api.serializers.live_setting import LiveSettingSerializer
from apps.auth_token.auth import PluginAuthentication
from apps.base.models import LiveSetting
from apps.base.utils import live_settings
from apps.oss_installation.tasks import sync_users_with_cloud
from apps.slack.tasks import unpopulate_slack_user_identities
from apps.telegram.client import TelegramClient
from apps.telegram.tasks import register_telegram_webhook
@ -41,8 +42,10 @@ class LiveSettingViewSet(PublicPrimaryKeyMixin, viewsets.ModelViewSet):
def perform_update(self, serializer):
new_value = serializer.validated_data["value"]
self._update_hook(new_value)
super().perform_update(serializer)
instance = serializer.save()
sync_users = self.request.query_params.get("sync_users", "true") == "true"
if instance.name == "GRAFANA_CLOUD_ONCALL_TOKEN" and sync_users:
sync_users_with_cloud.apply_async()
def perform_destroy(self, instance):
new_value = instance.default_value

View file

@ -34,6 +34,7 @@ from apps.auth_token.models import UserScheduleExportAuthToken
from apps.auth_token.models.mobile_app_auth_token import MobileAppAuthToken
from apps.auth_token.models.mobile_app_verification_token import MobileAppVerificationToken
from apps.base.messaging import get_messaging_backend_from_id
from apps.base.utils import live_settings
from apps.telegram.client import TelegramClient
from apps.telegram.models import TelegramVerificationCode
from apps.twilioapp.phone_manager import PhoneManager
@ -56,7 +57,19 @@ class CurrentUserView(APIView):
permission_classes = (IsAuthenticated,)
def get(self, request):
serializer = UserSerializer(request.user, context={"request": self.request})
context = {"request": self.request, "format": self.format_kwarg, "view": self}
if settings.OSS_INSTALLATION and live_settings.GRAFANA_CLOUD_NOTIFICATIONS_ENABLED:
from apps.oss_installation.models import CloudConnector, CloudUserIdentity
connector = CloudConnector.objects.first()
if connector is not None:
cloud_identities = list(CloudUserIdentity.objects.filter(email__in=[request.user.email]))
cloud_identities = {cloud_identity.email: cloud_identity for cloud_identity in cloud_identities}
context["cloud_identities"] = cloud_identities
context["connector"] = connector
serializer = UserSerializer(request.user, context=context)
return Response(serializer.data)
def put(self, request):
@ -179,6 +192,46 @@ class UserView(
return queryset.order_by("id")
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
page = self.paginate_queryset(queryset)
if page is not None:
context = {"request": self.request, "format": self.format_kwarg, "view": self}
if settings.OSS_INSTALLATION:
if live_settings.GRAFANA_CLOUD_NOTIFICATIONS_ENABLED:
from apps.oss_installation.models import CloudConnector, CloudUserIdentity
connector = CloudConnector.objects.first()
if connector is not None:
emails = list(queryset.values_list("email", flat=True))
cloud_identities = list(CloudUserIdentity.objects.filter(email__in=emails))
cloud_identities = {cloud_identity.email: cloud_identity for cloud_identity in cloud_identities}
context["cloud_identities"] = cloud_identities
context["connector"] = connector
serializer = self.get_serializer(page, many=True, context=context)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
def retrieve(self, request, *args, **kwargs):
context = {"request": self.request, "format": self.format_kwarg, "view": self}
instance = self.get_object()
if settings.OSS_INSTALLATION and live_settings.GRAFANA_CLOUD_NOTIFICATIONS_ENABLED:
from apps.oss_installation.models import CloudConnector, CloudUserIdentity
connector = CloudConnector.objects.first()
if connector is not None:
cloud_identities = list(CloudUserIdentity.objects.filter(email__in=[instance.email]))
cloud_identities = {cloud_identity.email: cloud_identity for cloud_identity in cloud_identities}
context["cloud_identities"] = cloud_identities
context["connector"] = connector
serializer = self.get_serializer(instance, context=context)
return Response(serializer.data)
def current(self, request):
serializer = UserSerializer(self.get_queryset().get(pk=self.request.user.pk))
return Response(serializer.data)

View file

@ -41,6 +41,7 @@ class LiveSetting(models.Model):
"SLACK_CLIENT_OAUTH_ID",
"SLACK_CLIENT_OAUTH_SECRET",
"SLACK_SIGNING_SECRET",
"SLACK_INSTALL_RETURN_REDIRECT_HOST",
"SEND_ANONYMOUS_USAGE_STATS",
"GRAFANA_CLOUD_ONCALL_TOKEN",
"GRAFANA_CLOUD_ONCALL_HEARTBEAT_ENABLED",
@ -50,24 +51,31 @@ class LiveSetting(models.Model):
DESCRIPTIONS = {
"SLACK_SIGNING_SECRET": (
"Check <a href='"
"https://github.com/grafana/amixr/blob/main/DEVELOPER.md#slack-application-setup"
"'>this instruction</a> for details how to set up Slack. "
"https://grafana.com/docs/grafana-cloud/oncall/open-source/#slack-setup"
"'>instruction</a> for details how to set up Slack. "
"Slack secrets can't be verified on the backend, please try installing the Slack Bot "
"after you update Slack credentials."
"after you update them."
),
"SLACK_CLIENT_OAUTH_SECRET": (
"Check <a href='"
"https://github.com/grafana/amixr/blob/main/DEVELOPER.md#slack-application-setup"
"'>this instruction</a> for details how to set up Slack. "
"https://grafana.com/docs/grafana-cloud/oncall/open-source/#slack-setup"
"'>instruction</a> for details how to set up Slack. "
"Slack secrets can't be verified on the backend, please try installing the Slack Bot "
"after you update Slack credentials."
"after you update them."
),
"SLACK_CLIENT_OAUTH_ID": (
"Check <a href='"
"https://github.com/grafana/amixr/blob/main/DEVELOPER.md#slack-application-setup"
"'>this instruction</a> for details how to set up Slack. "
"https://grafana.com/docs/grafana-cloud/oncall/open-source/#slack-setup"
"'>instruction</a> for details how to set up Slack. "
"Slack secrets can't be verified on the backend, please try installing the Slack Bot "
"after you update Slack credentials."
"after you update them."
),
"SLACK_INSTALL_RETURN_REDIRECT_HOST": (
"Check <a href='"
"https://grafana.com/docs/grafana-cloud/oncall/open-source/#slack-setup"
"'>instruction</a> for details how to set up Slack. "
"Slack secrets can't be verified on the backend, please try installing the Slack Bot "
"after you update them."
),
"TWILIO_ACCOUNT_SID": (
"Twilio username to allow amixr send sms and make phone calls, "
@ -103,7 +111,7 @@ class LiveSetting(models.Model):
"SEND_ANONYMOUS_USAGE_STATS": (
"Grafana OnCall will send anonymous, but uniquely-identifiable usage analytics to Grafana Labs."
" These statistics are sent to https://stats.grafana.org/. For more information on what's sent, look at"
"https://github.com/..." # TODO: add url to usage stats code
" https://github.com/grafana/oncall/blob/dev/engine/apps/oss_installation/usage_stats.py#L29"
),
"GRAFANA_CLOUD_ONCALL_TOKEN": "Secret token for Grafana Cloud OnCall instance.",
"GRAFANA_CLOUD_ONCALL_HEARTBEAT_ENABLED": "Enable hearbeat integration with Grafana Cloud OnCall.",

View file

@ -1,99 +0,0 @@
# Main
enabled = True
title = "Amazon SNS"
slug = "amazon_sns"
short_description = None
is_displayed_on_web = True
description = None
is_featured = False
is_able_to_autoresolve = True
is_demo_alert_enabled = True
description = None
# Default templates
slack_title = """\
{% if payload|length == 0 -%}
{% set title = payload.get("AlarmName", "Alert") %}
{%- else -%}
{% set title = "Alert" %}
{%- endif %}
*<{{ grafana_oncall_link }}|#{{ grafana_oncall_incident_id }} {{ title }}>* via {{ integration_name }}
{% if source_link %}
(*<{{ source_link }}|source>*)
{%- endif %}"""
slack_message = """\
{% if payload|length == 1 and "message" in payload -%}
{{ payload.get("message", "Non-JSON payload received. Please make sure you publish monitoring Alarms to SNS, not logs: https://docs.amixr.io/#/integrations/amazon_sns") }}
{%- else -%}
*State* {{ payload.get("NewStateValue", "NO") }}
Region: {{ payload.get("Region", "Undefined") }}
_Description_: {{ payload.get("AlarmDescription", "Undefined") }}
{%- endif %}
"""
slack_image_url = None
web_title = """\
{% if payload|length == 0 -%}
{{ payload.get("AlarmName", "Alert")}}
{%- else -%}
Alert
{%- endif %}"""
web_message = """\
{% if payload|length == 1 and "message" in payload -%}
{{ payload.get("message", "Non-JSON payload received. Please make sure you publish monitoring Alarms to SNS, not logs: https://docs.amixr.io/#/integrations/amazon_sns") }}
{%- else -%}
**State** {{ payload.get("NewStateValue", "NO") }}
Region: {{ payload.get("Region", "Undefined") }}
*Description*: {{ payload.get("AlarmDescription", "Undefined") }}
{%- endif %}
"""
web_image_url = slack_image_url
sms_title = web_title
phone_call_title = web_title
email_title = web_title
email_message = "{{ payload|tojson_pretty }}"
telegram_title = sms_title
telegram_message = """\
{% if payload|length == 1 and "message" in payload -%}
{{ payload.get("message", "Non-JSON payload received. Please make sure you publish monitoring Alarms to SNS, not logs: https://docs.amixr.io/#/integrations/amazon_sns") }}
{%- else -%}
<b>State</b> {{ payload.get("NewStateValue", "NO") }}
Region: {{ payload.get("Region", "Undefined") }}
<i>Description</i>: {{ payload.get("AlarmDescription", "Undefined") }}
{%- endif %}
"""
telegram_image_url = slack_image_url
source_link = """\
{% if payload|length == 0 -%}
{% if payload.get("Trigger", {}).get("Namespace") == "AWS/ElasticBeanstalk" -%}
https://console.aws.amazon.com/elasticbeanstalk/home?region={{ payload.get("TopicArn").split(":")[3] }}
{%- else -%}
https://console.aws.amazon.com/cloudwatch//home?region={{ payload.get("TopicArn").split(":")[3] }}
{%- endif %}
{%- endif %}"""
grouping_id = web_title
resolve_condition = """\
{{ payload.get("NewStateValue", "") == "OK" }}
"""
acknowledge_condition = None
group_verbose_name = web_title
example_payload = {"foo": "bar"}

View file

@ -0,0 +1,110 @@
import logging
import random
from urllib.parse import urljoin
import requests
from django.apps import apps
from django.conf import settings
from rest_framework import status
from apps.base.utils import live_settings
logger = logging.getLogger(__name__)
def setup_heartbeat_integration(name=None):
"""Setup Grafana Cloud OnCall heartbeat integration."""
CloudHeartbeat = apps.get_model("oss_installation", "CloudHeartbeat")
cloud_heartbeat = None
api_token = live_settings.GRAFANA_CLOUD_ONCALL_TOKEN
if not live_settings.GRAFANA_CLOUD_ONCALL_HEARTBEAT_ENABLED or not api_token:
return cloud_heartbeat
# don't specify a team in the data, so heartbeat integration will be created in the General.
name = name or f"OnCall Cloud Heartbeat {settings.BASE_URL}"
data = {"type": "formatted_webhook", "name": name}
url = urljoin(settings.GRAFANA_CLOUD_ONCALL_API_URL, "/api/v1/integrations/")
try:
headers = {"Authorization": api_token}
r = requests.post(url=url, data=data, headers=headers, timeout=5)
if r.status_code == status.HTTP_201_CREATED:
response_data = r.json()
cloud_heartbeat, _ = CloudHeartbeat.objects.update_or_create(
defaults={"integration_id": response_data["id"], "integration_url": response_data["heartbeat"]["link"]}
)
if r.status_code == status.HTTP_400_BAD_REQUEST:
response_data = r.json()
error = response_data["detail"]
if error == "Integration with this name already exists":
response = requests.get(url=f"{url}?name={name}", headers=headers)
integrations = response.json().get("results", [])
if len(integrations) == 1:
integration = integrations[0]
cloud_heartbeat, updated = CloudHeartbeat.objects.update_or_create(
defaults={
"integration_id": integration["id"],
"integration_url": integration["heartbeat"]["link"],
}
)
else:
setup_heartbeat_integration(f"{name}{ random.randint(1, 1024)}")
except requests.Timeout:
logger.warning("Unable to create cloud heartbeat integration. Request timeout.")
except requests.exceptions.RequestException as e:
logger.warning(f"Unable to create cloud heartbeat integration. Request exception {str(e)}.")
return cloud_heartbeat
def send_cloud_heartbeat():
CloudHeartbeat = apps.get_model("oss_installation", "CloudHeartbeat")
CloudConnector = apps.get_model("oss_installation", "CloudConnector")
"""Send heartbeat to Grafana Cloud OnCall integration."""
if not live_settings.GRAFANA_CLOUD_ONCALL_HEARTBEAT_ENABLED or not live_settings.GRAFANA_CLOUD_ONCALL_TOKEN:
logger.info(
"Unable to send cloud heartbeat. Check values for GRAFANA_CLOUD_ONCALL_HEARTBEAT_ENABLED and GRAFANA_CLOUD_ONCALL_TOKEN."
)
return
connector = CloudConnector.objects.first()
if connector is None:
logger.info("Unable to send cloud heartbeat. Cloud is not connected")
return
logger.info("Start send cloud heartbeat")
try:
cloud_heartbeat = CloudHeartbeat.objects.get()
except CloudHeartbeat.DoesNotExist:
cloud_heartbeat = setup_heartbeat_integration()
if cloud_heartbeat is None:
logger.warning("Unable to setup cloud heartbeat integration.")
return
cloud_heartbeat.success = False
try:
response = requests.get(cloud_heartbeat.integration_url, timeout=5)
logger.info(f"Send cloud heartbeat with response {response.status_code}")
except requests.Timeout:
logger.warning("Unable to send cloud heartbeat. Request timeout.")
except requests.exceptions.RequestException as e:
logger.warning(f"Unable to send cloud heartbeat. Request exception {str(e)}.")
else:
if response.status_code == status.HTTP_200_OK:
cloud_heartbeat.success = True
logger.info("Successfully send cloud heartbeat")
elif response.status_code == status.HTTP_403_FORBIDDEN:
# check for 403 because AlertChannelDefiningMixin returns 403 if no integration was found.
logger.info("Failed to send cloud heartbeat. Integration was not created yet")
# force re-creation on next run
cloud_heartbeat.delete()
else:
logger.info(f"Failed to send cloud heartbeat. response {response.status_code}")
# save result of cloud heartbeat if it wasn't deleted
if cloud_heartbeat.pk is not None:
cloud_heartbeat.save()
logger.info("Finish send cloud heartbeat")
def get_heartbeat_link(connector, heartbeat):
if connector is None:
return None
if heartbeat is None:
return None
return urljoin(connector.cloud_url, f"a/grafana-oncall-app/?page=integrations1&id={heartbeat.integration_id}")

View file

@ -1,9 +1,7 @@
from urllib.parse import urljoin
from rest_framework import serializers
import apps.oss_installation.constants as cloud_constants
from apps.oss_installation.models import CloudConnector, CloudUserIdentity
from apps.oss_installation.utils import cloud_user_identity_status
from apps.user_management.models import User
@ -15,23 +13,8 @@ class CloudUserSerializer(serializers.ModelSerializer):
fields = ["cloud_data"]
def get_cloud_data(self, obj):
link = None
status = cloud_constants.CLOUD_NOT_SYNCED
connector = CloudConnector.objects.filter().first()
if connector is not None:
cloud_user_identity = CloudUserIdentity.objects.filter(email=obj.email).first()
if cloud_user_identity is None:
status = cloud_constants.CLOUD_SYNCED_USER_NOT_FOUND
link = connector.cloud_url
elif not cloud_user_identity.phone_number_verified:
status = cloud_constants.CLOUD_SYNCED_PHONE_NOT_VERIFIED
link = urljoin(
connector.cloud_url, f"a/grafana-oncall-app/?page=users&p=1&id={cloud_user_identity.cloud_id}"
)
else:
status = cloud_constants.CLOUD_SYNCED_PHONE_VERIFIED
link = urljoin(
connector.cloud_url, f"a/grafana-oncall-app/?page=users&p=1&id={cloud_user_identity.cloud_id}"
)
cloud_user_identity = CloudUserIdentity.objects.filter(email=obj.email).first()
status, link = cloud_user_identity_status(connector, cloud_user_identity)
cloud_data = {"status": status, "link": link}
return cloud_data

View file

@ -1,13 +1,9 @@
from urllib.parse import urljoin
import requests
from celery.utils.log import get_task_logger
from django.conf import settings
from django.apps import apps
from django.utils import timezone
from rest_framework import status
from apps.base.utils import live_settings
from apps.oss_installation.models import CloudConnector, CloudHeartbeat, OssInstallation
from apps.oss_installation.cloud_heartbeat import send_cloud_heartbeat
from apps.oss_installation.usage_stats import UsageStatsService
from common.custom_celery_tasks import shared_dedicated_queue_retry_task
@ -17,6 +13,8 @@ logger = get_task_logger(__name__)
@shared_dedicated_queue_retry_task()
def send_usage_stats_report():
logger.info("Start send_usage_stats_report")
OssInstallation = apps.get_model("oss_installation", "OssInstallation")
installation = OssInstallation.objects.get_or_create()[0]
enabled = live_settings.SEND_ANONYMOUS_USAGE_STATS
if enabled:
@ -30,80 +28,24 @@ def send_usage_stats_report():
logger.info("Finish send_usage_stats_report")
def _setup_heartbeat_integration():
"""Setup Grafana Cloud OnCall heartbeat integration."""
cloud_heartbeat = None
api_token = live_settings.GRAFANA_CLOUD_ONCALL_TOKEN
# don't specify a team in the data, so heartbeat integration will be created in the General.
data = {"type": "formatted_webhook", "name": f"OnCall {settings.BASE_URL}"}
url = urljoin(settings.GRAFANA_CLOUD_ONCALL_API_URL, "/api/v1/integrations/")
try:
headers = {"Authorization": api_token}
r = requests.post(url=url, data=data, headers=headers, timeout=5)
if r.status_code == status.HTTP_201_CREATED:
response_data = r.json()
cloud_heartbeat, _ = CloudHeartbeat.objects.update_or_create(
defaults={"integration_id": response_data["id"], "integration_url": response_data["heartbeat"]["link"]}
)
except requests.Timeout:
logger.warning("Unable to create cloud heartbeat integration. Request timeout.")
except requests.exceptions.RequestException as e:
logger.warning(f"Unable to create cloud heartbeat integration. Request exception {str(e)}.")
return cloud_heartbeat
@shared_dedicated_queue_retry_task()
def send_cloud_heartbeat():
"""Send heartbeat to Grafana Cloud OnCall integration."""
if not live_settings.GRAFANA_CLOUD_ONCALL_HEARTBEAT_ENABLED or not live_settings.GRAFANA_CLOUD_ONCALL_TOKEN:
logger.info(
"Unable to send cloud heartbeat. Check values for GRAFANA_CLOUD_ONCALL_HEARTBEAT_ENABLED and GRAFANA_CLOUD_ONCALL_TOKEN."
)
return
logger.info("Start send cloud heartbeat")
try:
cloud_heartbeat = CloudHeartbeat.objects.get()
except CloudHeartbeat.DoesNotExist:
cloud_heartbeat = _setup_heartbeat_integration()
if cloud_heartbeat is None:
logger.warning("Unable to setup cloud heartbeat integration.")
return
cloud_heartbeat.success = False
try:
response = requests.get(cloud_heartbeat.integration_url, timeout=5)
logger.info(f"Send cloud heartbeat with response {response.status_code}")
except requests.Timeout:
logger.warning("Unable to send cloud heartbeat. Request timeout.")
except requests.exceptions.RequestException as e:
logger.warning(f"Unable to send cloud heartbeat. Request exception {str(e)}.")
else:
if response.status_code == status.HTTP_200_OK:
cloud_heartbeat.success = True
logger.info("Successfully send cloud heartbeat")
elif response.status_code == status.HTTP_403_FORBIDDEN:
# check for 403 because AlertChannelDefiningMixin returns 403 if no integration was found.
logger.info("Failed to send cloud heartbeat. Integration was not created yet")
# force re-creation on next run
cloud_heartbeat.delete()
else:
logger.info(f"Failed to send cloud heartbeat. response {response.status_code}")
# save result of cloud heartbeat if it wasn't deleted
if cloud_heartbeat.pk is not None:
cloud_heartbeat.save()
logger.info("Finish send cloud heartbeat")
def send_cloud_heartbeat_task():
send_cloud_heartbeat()
@shared_dedicated_queue_retry_task()
def sync_users_with_cloud():
CloudConnector = apps.get_model("oss_installation", "CloudConnector")
logger.info("Start sync_users_with_cloud")
connector = CloudConnector.objects.first()
if connector is not None:
status, error = connector.sync_users_with_cloud()
log_message = "Users synced. Status {status}."
if error:
log_message += f" Error {error}"
logger.info(log_message)
if live_settings.GRAFANA_CLOUD_NOTIFICATIONS_ENABLED:
connector = CloudConnector.objects.first()
if connector is not None:
status, error = connector.sync_users_with_cloud()
log_message = "Users synced. Status {status}."
if error:
log_message += f" Error {error}"
logger.info(log_message)
else:
logger.info("Grafana Cloud is not connected")
else:
logger.info("Grafana Cloud is not connected")
logger.info("GRAFANA_CLOUD_NOTIFICATIONS_ENABLED is not enabled")

View file

@ -2,7 +2,7 @@ from django.urls import include, path
from common.api_helpers.optional_slash_router import OptionalSlashRouter, optional_slash_path
from .views import CloudConnectionView, CloudUsersView, CloudUserView
from .views import CloudConnectionView, CloudHeartbeatView, CloudUsersView, CloudUserView
router = OptionalSlashRouter()
router.register("cloud_users", CloudUserView, basename="cloud-users")
@ -11,4 +11,5 @@ urlpatterns = [
path("", include(router.urls)),
optional_slash_path("cloud_users", CloudUsersView.as_view(), name="cloud-users-list"),
optional_slash_path("cloud_connection", CloudConnectionView.as_view(), name="cloud-connection-status"),
optional_slash_path("cloud_heartbeat", CloudHeartbeatView.as_view(), name="cloud-heartbeat"),
]

View file

@ -3,11 +3,11 @@ import platform
from dataclasses import asdict, dataclass
import requests
from django.apps import apps
from django.conf import settings
from django.db.models import Sum
from apps.alerts.models import AlertGroupCounter
from apps.oss_installation.models import OssInstallation
from apps.oss_installation.utils import active_oss_users_count
USAGE_STATS_URL = "https://stats.grafana.org/oncall-usage-report"
@ -27,9 +27,12 @@ class UsageStatsReport:
class UsageStatsService:
def get_usage_stats_report(self):
OssInstallation = apps.get_model("oss_installation", "OssInstallation")
metrics = {}
metrics["active_users_count"] = active_oss_users_count()
total_alert_groups = AlertGroupCounter.objects.aggregate(Sum("value")).get("value__sum", 0)
total_alert_groups = AlertGroupCounter.objects.aggregate(Sum("value")).get("value__sum", None)
if total_alert_groups is None:
total_alert_groups = 0
metrics["alert_groups_count"] = total_alert_groups
usage_stats_id = OssInstallation.objects.get_or_create()[0].installation_id

View file

@ -1,8 +1,10 @@
import logging
from urllib.parse import urljoin
from django.apps import apps
from django.utils import timezone
from apps.oss_installation import constants as oss_constants
from apps.schedules.ical_utils import list_users_to_notify_from_ical_for_period
logger = logging.getLogger(__name__)
@ -65,3 +67,20 @@ def active_oss_users_count():
unique_active_users.add(user.pk)
return len(unique_active_users)
def cloud_user_identity_status(connector, identity):
link = None
if connector is None:
status = oss_constants.CLOUD_NOT_SYNCED
elif identity is None:
status = oss_constants.CLOUD_SYNCED_USER_NOT_FOUND
link = connector.cloud_url
else:
if identity.phone_number_verified:
status = oss_constants.CLOUD_SYNCED_PHONE_VERIFIED
else:
status = oss_constants.CLOUD_SYNCED_PHONE_NOT_VERIFIED
link = urljoin(connector.cloud_url, f"a/grafana-oncall-app/?page=users&p=1&id={identity.cloud_id}")
return status, link

View file

@ -1,2 +1,3 @@
from .cloud_connection import CloudConnectionView # noqa: F401
from .cloud_heartbeat import CloudHeartbeatView # noqa: F401
from .cloud_users import CloudUsersView, CloudUserView # noqa: F401

View file

@ -1,5 +1,3 @@
from urllib.parse import urljoin
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
@ -7,7 +5,9 @@ from rest_framework.views import APIView
from apps.api.permissions import IsAdmin
from apps.auth_token.auth import PluginAuthentication
from apps.base.models import LiveSetting
from apps.base.utils import live_settings
from apps.oss_installation.cloud_heartbeat import get_heartbeat_link
from apps.oss_installation.models import CloudConnector, CloudHeartbeat
@ -22,19 +22,16 @@ class CloudConnectionView(APIView):
"cloud_connection_status": connector is not None,
"cloud_notifications_enabled": live_settings.GRAFANA_CLOUD_NOTIFICATIONS_ENABLED,
"cloud_heartbeat_enabled": live_settings.GRAFANA_CLOUD_ONCALL_HEARTBEAT_ENABLED,
"cloud_heartbeat_link": self._get_heartbeat_link(connector, heartbeat),
"cloud_heartbeat_link": get_heartbeat_link(connector, heartbeat),
"cloud_heartbeat_status": heartbeat is not None and heartbeat.success,
}
return Response(response)
def _get_heartbeat_link(self, connector, heartbeat):
if connector is None:
return None
if heartbeat is None:
return None
return urljoin(connector.cloud_url, f"a/grafana-oncall-app/?page=integrations1&id={heartbeat.integration_id}")
def delete(self, request):
s = LiveSetting.objects.filter(name="GRAFANA_CLOUD_ONCALL_TOKEN").first()
if s is not None:
s.value = None
s.save()
connector = CloudConnector.objects.first()
if connector is None:
return Response(status=status.HTTP_404_NOT_FOUND)

View file

@ -0,0 +1,27 @@
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from apps.api.permissions import IsAdmin
from apps.auth_token.auth import PluginAuthentication
from apps.oss_installation.cloud_heartbeat import get_heartbeat_link, setup_heartbeat_integration
from apps.oss_installation.models import CloudConnector, CloudHeartbeat
class CloudHeartbeatView(APIView):
authentication_classes = (PluginAuthentication,)
permission_classes = (IsAuthenticated, IsAdmin)
def post(self, request):
connector = CloudConnector.objects.first()
if connector is not None:
try:
CloudHeartbeat.objects.get()
return Response(status=status.HTTP_400_BAD_REQUEST, data={"detail": "Cloud heartbeat already exists"})
except CloudHeartbeat.DoesNotExist:
heartbeat = setup_heartbeat_integration()
link = get_heartbeat_link(connector, heartbeat)
return Response(status=status.HTTP_200_OK, data={"link": link})
else:
return Response(status=status.HTTP_400_BAD_REQUEST, data={"detail": "Grafana Cloud is not connected"})

View file

@ -1,4 +1,4 @@
from urllib.parse import urljoin
from collections import OrderedDict
from rest_framework import mixins, status, viewsets
from rest_framework.decorators import action
@ -6,11 +6,11 @@ from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
import apps.oss_installation.constants as cloud_constants
from apps.api.permissions import ActionPermission, AnyRole, IsAdmin, IsOwnerOrAdmin
from apps.auth_token.auth import PluginAuthentication
from apps.oss_installation.models import CloudConnector, CloudUserIdentity
from apps.oss_installation.serializers import CloudUserSerializer
from apps.oss_installation.utils import cloud_user_identity_status
from apps.user_management.models import User
from common.api_helpers.mixins import PublicPrimaryKeyMixin
from common.api_helpers.paginators import HundredPageSizePaginator
@ -28,10 +28,10 @@ class CloudUsersView(HundredPageSizePaginator, APIView):
if request.user.current_team is not None:
queryset = queryset.filter(teams=request.user.current_team).distinct()
emails = list(queryset.values_list("email", flat=True))
results = self.paginate_queryset(queryset, request, view=self)
emails = list(queryset.values_list("email", flat=True))
cloud_identities = list(CloudUserIdentity.objects.filter(email__in=emails))
cloud_identities = {cloud_identity.email: cloud_identity for cloud_identity in cloud_identities}
@ -40,20 +40,8 @@ class CloudUsersView(HundredPageSizePaginator, APIView):
connector = CloudConnector.objects.first()
for user in results:
link = None
status = cloud_constants.CLOUD_NOT_SYNCED
if connector is not None:
status = cloud_constants.CLOUD_SYNCED_USER_NOT_FOUND
cloud_identity = cloud_identities.get(user.email, None)
if cloud_identity:
status = cloud_constants.CLOUD_SYNCED_PHONE_NOT_VERIFIED
is_phone_verified = cloud_identity.phone_number_verified
if is_phone_verified:
status = cloud_constants.CLOUD_SYNCED_PHONE_VERIFIED
link = urljoin(
connector.cloud_url, f"a/grafana-oncall-app/?page=users&p=1&id={cloud_identity.cloud_id}"
)
cloud_identity = cloud_identities.get(user.email, None)
status, link = cloud_user_identity_status(connector, cloud_identity)
response.append(
{
"id": user.public_primary_key,
@ -63,7 +51,20 @@ class CloudUsersView(HundredPageSizePaginator, APIView):
}
)
return self.get_paginated_response(response)
return self.get_paginated_response_with_matched_users_count(response, len(cloud_identities))
def get_paginated_response_with_matched_users_count(self, data, matched_users_count):
return Response(
OrderedDict(
[
("count", self.page.paginator.count),
("matched_users_count", matched_users_count),
("next", self.get_next_link()),
("previous", self.get_previous_link()),
("results", data),
]
)
)
def post(self, request):
connector = CloudConnector.objects.first()

View file

@ -41,6 +41,10 @@ class IntegrationView(
queryset = AlertReceiveChannel.objects.filter(organization=self.request.auth.organization).order_by(
"created_at"
)
name = self.request.query_params.get("name", None)
if name is not None:
queryset = queryset.filter(verbal_name=name)
queryset = self.filter_queryset(queryset)
queryset = self.serializer_class.setup_eager_loading(queryset)
queryset = queryset.annotate(alert_groups_count_annotated=Count("alert_groups", distinct=True))
return queryset

View file

@ -56,7 +56,11 @@ class OpenAlertAppearanceDialogStep(
raw_request_data = json.dumps(alert_group.alerts.first().raw_request_data, sort_keys=True, indent=4)
# This is a special case for amazon sns notifications in str format CHEKED
if alert_group.channel.integration == AlertReceiveChannel.INTEGRATION_AMAZON_SNS and raw_request_data == "{}":
if (
AlertReceiveChannel.INTEGRATION_AMAZON_SNS is not None
and alert_group.channel.integration == AlertReceiveChannel.INTEGRATION_AMAZON_SNS
and raw_request_data == "{}"
):
raw_request_data = alert_group.alerts.first().message
raw_request_data_chunks = [

View file

@ -119,6 +119,9 @@ class SlackEventApiEndpointView(APIView):
return Response(status=403)
if not settings.DEBUG:
if live_settings.SLACK_SIGNING_SECRET is None and settings.SLACK_SIGNING_SECRET_LIVE:
raise Exception("Please specify SLACK_SIGNING_SECRET or use DEBUG.")
if not (
SlackEventApiEndpointView.verify_signature(
slack_request_timestamp, slack_signature, body, live_settings.SLACK_SIGNING_SECRET

View file

@ -34,8 +34,10 @@ class LiveSettingDjangoStrategy(DjangoStrategy):
def build_absolute_uri(self, path=None):
"""
Overriden DjangoStrategy's method to substitute and force the host value from ENV
Overridden DjangoStrategy's method to substitute and force the host value from ENV
"""
if live_settings.SLACK_INSTALL_RETURN_REDIRECT_HOST is not None and path is not None:
return live_settings.SLACK_INSTALL_RETURN_REDIRECT_HOST + path
if settings.SLACK_INSTALL_RETURN_REDIRECT_HOST is not None and path is not None:
return settings.SLACK_INSTALL_RETURN_REDIRECT_HOST + path
if self.request:

View file

@ -0,0 +1,66 @@
# Main
enabled = True
title = "Elastalert"
slug = "elastalert"
short_description = "Elastic"
is_displayed_on_web = True
description = None
is_featured = False
is_able_to_autoresolve = True
is_demo_alert_enabled = True
description = None
# Default templates
slack_title = """\
*<{{ grafana_oncall_link }}|#{{ grafana_oncall_incident_id }} Incident>* via {{ integration_name }}
{% if source_link %}
(*<{{ source_link }}|source>*)
{%- endif %}"""
slack_message = "```{{ payload|tojson_pretty }}```"
slack_image_url = None
web_title = "Incident"
web_message = """\
```
{{ payload|tojson_pretty }}
```
"""
web_image_url = slack_image_url
sms_title = web_title
phone_call_title = sms_title
email_title = web_title
email_message = "{{ payload|tojson_pretty }}"
telegram_title = sms_title
telegram_message = "<code>{{ payload|tojson_pretty }}</code>"
telegram_image_url = slack_image_url
source_link = None
grouping_id = '{{ payload.get("alert_uid", "")}}'
resolve_condition = """\
{%- if "is_amixr_heartbeat_restored" in payload -%}
{# We don't know the payload format from your integration. #}
{# The heartbeat alerts will go here so we check for our own key #}
{{ payload["is_amixr_heartbeat_restored"] }}
{%- else -%}
{{ payload.get("state", "").upper() == "OK" }}
{%- endif %}"""
acknowledge_condition = None
group_verbose_name = "Incident"
example_payload = {"message": "This alert was sent by user for the demonstration purposes"}

View file

@ -0,0 +1,65 @@
# Main
enabled = True
title = "Kapacitor"
slug = "kapacitor"
short_description = "InfluxDB"
description = None
is_displayed_on_web = True
is_featured = False
is_able_to_autoresolve = True
is_demo_alert_enabled = True
description = None
# Default templates
slack_title = """\
*<{{ grafana_oncall_link }}|#{{ grafana_oncall_incident_id }} {{ payload.get("id", "Title undefined (check Slack Title Template)") }}>* via {{ integration_name }}
{% if source_link %}
(*<{{ source_link }}|source>*)
{%- endif %}"""
slack_message = """\
```{{ payload|tojson_pretty }}```
"""
slack_image_url = None
web_title = '{{ payload.get("id", "Title undefined (check Web Title Template)") }}'
web_message = """\
```
{{ payload|tojson_pretty }}
```
"""
web_image_url = slack_image_url
sms_title = web_title
phone_call_title = web_title
email_title = web_title
email_message = slack_message
telegram_title = sms_title
telegram_message = "<code>{{ payload|tojson_pretty }}</code>"
telegram_image_url = slack_image_url
source_link = None
grouping_id = '{{ payload.get("id", "") }}'
resolve_condition = '{{ payload.get("level", "").startswith("OK") }}'
acknowledge_condition = None
group_verbose_name = '{{ payload.get("id", "") }}'
example_payload = {
"id": "TestAlert",
"message": "This alert was sent by user for the demonstration purposes",
"data": "{foo: bar}",
}

View file

@ -56,7 +56,7 @@ resolve_condition = """\
{# The heartbeat alerts will go here so we check for our own key #}
{{ payload["is_amixr_heartbeat_restored"] }}
{%- else -%}
{{ payload.get("state", "").upper() == "OK" }}'
{{ payload.get("state", "").upper() == "OK" }}
{%- endif %}"""
acknowledge_condition = None

View file

@ -1,5 +1,4 @@
import sys
from random import randrange
from .prod_without_db import * # noqa
@ -37,27 +36,3 @@ CELERY_BROKER_URL = "redis://localhost:6379/0"
if TESTING:
TELEGRAM_TOKEN = "0000000000:XXXXXXXXXXXXXXXXXXXXXXXXXXXX-XXXXXX"
TWILIO_AUTH_TOKEN = "twilio_auth_token"
# TODO: OSS: Add these setting to oss settings file. Add Version there too.
OSS_INSTALLATION_FEATURES_ENABLED = True
SEND_ANONYMOUS_USAGE_STATS = True
INSTALLED_APPS += ["apps.oss_installation"] # noqa
CELERY_BEAT_SCHEDULE["send_usage_stats"] = { # noqa
"task": "apps.oss_installation.tasks.send_usage_stats_report",
"schedule": crontab(hour=0, minute=randrange(0, 59)), # Send stats report at a random minute past midnight # noqa
"args": (),
} # noqa
CELERY_BEAT_SCHEDULE["send_cloud_heartbeat"] = { # noqa
"task": "apps.oss_installation.tasks.send_cloud_heartbeat",
"schedule": crontab(minute="*/3"), # noqa
"args": (),
} # noqa
CELERY_BEAT_SCHEDULE["sync_users_with_cloud"] = { # noqa
"task": "apps.oss_installation.tasks.sync_users_with_cloud",
"schedule": crontab(hour="*/12"), # noqa
"args": (),
} # noqa

View file

@ -1,4 +1,5 @@
import os
from random import randrange
from urllib.parse import urljoin
from celery.schedules import crontab
@ -7,8 +8,8 @@ from common.utils import getenv_boolean
VERSION = "dev-oss"
# Indicates if instance is OSS installation.
# It is needed to plug-in oss urls.
OSS_INSTALLATION = getenv_boolean("OSS", False)
# It is needed to plug-in oss application and urls.
OSS_INSTALLATION = getenv_boolean("GRAFANA_ONCALL_OSS_INSTALLATION", True)
SEND_ANONYMOUS_USAGE_STATS = getenv_boolean("SEND_ANONYMOUS_USAGE_STATS", default=True)
# License is OpenSource or Cloud
@ -428,15 +429,39 @@ FEATURE_EXTRA_MESSAGING_BACKENDS_ENABLED = getenv_boolean("FEATURE_EXTRA_MESSAGI
EXTRA_MESSAGING_BACKENDS = []
INSTALLED_ONCALL_INTEGRATIONS = [
"apps.integrations.metadata.configuration.alertmanager",
"apps.integrations.metadata.configuration.grafana",
"apps.integrations.metadata.configuration.grafana_alerting",
"apps.integrations.metadata.configuration.formatted_webhook",
"apps.integrations.metadata.configuration.webhook",
"apps.integrations.metadata.configuration.amazon_sns",
"apps.integrations.metadata.configuration.heartbeat",
"apps.integrations.metadata.configuration.inbound_email",
"apps.integrations.metadata.configuration.maintenance",
"apps.integrations.metadata.configuration.manual",
"apps.integrations.metadata.configuration.slack_channel",
"config_integrations.alertmanager",
"config_integrations.grafana",
"config_integrations.grafana_alerting",
"config_integrations.formatted_webhook",
"config_integrations.webhook",
"config_integrations.kapacitor",
"config_integrations.elastalert",
"config_integrations.heartbeat",
"config_integrations.inbound_email",
"config_integrations.maintenance",
"config_integrations.manual",
"config_integrations.slack_channel",
]
if OSS_INSTALLATION:
INSTALLED_APPS += ["apps.oss_installation"] # noqa
CELERY_BEAT_SCHEDULE["send_usage_stats"] = { # noqa
"task": "apps.oss_installation.tasks.send_usage_stats_report",
"schedule": crontab(
hour=0, minute=randrange(0, 59)
), # Send stats report at a random minute past midnight # noqa
"args": (),
} # noqa
CELERY_BEAT_SCHEDULE["send_cloud_heartbeat"] = { # noqa
"task": "apps.oss_installation.tasks.send_cloud_heartbeat_task",
"schedule": crontab(minute="*/3"), # noqa
"args": (),
} # noqa
CELERY_BEAT_SCHEDULE["sync_users_with_cloud"] = { # noqa
"task": "apps.oss_installation.tasks.sync_users_with_cloud",
"schedule": crontab(hour="*/12"), # noqa
"args": (),
} # noqa

View file

@ -27,5 +27,3 @@ TWILIO_AUTH_TOKEN = "dummy_twilio_auth_token"
FEATURE_EXTRA_MESSAGING_BACKENDS_ENABLED = True
EXTRA_MESSAGING_BACKENDS = ["apps.base.tests.messaging_backend.TestOnlyBackend"]
OSS_INSTALLATION = True
INSTALLED_APPS += ["apps.oss_installation"] # noqa

View file

@ -36,22 +36,3 @@ MIRAGE_CIPHER_IV = "1234567890abcdef" # use default
APPEND_SLASH = False
SECURE_SSL_REDIRECT = False
# TODO: OSS: Add these setting to oss settings file. Add Version there too.
OSS_INSTALLATION_FEATURES_ENABLED = True
INSTALLED_APPS += ["apps.oss_installation"] # noqa
CELERY_BEAT_SCHEDULE["send_usage_stats"] = { # noqa
"task": "apps.oss_installation.tasks.send_usage_stats_report",
"schedule": crontab(hour=0, minute=randrange(0, 59)), # Send stats report at a random minute past midnight # noqa
"args": (),
} # noqa
CELERY_BEAT_SCHEDULE["send_cloud_heartbeat"] = { # noqa
"task": "apps.oss_installation.tasks.send_cloud_heartbeat",
"schedule": crontab(minute="*/3"), # noqa
"args": (),
} # noqa
SEND_ANONYMOUS_USAGE_STATS = True

View file

@ -35,7 +35,7 @@ export interface NotificationPolicyProps {
waitDelays?: WaitDelay[];
notifyByOptions?: NotifyBy[];
telegramVerified: boolean;
phoneVerified: boolean;
phoneStatus: number;
color: string;
number: number;
userAction: UserAction;
@ -115,13 +115,21 @@ export class NotificationPolicy extends React.Component<NotificationPolicyProps,
}
_renderPhoneNote() {
const { phoneVerified } = this.props;
const { phoneStatus } = this.props;
return phoneVerified ? (
<PolicyNote type="success">Phone number is verified</PolicyNote>
) : (
<PolicyNote type="danger">Phone number is not verified</PolicyNote>
);
switch (phoneStatus) {
case 0:
return <PolicyNote type="danger">Cloud is not synced</PolicyNote>;
case 1:
return <PolicyNote type="danger">User is not matched with cloud</PolicyNote>;
case 2:
return <PolicyNote type="danger">Phone number is not verified</PolicyNote>;
case 3:
return <PolicyNote type="success">Phone number is verified</PolicyNote>;
default:
return null;
}
}
_renderTelegramNote() {

View file

@ -12,6 +12,7 @@ import Timeline from 'components/Timeline/Timeline';
import { WithPermissionControl } from 'containers/WithPermissionControl/WithPermissionControl';
import { NotificationPolicyType } from 'models/notification_policy';
import { User as UserType } from 'models/user/user.types';
import { AppFeature } from 'state/features';
import { useStore } from 'state/useStore';
import { UserAction } from 'state/userAction';
@ -105,6 +106,12 @@ const PersonalNotificationSettings = observer((props: PersonalNotificationSettin
const user = userStore.items[userPk];
const userAction = isCurrent ? UserAction.UpdateOwnSettings : UserAction.UpdateNotificationPolicies;
const getPhoneStatus = () => {
if (store.hasFeature(AppFeature.CloudNotifications)) {
return user.cloud_connection_status;
}
return Number(user.verified_phone_number) + 2;
};
return (
<div className={cx('root')}>
@ -124,7 +131,7 @@ const PersonalNotificationSettings = observer((props: PersonalNotificationSettin
index={index}
number={index + 1}
telegramVerified={Boolean(user.telegram_configuration)}
phoneVerified={Boolean(user && user.verified_phone_number)}
phoneStatus={getPhoneStatus()}
slackTeamIdentity={store.teamStore.currentTeam?.slack_team_identity}
slackUserIdentity={user.slack_user_identity}
data={notificationPolicy}

View file

@ -1,11 +1,12 @@
import React, { useCallback } from 'react';
import { Button, Label } from '@grafana/ui';
import { Button, Label, VerticalGroup } from '@grafana/ui';
import cn from 'classnames/bind';
import Text from 'components/Text/Text';
import { UserSettingsTab } from 'containers/UserSettings/UserSettings.types';
import { User } from 'models/user/user.types';
import { AppFeature } from 'state/features';
import { useStore } from 'state/useStore';
import styles from './index.module.css';
@ -29,31 +30,85 @@ const PhoneConnector = (props: PhoneConnectorProps) => {
onTabChange(UserSettingsTab.PhoneVerification);
}, [storeUser?.unverified_phone_number]);
const cloudVersionPhone = (user: User) => {
switch (user.cloud_connection_status) {
case 0:
return <Text className={cx('error-message')}>Cloud is not synced</Text>;
case 1:
return (
<VerticalGroup>
<Text className={cx('error-message')}>User is not matched with cloud</Text>
<Button size="sm" fill="text" onClick={handleClickConfirmPhoneButton}>
Sign Up to Cloud
</Button>
</VerticalGroup>
);
case 2:
return (
<VerticalGroup>
<Text type="warning">Phone number is not verified in Grafana Cloud</Text>
<Button size="sm" fill="text" onClick={handleClickConfirmPhoneButton}>
Verify or change
</Button>
</VerticalGroup>
);
case 3:
return (
<VerticalGroup>
<Text type="success">Phone number verified</Text>
<Button size="sm" fill="text" onClick={handleClickConfirmPhoneButton}>
Change
</Button>
</VerticalGroup>
);
default:
return (
<VerticalGroup>
<Text className={cx('error-message')}>User is not matched with cloud</Text>
<Button size="sm" fill="text" onClick={handleClickConfirmPhoneButton}>
Sign Up to Cloud
</Button>
</VerticalGroup>
);
}
};
return (
<div className={cx('user-item')}>
<Label>Verified phone number:</Label>
<span className={cx('user-value')}>{storeUser.verified_phone_number || '—'}</span>
{storeUser.verified_phone_number ? (
<div>
<Text type="secondary">Phone number is verified</Text>
<Button size="sm" fill="text" onClick={handleClickConfirmPhoneButton}>
Change
</Button>
</div>
) : storeUser.unverified_phone_number ? (
<div>
<Text type="warning">Phone number is not verified</Text>
<Button size="sm" fill="text" onClick={handleClickConfirmPhoneButton}>
Verify or change
</Button>
</div>
{store.hasFeature(AppFeature.CloudNotifications) ? (
<>
<Label>Cloud phone status:</Label>
{cloudVersionPhone(storeUser)}
</>
) : (
<div>
<Text type="warning">Phone number is not added</Text>
<Button size="sm" fill="text" onClick={handleClickConfirmPhoneButton}>
Add
</Button>
</div>
<>
<Label>Verified phone number:</Label>
<span className={cx('user-value')}>{storeUser.verified_phone_number || '—'}</span>
{storeUser.verified_phone_number ? (
<div>
<Text type="secondary">Phone number is verified</Text>
<Button size="sm" fill="text" onClick={handleClickConfirmPhoneButton}>
Change
</Button>
</div>
) : storeUser.unverified_phone_number ? (
<div>
<Text type="warning">Phone number is not verified</Text>
<Button size="sm" fill="text" onClick={handleClickConfirmPhoneButton}>
Verify or change
</Button>
</div>
) : (
<div>
<Text type="warning">Phone number is not added</Text>
<Button size="sm" fill="text" onClick={handleClickConfirmPhoneButton}>
Add
</Button>
</div>
)}
</>
)}
</div>
);

View file

@ -30,3 +30,7 @@
.warning-icon {
color: var(--warning-text-color);
}
.error-message {
color: var(--error-text-color);
}

View file

@ -48,12 +48,15 @@ const CloudPhoneSettings = observer((props: CloudPhoneSettingsProps) => {
}, []);
const handleLinkClick = (link: string) => {
getLocationSrv().update({ partial: false, path: link });
window.location.replace(link);
};
const syncUser = async () => {
setSyncing(true);
await store.cloudStore.syncCloudUser(userPk);
const cloudUser = await store.cloudStore.getCloudUser(userPk);
setUserStatus(cloudUser?.cloud_data?.status);
setUserLink(cloudUser?.cloud_data?.link);
setSyncing(false);
};

View file

@ -30,13 +30,13 @@
background: var(--highlighted-row-bg);
}
@media (max-width: 1440px) {
@media (max-width: 1540px) {
.page-header__tabs > ul > li > a > div {
display: none;
}
}
@media (max-width: 1200px) {
@media (max-width: 1300px) {
.sidemenu {
position: fixed !important;
height: 100%;

View file

@ -52,10 +52,11 @@ export default class BaseStore {
}
@action
async update(id: any, data: any) {
async update(id: any, data: any, params: any = null) {
const result = await makeRequest(`${this.path}${id}/`, {
method: 'PUT',
data,
params: params,
}).catch(this.onApiError);
// Update env_status field for current team

View file

@ -13,7 +13,7 @@ import { Cloud } from './cloud.types';
export class CloudStore extends BaseStore {
@observable.shallow
searchResult: { count?: number; results?: Array<Cloud['id']> } = {};
searchResult: { matched_users_count?: number; results?: Array<Cloud['id']> } = {};
@observable.shallow
items: { [id: string]: Cloud } = {};
@ -26,7 +26,7 @@ export class CloudStore extends BaseStore {
@action
async updateItems(page = 1) {
const { count, results } = await makeRequest(this.path, {
const { matched_users_count, results } = await makeRequest(this.path, {
params: { page },
});
@ -42,14 +42,14 @@ export class CloudStore extends BaseStore {
};
this.searchResult = {
count,
matched_users_count,
results: results.map((item: Cloud) => item.id),
};
}
getSearchResult() {
return {
count: this.searchResult.count,
matched_users_count: this.searchResult.matched_users_count,
results: this.searchResult.results && this.searchResult.results.map((id: Cloud['id']) => this.items?.[id]),
};
}
@ -62,6 +62,12 @@ export class CloudStore extends BaseStore {
return await makeRequest(`${this.path}${id}/sync/`, { method: 'POST' });
}
async getCloudHeartbeat() {
return await makeRequest(`/cloud_heartbeat/`, { method: 'POST' }).catch((error) => {
console.log(error);
});
}
async getCloudUser(id: string) {
return await makeRequest(`${this.path}${id}`, { method: 'GET' });
}

View file

@ -52,4 +52,5 @@ export interface User {
export_url?: string;
status?: number;
link?: string;
cloud_connection_status?: number;
}

View file

@ -25,7 +25,8 @@
height: 32px;
}
.cloud-page-title {
.cloud-page-title,
.heartbit-button {
margin-top: 24px;
}

Some files were not shown because too many files have changed in this diff Show more