/*
 * Copyright 2016-2019, EnMasse authors.
 * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html).
 */
package io.enmasse.controller.standard;

import io.enmasse.amqp.Artemis;
import io.enmasse.amqp.SyncRequestClient;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.client.internal.readiness.Readiness;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

class BrokerStatusCollector {
    private static final Logger log = LoggerFactory.getLogger(BrokerStatusCollector.class);

    private final Kubernetes kubernetes;
    private final BrokerClientFactory brokerClientFactory;

    BrokerStatusCollector(Kubernetes kubernetes, BrokerClientFactory brokerClientFactory) {
        this.kubernetes = kubernetes;
        this.brokerClientFactory = brokerClientFactory;
    }

    long getQueueMessageCount(String queue, String clusterId) throws Exception {
        long totalMessageCount = 0;
        List<Pod> pods = kubernetes.listBrokers(clusterId);
        for (Pod broker : pods) {
            if (Readiness.isPodReady(broker)) {
                try (
                        SyncRequestClient brokerClient = brokerClientFactory.connectBrokerManagementClient(broker.getStatus().getPodIP(), 5673);
                        Artemis artemis = new Artemis(brokerClient);
                        ) {
                    long queueMessageCount = artemis.getQueueMessageCount(queue);
                    if (queueMessageCount < 0) {
                        // ARTEMIS-1982?
                        throw new IllegalStateException(String.format("Depth for queue '%s' on broker pod '%s' in cluster '%s' reported negative (%d)",
                                queue,
                                broker.getMetadata().getName(),
                                clusterId,
                                queueMessageCount));
                    }
                    totalMessageCount += queueMessageCount;
                }
            } else {
                log.info("Broker pod '{}' in cluster '{}' is not ready ({}), cannot get depth for queue '{}' at this time.",
                        broker.getMetadata().getName(),
                        clusterId,
                        broker.getStatus(),
                        queue);
            }
        }
        log.info("Queue '{}' on cluster '{}' ({} replica(s)) has depth: {}", queue,  clusterId, pods.size(), totalMessageCount);
        return totalMessageCount;
    }
}

@@ -2050,24 +2050,61 @@
         
-log.info
+throw new IllegalStateException(String.format
 (%22Broker
@@ -2109,18 +2109,18 @@
 er pod '
-%7B%7D
+%25s
 ' in clu
@@ -2125,18 +2125,18 @@
 luster '
-%7B%7D
+%25s
 ' is not
@@ -2143,18 +2143,18 @@
  ready (
-%7B%7D
+%25s
 ), canno
@@ -2176,18 +2176,18 @@
  queue '
-%7B%7D
+%25s
 ' at thi
@@ -2357,24 +2357,25 @@
       queue)
+)
 ;%0A          

Fix #2876: Do not consider broker pods that are offline drained (#2881)