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

Zabbix Api Laravel Package

bytes-commerce/zabbix-api

Symfony bundle for the Zabbix JSON-RPC API with persistent auth/token caching, type-safe action factory, and history/metrics retrieval. PHP 8.3+ strict typing, zero-config via env vars, broad API coverage, optional async monitoring via Messenger.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require bytes-commerce/zabbix-api
    

    The bundle auto-registers via Symfony Flex.

  2. Configuration Add to .env.local:

    ZABBIX_API_BASE_URI=https://zabbix.example.com/api_jsonrpc.php
    ZABBIX_USERNAME=monitoring_user
    ZABBIX_PASSWORD=secure_password
    ZABBIX_AUTH_TTL=3600  # Optional: cache TTL in seconds
    APP_NAME=MyApplication # Used for host identification
    
  3. First Use Case Inject ZabbixServiceInterface and use the factory pattern:

    use BytesCommerce\ZabbixApi\ZabbixServiceInterface;
    use BytesCommerce\ZabbixApi\Actions\History;
    
    class MonitoringController {
        public function __construct(private readonly ZabbixServiceInterface $zabbix) {}
    
        public function getCpuMetrics(): array {
            $history = $this->zabbix->action(History::class);
            return $history->getLast24Hours(
                itemIds: ['12345'],
                historyType: HistoryTypeEnum::NUMERIC_FLOAT
            );
        }
    }
    

Where to Look First

  • Actions Table: Reference the Core Concepts > Actions section for available API modules.
  • DTOs: Check the Dto classes under each action (e.g., GetHostGroupDto) for type-safe parameters.
  • Enums: Use HistoryTypeEnum, ItemTypeEnum, etc., for strict typing.

Implementation Patterns

1. Factory Pattern for Actions

  • Type-Safe Instantiation: Always use $zabbix->action(ActionClass::class).
    $hostAction = $zabbix->action(Host::class);
    $history = $zabbix->action(History::class);
    
  • IDE Autocomplete: Leverage PHP 8.3+ strict typing for method suggestions.

2. DTO-Driven Workflows

  • Use DTOs for Complex Queries: Example for HostGroup:
    $dto = new GetHostGroupDto(
        groupids: ['15'],
        output: 'extend',
        selectHosts: true
    );
    $groups = $hostGroup->get($dto)->hostGroups;
    
  • Mass Operations: Use MassAddHostGroupDto, MassUpdateHostGroupDto, etc., for bulk actions.

3. Asynchronous Monitoring

  • Push Metrics/Events: Dispatch messages via Symfony Messenger:
    $bus->dispatch(new PushMetricMessage(
        key: 'app.user.login',
        value: 1,
        tags: ['env' => 'prod']
    ));
    
  • Transport Config: Customize in config/packages/zabbix_api.yaml:
    zabbix_api:
        messenger_transport: async  # Options: async, sync, false
    

4. Automatic Setup

  • Enable Auto-Provisioning:
    zabbix_api:
        setup_enabled: true
        app_name: 'MyApp'
        host_group: 'AppServers'
        dashboard_config_path: '%kernel.project_dir%/config/zabbix'
    
  • Trigger Setup: Dispatch EnsureZabbixSetupMessage manually if needed.

5. Error Handling

  • Retry Logic: The bundle auto-retrieves tokens on failure (max 1 retry).
  • Custom Exceptions: Catch ZabbixApiException for API errors:
    try {
        $history->getLatest(['12345']);
    } catch (ZabbixApiException $e) {
        $this->handleZabbixError($e);
    }
    

6. Low-Level Control

  • Direct Client Calls: Use ZabbixClientInterface for raw API access:
    $client->call(ZabbixAction::HOST_GET, ['output' => 'extend']);
    
  • Dynamic Actions: Use ActionServiceInterface for runtime method calls:
    $this->actionService->call(History::class, [
        'method' => 'get',
        'params' => ['itemids' => ['10084']]
    ]);
    

