CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-py-zabbix

Python module to work with Zabbix monitoring systems through API and sender functionality

Pending
Overview
Eval results
Files

metric-sending.mddocs/

Metric Sending

Send monitoring metrics to Zabbix server via trapper protocol with batch processing, configurable connection parameters, and comprehensive response handling. This functionality allows external applications to push metrics data directly to Zabbix for monitoring and alerting.

Capabilities

ZabbixSender Class

Client for sending metrics to Zabbix server using the trapper protocol with batch processing and configurable connection settings.

class ZabbixSender:
    def __init__(self, zabbix_server='127.0.0.1', zabbix_port=10051, use_config=None, chunk_size=250, socket_wrapper=None, timeout=10):
        """
        Initialize ZabbixSender client.
        
        Parameters:
        - zabbix_server (str): Zabbix server IP address (default: '127.0.0.1')
        - zabbix_port (int): Zabbix server port (default: 10051)
        - use_config (str/bool, optional): Path to zabbix_agentd.conf file or True for default location
        - chunk_size (int): Number of metrics to send per batch (default: 250)
        - socket_wrapper (function, optional): Socket wrapper function for SSL/encryption
        - timeout (int): Connection timeout in seconds (default: 10)
        """

Sending Metrics

def send(self, metrics):
    """
    Send list of metrics to Zabbix server.
    
    Parameters:
    - metrics (list): List of ZabbixMetric objects to send
    
    Returns:
    ZabbixResponse: Response object with send results
    
    Raises:
    socket.error: If connection fails
    ValueError: If invalid metric data
    """

ZabbixMetric Class

Container class representing a single metric to send to Zabbix with host, key, value, and optional timestamp.

class ZabbixMetric:
    def __init__(self, host, key, value, clock=None):
        """
        Create a single metric for sending to Zabbix.
        
        Parameters:
        - host (str): Hostname as displayed in Zabbix frontend
        - key (str): Item key identifier (must match Zabbix item configuration)
        - value (str/int/float): Metric value to send
        - clock (int, optional): Unix timestamp (default: current time)
        
        Attributes:
        - host (str): Metric hostname
        - key (str): Metric key
        - value (str): Metric value (converted to string)
        - clock (int): Unix timestamp
        """

ZabbixResponse Class

Response parser that processes server responses and provides access to send operation statistics.

class ZabbixResponse:
    def __init__(self):
        """Initialize response tracking counters."""
    
    def parse(self, response):
        """
        Parse server response and update counters.
        
        Parameters:
        - response (str): JSON response from Zabbix server
        """
    
    @property
    def processed(self):
        """
        Number of successfully processed metrics.
        
        Returns:
        int: Count of processed metrics
        """
    
    @property
    def failed(self):
        """
        Number of failed metrics.
        
        Returns:
        int: Count of failed metrics
        """
    
    @property
    def total(self):
        """
        Total number of metrics sent.
        
        Returns:
        int: Total metric count
        """
    
    @property
    def time(self):
        """
        Total processing time on server.
        
        Returns:
        Decimal: Processing time in seconds
        """
    
    @property
    def chunk(self):
        """
        Number of chunks/batches sent.
        
        Returns:
        int: Chunk count
        """

Usage Examples

Basic Metric Sending

from pyzabbix import ZabbixMetric, ZabbixSender

# Create individual metrics
metrics = [
    ZabbixMetric('webserver01', 'cpu.usage', 85.2),
    ZabbixMetric('webserver01', 'memory.usage[percent]', 67.5),
    ZabbixMetric('webserver01', 'disk.free[/]', 1024000000),
    ZabbixMetric('database01', 'mysql.queries', 1500),
]

# Send to Zabbix server
sender = ZabbixSender(zabbix_server='192.168.1.100', zabbix_port=10051)
result = sender.send(metrics)

print(f"Processed: {result.processed}")
print(f"Failed: {result.failed}")
print(f"Total: {result.total}")
print(f"Time: {result.time} seconds")

Using Configuration File

from pyzabbix import ZabbixMetric, ZabbixSender

# Use default zabbix_agentd.conf location
sender = ZabbixSender(use_config=True)

# Or specify custom config file path
sender = ZabbixSender(use_config='/etc/zabbix/zabbix_agentd.conf')

metrics = [
    ZabbixMetric('server01', 'custom.metric', 42),
]

