0
# API Health Checking
1
2
Comprehensive API validation and feature detection system that ensures compatibility with different Grafana versions and configurations. The health checking system validates connectivity, authentication, and feature availability before performing operations.
3
4
## Capabilities
5
6
### Main Health Check Function
7
8
The primary API validation function that orchestrates comprehensive health checking and feature detection.
9
10
```python { .api }
11
def main(settings):
12
"""
13
Perform comprehensive API health checks and feature detection
14
15
Args:
16
settings (dict): Configuration settings including API endpoints and credentials
17
18
Returns:
19
tuple: (status_code, response_data, dashboard_uid_support,
20
datasource_uid_support, paging_support, contact_point_support)
21
"""
22
```
23
24
### Core Health Check Functions
25
26
Located in the `grafana_backup.dashboardApi` module, these functions provide low-level API validation.
27
28
#### Basic Health Check
29
```python { .api }
30
def health_check(grafana_url, http_get_headers, verify_ssl, client_cert, debug):
31
"""
32
Check Grafana server health and availability
33
34
Args:
35
grafana_url (str): Base URL of Grafana instance
36
http_get_headers (dict): HTTP headers for authentication
37
verify_ssl (bool): Whether to verify SSL certificates
38
client_cert (str): Path to client certificate (optional)
39
debug (bool): Enable debug logging
40
41
Returns:
42
tuple: (status_code, json_response)
43
"""
44
```
45
46
#### Authentication Check
47
```python { .api }
48
def auth_check(grafana_url, http_get_headers, verify_ssl, client_cert, debug):
49
"""
50
Verify API token authentication and permissions
51
52
Args:
53
grafana_url (str): Base URL of Grafana instance
54
http_get_headers (dict): HTTP headers with API token
55
verify_ssl (bool): Whether to verify SSL certificates
56
client_cert (str): Path to client certificate (optional)
57
debug (bool): Enable debug logging
58
59
Returns:
60
tuple: (status_code, json_response)
61
"""
62
```
63
64
#### UID Feature Detection
65
```python { .api }
66
def uid_feature_check(grafana_url, http_get_headers, verify_ssl, client_cert, debug):
67
"""
68
Detect if Grafana instance supports UID-based operations
69
70
Args:
71
grafana_url (str): Base URL of Grafana instance
72
http_get_headers (dict): HTTP headers for authentication
73
verify_ssl (bool): Whether to verify SSL certificates
74
client_cert (str): Path to client certificate (optional)
75
debug (bool): Enable debug logging
76
77
Returns:
78
tuple: (dashboard_uid_support, datasource_uid_support)
79
"""
80
```
81
82
#### Paging Feature Detection
83
```python { .api }
84
def paging_feature_check(grafana_url, http_get_headers, verify_ssl, client_cert, debug):
85
"""
86
Detect if Grafana instance supports API paging (v6.2+)
87
88
Args:
89
grafana_url (str): Base URL of Grafana instance
90
http_get_headers (dict): HTTP headers for authentication
91
verify_ssl (bool): Whether to verify SSL certificates
92
client_cert (str): Path to client certificate (optional)
93
debug (bool): Enable debug logging
94
95
Returns:
96
bool: True if paging is supported, False otherwise
97
"""
98
```
99
100
#### Contact Point Feature Detection
101
```python { .api }
102
def contact_point_check(grafana_url, http_get_headers, verify_ssl, client_cert, debug):
103
"""
104
Detect if Grafana instance supports unified alerting contact points
105
106
Args:
107
grafana_url (str): Base URL of Grafana instance
108
http_get_headers (dict): HTTP headers for authentication
109
verify_ssl (bool): Whether to verify SSL certificates
110
client_cert (str): Path to client certificate (optional)
111
debug (bool): Enable debug logging
112
113
Returns:
114
bool: True if contact points are supported, False otherwise
115
"""
116
```
117
118
## Feature Detection Details
119
120
### UID Support Detection
121
122
The system detects whether the Grafana instance supports UID-based operations:
123
124
#### Dashboard UID Support
125
- **Detection method**: Searches for first dashboard and checks for 'uid' field
126
- **Fallback behavior**: Uses ID-based operations if UIDs not supported
127
- **Impact**: Affects dashboard backup/restore file naming and references
128
129
#### Datasource UID Support
130
- **Detection method**: Retrieves first datasource and checks for 'uid' field
131
- **Fallback behavior**: Uses name-based datasource references
132
- **Impact**: Affects datasource backup/restore and dashboard datasource references
133
134
### Paging Support Detection
135
136
Detects support for API result paging introduced in Grafana 6.2:
137
138
- **Detection method**: Attempts to use paging parameters in search API
139
- **Benefits**: Enables efficient handling of large datasets
140
- **Fallback**: Uses limit-based search for older versions
141
142
### Contact Point Support Detection
143
144
Detects unified alerting contact point support:
145
146
- **Detection method**: Attempts to access contact points API endpoint
147
- **Grafana version**: Available in newer Grafana versions with unified alerting
148
- **Impact**: Determines whether contact points can be backed up and restored
149
150
## Configuration Options
151
152
### Health Check Controls
153
154
Health checking behavior can be controlled through configuration:
155
156
```python { .api }
157
# Configuration settings that control health checking
158
API_HEALTH_CHECK: bool # Enable/disable basic health checks
159
API_AUTH_CHECK: bool # Enable/disable authentication verification
160
DEBUG: bool # Enable debug logging for health checks
161
```
162
163
### SSL and Certificate Options
164
165
```python { .api }
166
# SSL and certificate configuration
167
VERIFY_SSL: bool # Verify SSL certificates
168
CLIENT_CERT: str # Path to client certificate file for mutual TLS
169
```
170
171
## Usage Examples
172
173
### Basic Health Check
174
```python
175
from grafana_backup.api_checks import main as check_api
176
from grafana_backup.grafanaSettings import main as load_config
177
178
# Load configuration
179
settings = load_config('/path/to/grafanaSettings.json')
180
181
# Perform comprehensive health check
182
(status, response, dashboard_uid, datasource_uid,
183
paging, contact_points) = check_api(settings)
184
185
if status == 200:
186
print("API is healthy and authenticated")
187
print(f"Dashboard UID support: {dashboard_uid}")
188
print(f"Datasource UID support: {datasource_uid}")
189
print(f"Paging support: {paging}")
190
print(f"Contact point support: {contact_points}")
191
else:
192
print(f"API check failed: {response}")
193
```
194
195
### Individual Feature Checks
196
```python
197
from grafana_backup.dashboardApi import (
198
health_check, auth_check, uid_feature_check,
199
paging_feature_check, contact_point_check
200
)
201
202
# Extract settings
203
grafana_url = settings['GRAFANA_URL']
204
headers = settings['HTTP_GET_HEADERS']
205
verify_ssl = settings['VERIFY_SSL']
206
client_cert = settings['CLIENT_CERT']
207
debug = settings['DEBUG']
208
209
# Individual health checks
210
health_status, health_response = health_check(
211
grafana_url, headers, verify_ssl, client_cert, debug
212
)
213
214
auth_status, auth_response = auth_check(
215
grafana_url, headers, verify_ssl, client_cert, debug
216
)
217
218
dashboard_uid, datasource_uid = uid_feature_check(
219
grafana_url, headers, verify_ssl, client_cert, debug
220
)
221
222
paging_supported = paging_feature_check(
223
grafana_url, headers, verify_ssl, client_cert, debug
224
)
225
226
contact_points_supported = contact_point_check(
227
grafana_url, headers, verify_ssl, client_cert, debug
228
)
229
```
230
231
### Integration with Operations
232
233
Health checking is automatically integrated into all major operations:
234
235
```python
236
# Example from backup operation
237
from grafana_backup.save import main as save_backup
238
239
# Health checks are performed automatically before backup
240
save_args = {
241
'save': True,
242
'--components': None,
243
'--no-archive': False,
244
'--config': None
245
}
246
247
# This call will automatically:
248
# 1. Perform health checks
249
# 2. Detect feature support
250
# 3. Adapt backup behavior based on detected features
251
# 4. Exit gracefully if health checks fail
252
save_backup(save_args, settings)
253
```
254
255
## Health Check Results
256
257
### Successful Health Check Response
258
259
When all health checks pass, the system configures feature flags:
260
261
```python
262
# Features are added to settings for use by other modules
263
settings.update({
264
'DASHBOARD_UID_SUPPORT': True,
265
'DATASOURCE_UID_SUPPORT': True,
266
'PAGING_SUPPORT': True,
267
'CONTACT_POINT_SUPPORT': False
268
})
269
```
270
271
### Failed Health Check Handling
272
273
When health checks fail, operations are prevented:
274
275
- **Connection failures**: Network connectivity or URL configuration issues
276
- **Authentication failures**: Invalid API tokens or insufficient permissions
277
- **SSL errors**: Certificate validation failures or expired certificates
278
- **Version incompatibility**: Unsupported Grafana versions or configurations
279
280
## Error Handling and Diagnostics
281
282
### Debug Information
283
284
When debug mode is enabled, health checks provide detailed diagnostic information:
285
286
```python
287
# Debug output includes:
288
# - HTTP request/response details
289
# - Authentication header validation
290
# - SSL certificate information
291
# - API endpoint availability
292
# - Feature detection results
293
```
294
295
### Common Issues and Solutions
296
297
#### Connection Issues
298
- **Symptom**: Health check returns non-200 status
299
- **Solutions**: Verify URL, check network connectivity, validate SSL configuration
300
301
#### Authentication Issues
302
- **Symptom**: Auth check fails with 401/403 status
303
- **Solutions**: Verify API token, check token permissions, validate admin credentials
304
305
#### Feature Detection Issues
306
- **Symptom**: Features detected incorrectly
307
- **Solutions**: Check Grafana version, verify API access, review debug output
308
309
## Best Practices
310
311
### Health Check Configuration
312
313
```json
314
{
315
"general": {
316
"api_health_check": true,
317
"api_auth_check": true,
318
"debug": false,
319
"verify_ssl": true
320
}
321
}
322
```
323
324
### Production Considerations
325
326
- **SSL verification**: Always enable SSL verification in production
327
- **Debug logging**: Disable debug logging in production for security
328
- **Health check timing**: Health checks add minimal overhead but can be disabled if needed
329
- **Certificate management**: Ensure SSL certificates are valid and up-to-date
330
331
### Troubleshooting
332
333
- **Enable debug mode**: Set `DEBUG=true` for detailed diagnostic information
334
- **Check network connectivity**: Verify Grafana instance is accessible
335
- **Validate credentials**: Confirm API token has required permissions
336
- **Review Grafana logs**: Check Grafana server logs for additional context
337
338
The API health checking system provides robust validation and feature detection to ensure reliable operation across different Grafana versions and configurations.