Gotchas and Tips

Pitfalls

  1. Token Cache Invalidation

    • Issue: If ZABBIX_AUTH_TTL is too short, frequent re-authentication may occur.
    • Fix: Set a reasonable TTL (e.g., 7200 for 2 hours) or disable caching (ZABBIX_AUTH_TTL=0).
  2. DTO Validation

    • Issue: Missing required fields in DTOs (e.g., hostid in CreateItemDto) cause silent failures.
    • Fix: Use IDE hints or validate DTOs manually:
      if (empty($dto->hostid)) {
          throw new \InvalidArgumentException('hostid is required');
      }
      
  3. Messenger Transport

    • Issue: Async transport may drop messages if the queue fails.
    • Fix: Monitor the zabbix_api_async queue or switch to sync for debugging:
      zabbix_api:
          messenger_transport: sync
      
  4. History Data Types

    • Issue: Incorrect HistoryTypeEnum (e.g., using NUMERIC_FLOAT for text data) returns empty results.
    • Fix: Map item types to correct enums (see History Data Types).
  5. Auto-Setup Conflicts

    • Issue: setup_enabled: true may overwrite existing hosts/items.
    • Fix: Exclude specific resources by configuring dashboard_config_path or overriding the EnsureZabbixSetupMessage handler.

Debugging Tips

  1. Enable API Logging Add to config/packages/monolog.yaml:

    handlers:
        zabbix_api:
            type: stream
            path: "%kernel.logs_dir%/zabbix_api.log"
            level: debug
            channels: ["zabbix_api"]
    

    Then enable the channel in ZabbixService:

    $this->logger->debug('Zabbix API call', ['params' => $params]);
    
  2. Raw API Responses Access raw responses via ZabbixClientInterface:

    $response = $client->call(ZabbixAction::HOST_GET, ['output' => 'extend']);
    $this->logger->debug('Raw response', ['data' => $response]);
    
  3. Token Debugging Check cached token location:

    $token = $this->tokenStorage->getToken();
    $this->logger->debug('Current token', ['token' => $token]);
    

Extension Points

  1. Custom Actions Extend the factory by implementing ActionInterface:

    class CustomAction implements ActionInterface {
        public function __invoke(ZabbixClientInterface $client): mixed {
            return $client->call(ZabbixAction::CUSTOM_ACTION, ['param' => 'value']);
        }
    }
    

    Register in services.yaml:

    BytesCommerce\ZabbixApi\ZabbixService:
        arguments:
            $actions:
                - BytesCommerce\ZabbixApi\Actions\CustomAction
    
  2. Override DTOs Create custom DTO classes extending the bundle’s DTOs to add validation or defaults:

    class CustomGetHostGroupDto extends GetHostGroupDto {
        public function __construct() {
            parent::__construct(output: 'extend', selectHosts: true);
        }
    }
    
  3. Messenger Handlers Extend PushMetricMessageHandler or PushEventMessageHandler to customize payload formatting:

    class CustomMetricHandler implements PushMetricMessageHandlerInterface {
        public function __invoke(PushMetricMessage $message): void {
            // Custom logic before sending to Zabbix
            $client->sendMetric($message->key, $message->value);
        }
    }
    

Configuration Quirks

  1. Environment Variables

    • Priority: .env.local > .env > config/packages/zabbix_api.yaml.
    • Fallback: Use ZABBIX_API_BASE_URI as the default; override in config if needed.
  2. Auto-Registration

    • Issue: Bundle may not auto-register if Symfony Flex is disabled.
    • Fix: Manually import in config/bundles.php:
      return [
          BytesCommerce\ZabbixApiBundle\ZabbixApiBundle::class => ['all' => true],
      ];
      
  3. PHP 8.3+ Features

    • **Readonly
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
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
christhompsontldr/laravel-inky
spatie/mailcoach-vapor