result = sender.send(metrics)

Batch Processing with Custom Chunk Size

from pyzabbix import ZabbixMetric, ZabbixSender

# Create large number of metrics
metrics = []
for i in range(1000):
    metrics.append(ZabbixMetric('server01', f'metric.{i}', i * 10))

# Send in smaller chunks
sender = ZabbixSender(
    zabbix_server='zabbix.example.com',
    chunk_size=100,  # Send 100 metrics at a time
    timeout=30       # 30 second timeout
)

result = sender.send(metrics)
print(f"Sent {result.total} metrics in {result.chunk} chunks")

Using Timestamps

import time
from pyzabbix import ZabbixMetric, ZabbixSender

# Current timestamp
current_time = int(time.time())

# Historical timestamp (1 hour ago)
historical_time = current_time - 3600

metrics = [
    ZabbixMetric('server01', 'current.value', 100, current_time),
    ZabbixMetric('server01', 'historical.value', 90, historical_time),
    ZabbixMetric('server01', 'auto.timestamp', 110),  # Uses current time
]

sender = ZabbixSender()
result = sender.send(metrics)

SSL/TLS Connection

import ssl
from pyzabbix import ZabbixMetric, ZabbixSender

def ssl_wrapper(sock):
    """Custom SSL wrapper function."""
    context = ssl.create_default_context()
    return context.wrap_socket(sock)

sender = ZabbixSender(
    zabbix_server='secure-zabbix.example.com',
    zabbix_port=10051,
    socket_wrapper=ssl_wrapper
)

metrics = [ZabbixMetric('server01', 'secure.metric', 42)]
result = sender.send(metrics)

Error Handling

import socket
from pyzabbix import ZabbixMetric, ZabbixSender

sender = ZabbixSender(zabbix_server='192.168.1.100', timeout=5)
metrics = [ZabbixMetric('server01', 'test.metric', 100)]

try:
    result = sender.send(metrics)
    
    if result.failed > 0:
        print(f"Warning: {result.failed} metrics failed to process")
    
    print(f"Successfully sent {result.processed} metrics")
    
except socket.timeout:
    print("Connection timeout - Zabbix server may be unreachable")
except socket.error as e:
    print(f"Network error: {e}")
except ValueError as e:
    print(f"Invalid metric data: {e}")

Monitoring Script Integration

import psutil
import time
from pyzabbix import ZabbixMetric, ZabbixSender

def collect_system_metrics(hostname):
    """Collect system metrics and send to Zabbix."""
    metrics = []
    
    # CPU usage
    cpu_percent = psutil.cpu_percent(interval=1)
    metrics.append(ZabbixMetric(hostname, 'system.cpu.util', cpu_percent))
    
    # Memory usage
    memory = psutil.virtual_memory()
    metrics.append(ZabbixMetric(hostname, 'vm.memory.util[pused]', memory.percent))
    
    # Disk usage
    disk = psutil.disk_usage('/')
    disk_percent = (disk.used / disk.total) * 100
    metrics.append(ZabbixMetric(hostname, 'vfs.fs.size[/,pused]', disk_percent))
    
    # Load average (Unix systems)
    try:
        load1, load5, load15 = psutil.getloadavg()
        metrics.append(ZabbixMetric(hostname, 'system.cpu.load[all,avg1]', load1))
    except AttributeError:
        pass  # Not available on Windows
    
    return metrics

# Send metrics
hostname = 'server01'
sender = ZabbixSender(zabbix_server='monitoring.example.com')

while True:
    try:
        metrics = collect_system_metrics(hostname)
        result = sender.send(metrics)
        print(f"Sent {result.processed} metrics, {result.failed} failed")
        
    except Exception as e:
        print(f"Error collecting/sending metrics: {e}")
    
    time.sleep(60)  # Send every minute

Configuration File Format

When using use_config=True or specifying a config file path, ZabbixSender reads server connection details from zabbix_agentd.conf format:

# Server configuration
Server=192.168.1.100
ServerPort=10051

# Optional settings
Timeout=10

The following parameters are read from the configuration file:

  • Server or ServerActive: Zabbix server IP address
  • ServerPort: Zabbix server port (default: 10051)

Install with Tessl CLI

npx tessl i tessl/pypi-py-zabbix

docs

api-interface.md

index.md

metric-sending.md

tile.json