Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Php Zabbix Sender Laravel Package

disc/php-zabbix-sender

Modern PHP implementation of a Zabbix Sender client. Send metrics to Zabbix server quickly by adding host/key/value data and calling send(). Supports PHP 5.4+ and works with Zabbix 2.0.8, 2.1.7+ and 4.0.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require disc/php-zabbix-sender
    

    Add the package to your composer.json and run composer update.

  2. Basic Setup: Import the package and initialize the sender with your Zabbix server details:

    use Disc\Zabbix\Sender;
    
    $sender = new Sender('zabbix.example.com', 10051);
    
  3. First Use Case: Send a simple metric to Zabbix:

    $sender->addData('your_hostname', 'system.cpu.load[percpu,avg1]', 42.5);
    $sender->send();
    

Where to Look First

  • README.md: For basic usage and examples.
  • sample/sample.php: A practical example of how to integrate the package into a Laravel application.
  • Tests: Located in the tests/ directory, useful for understanding edge cases and expected behavior.

Implementation Patterns

Usage Patterns

  1. Sending Metrics:

    $sender = new Sender('zabbix.example.com', 10051);
    $sender->addData('webserver1', 'net.if.in[eth0]', 1024); // Hostname, key, value
    $sender->send();
    
  2. Bulk Sending:

    $sender = new Sender('zabbix.example.com', 10051);
    $metrics = [
        ['webserver1', 'vm.memory.size[available]', 500000],
        ['webserver1', 'system.cpu.util[,user]', 30.5],
    ];
    foreach ($metrics as $metric) {
        $sender->addData($metric[0], $metric[1], $metric[2]);
    }
    $sender->send();
    
  3. Timeout Handling: Configure a timeout for the connection (default: 10 seconds):

    $sender = new Sender('zabbix.example.com', 10051, 30); // 30-second timeout
    
  4. Laravel Integration:

    • Service Provider: Register the sender in AppServiceProvider:
      public function register()
      {
          $this->app->singleton('zabbix.sender', function ($app) {
              return new Sender(config('zabbix.host'), config('zabbix.port'));
          });
      }
      
    • Config File: Define Zabbix settings in config/zabbix.php:
      return [
          'host' => 'zabbix.example.com',
          'port' => 10051,
          'timeout' => 10,
      ];
      
    • Facade: Create a facade for easy access:
      // app/Facades/Zabbix.php
      namespace App\Facades;
      
      use Illuminate\Support\Facades\Facade;
      
      class Zabbix extends Facade
      {
          protected static function getFacadeAccessor()
          {
              return 'zabbix.sender';
          }
      }
      
    • Usage in Controllers/Jobs:
      use App\Facades\Zabbix;
      
      public function sendMetrics()
      {
          Zabbix::addData('webserver1', 'system.cpu.load[percpu,avg1]', 45.2);
          Zabbix::send();
      }
      
  5. Logging Failures: Wrap the send() call in a try-catch block to log errors:

    try {
        $sender->send();
    } catch (\Exception $e) {
        \Log::error("Zabbix sender failed: " . $e->getMessage());
    }
    

Gotchas and Tips

Pitfalls

  1. Hostname Mismatch: Ensure the hostname used in addData() matches the hostname registered in Zabbix. Mismatches will result in failed sends.

  2. Key Validation: Zabbix keys must be valid (e.g., system.cpu.load[percpu,avg1]). Invalid keys will cause the send to fail silently or throw an exception.

  3. Connection Issues:

    • Timeouts: If the Zabbix server is unreachable, the sender will throw a RuntimeException. Handle this gracefully in production.
    • Firewall/Network: Ensure the server can reach the Zabbix agent port (default: 10051). Test connectivity with:
      telnet zabbix.example.com 10051
      
  4. Data Types: The addData() method expects the value to be a numeric type (int/float). Passing strings or other types may cause issues.

  5. Zabbix Version Compatibility:

    • For Zabbix 4.0+, ensure you’re using version 1.3.0+ of the package.
    • Older versions (e.g., 2.0.8) may require adjustments to the protocol header.

Debugging

  1. Enable Verbose Output: The package doesn’t natively support verbose logging, but you can inspect the raw data being sent by extending the Sender class:

    class DebugSender extends Sender
    {
        protected function sendData()
        {
            \Log::debug('Sending data: ' . print_r($this->data, true));
            parent::sendData();
        }
    }
    
  2. Check Zabbix Server Logs: If sends fail, check the Zabbix server logs (/var/log/zabbix/zabbix_server.log) for errors like:

    cannot send to [127.0.0.1]:10051, timeout in 10 seconds
    
  3. Test with zabbix_sender: Validate your keys and hostnames using the official Zabbix sender:

    echo "your_hostname system.cpu.load[percpu,avg1] 42.5" | zabbix_sender -z zabbix.example.com -p 10051 -vv
    

Tips

  1. Batch Processing: For high-volume metrics, batch sends to reduce overhead:

    $sender = new Sender('zabbix.example.com', 10051);
    foreach ($metrics as $metric) {
        $sender->addData($metric['hostname'], $metric['key'], $metric['value']);
    }
    $sender->send(); // Single send call for all metrics
    
  2. Retry Logic: Implement a retry mechanism for transient failures:

    $attempts = 0;
    $maxAttempts = 3;
    while ($attempts < $maxAttempts) {
        try {
            $sender->send();
            break;
        } catch (\Exception $e) {
            $attempts++;
            if ($attempts >= $maxAttempts) {
                throw $e;
            }
            sleep(2 ** $attempts); // Exponential backoff
        }
    }
    
  3. Environment-Specific Config: Use Laravel’s environment config to switch Zabbix servers:

    // config/zabbix.php
    return [
        'host' => env('ZABBIX_HOST', 'zabbix.example.com'),
        'port' => env('ZABBIX_PORT', 10051),
    ];
    
  4. Queue Delayed Sends: For non-critical metrics, delay sending via Laravel queues:

    // In a job
    public function handle()
    {
        $this->delay(now()->addMinutes(5));
        $sender = new Sender(config('zabbix.host'), config('zabbix.port'));
        $sender->addData('webserver1', 'system.cpu.load[percpu,avg1]', 42.5);
        $sender->send();
    }
    
  5. Monitoring: Track send failures using Laravel’s monitoring tools (e.g., Horizon) or a dedicated monitoring system. Example:

    try {
        $sender->send();
        event(new ZabbixMetricSent($hostname, $key));
    } catch (\Exception $e) {
        event(new ZabbixMetricFailed($hostname, $key, $e->getMessage()));
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity