BrokersBase.java 19.1 KB
Newer Older
M
Matteo Merli 已提交
1
/**
2 3 4 5 6 7 8
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
M
Matteo Merli 已提交
9
 *
10
 *   http://www.apache.org/licenses/LICENSE-2.0
M
Matteo Merli 已提交
11
 *
12 13 14 15 16 17
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
M
Matteo Merli 已提交
18
 */
19
package org.apache.pulsar.broker.admin.impl;
M
Matteo Merli 已提交
20

21
import static org.apache.pulsar.broker.service.BrokerService.BROKER_SERVICE_CONFIGURATION_PATH;
22 23

import java.util.List;
M
Matteo Merli 已提交
24
import java.util.Map;
25
import java.util.Optional;
M
Matteo Merli 已提交
26
import java.util.Set;
I
Ivan Kelly 已提交
27 28 29 30 31
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.TimeUnit;
M
Matteo Merli 已提交
32

33
import javax.ws.rs.DELETE;
M
Matteo Merli 已提交
34
import javax.ws.rs.GET;
35
import javax.ws.rs.POST;
M
Matteo Merli 已提交
36 37
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
I
Ivan Kelly 已提交
38 39
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.Suspended;
40
import javax.ws.rs.core.Response.Status;
M
Matteo Merli 已提交
41

42
import org.apache.bookkeeper.conf.ClientConfiguration;
43
import org.apache.bookkeeper.util.ZkUtils;
44
import org.apache.pulsar.broker.ServiceConfiguration;
45
import org.apache.pulsar.broker.admin.AdminResource;
46
import org.apache.pulsar.broker.loadbalance.LoadManager;
I
Ivan Kelly 已提交
47
import org.apache.pulsar.broker.namespace.NamespaceService;
48
import org.apache.pulsar.broker.service.BrokerService;
49 50
import org.apache.pulsar.broker.service.Subscription;
import org.apache.pulsar.broker.service.Topic;
51
import org.apache.pulsar.broker.web.RestException;
I
Ivan Kelly 已提交
52 53 54 55 56 57
import org.apache.pulsar.client.api.Message;
import org.apache.pulsar.client.api.MessageId;
import org.apache.pulsar.client.api.Producer;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.client.api.Reader;
import org.apache.pulsar.client.api.Schema;
58
import org.apache.pulsar.common.conf.InternalConfigurationData;
59 60 61
import org.apache.pulsar.common.policies.data.NamespaceOwnershipStatus;
import org.apache.pulsar.common.util.ObjectMapperFactory;
import org.apache.pulsar.zookeeper.ZooKeeperDataCache;
62 63
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
M
Matteo Merli 已提交
64 65 66
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

67 68
import com.google.common.collect.Maps;

M
Matteo Merli 已提交
69 70 71
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
72

L
lipenghui 已提交
73 74 75
/**
 * Broker admin base.
 */
76 77
public class BrokersBase extends AdminResource {
    private static final Logger LOG = LoggerFactory.getLogger(BrokersBase.class);
78
    private int serviceConfigZkVersion = -1;
79

M
Matteo Merli 已提交
80 81
    @GET
    @Path("/{cluster}")
82 83 84 85 86 87 88
    @ApiOperation(
        value = "Get the list of active brokers (web service addresses) in the cluster."
                + "If authorization is not enabled, any cluster name is valid.",
        response = String.class,
        responseContainer = "Set")
    @ApiResponses(
        value = {
89
            @ApiResponse(code = 307, message = "Current broker doesn't serve this cluster"),
90 91 92
            @ApiResponse(code = 401, message = "Authentication required"),
            @ApiResponse(code = 403, message = "This operation requires super-user access"),
            @ApiResponse(code = 404, message = "Cluster does not exist: cluster={clustername}") })
M
Matteo Merli 已提交
93 94 95 96 97 98
    public Set<String> getActiveBrokers(@PathParam("cluster") String cluster) throws Exception {
        validateSuperUserAccess();
        validateClusterOwnership(cluster);

        try {
            // Add Native brokers
99
            return pulsar().getLocalZkCache().getChildren(LoadManager.LOADBALANCE_BROKERS_ROOT);
M
Matteo Merli 已提交
100
        } catch (Exception e) {
101
            LOG.error("[{}] Failed to get active broker list: cluster={}", clientAppId(), cluster, e);
M
Matteo Merli 已提交
102 103 104 105 106
            throw new RestException(e);
        }
    }

    @GET
107
    @Path("/{clusterName}/{broker-webserviceurl}/ownedNamespaces")
M
Matteo Merli 已提交
108
    @ApiOperation(value = "Get the list of namespaces served by the specific broker", response = NamespaceOwnershipStatus.class, responseContainer = "Map")
109
    @ApiResponses(value = {
110
        @ApiResponse(code = 307, message = "Current broker doesn't serve the cluster"),
111 112
        @ApiResponse(code = 403, message = "Don't have admin permission"),
        @ApiResponse(code = 404, message = "Cluster doesn't exist") })
113
    public Map<String, NamespaceOwnershipStatus> getOwnedNamespaces(@PathParam("clusterName") String cluster,
114
            @PathParam("broker-webserviceurl") String broker) throws Exception {
M
Matteo Merli 已提交
115 116 117 118 119 120 121 122 123 124 125 126 127
        validateSuperUserAccess();
        validateClusterOwnership(cluster);
        validateBrokerName(broker);

        try {
            // now we validated that this is the broker specified in the request
            return pulsar().getNamespaceService().getOwnedNameSpacesStatus();
        } catch (Exception e) {
            LOG.error("[{}] Failed to get the namespace ownership status. cluster={}, broker={}", clientAppId(),
                    cluster, broker);
            throw new RestException(e);
        }
    }
128

129 130 131
    @POST
    @Path("/configuration/{configName}/{configValue}")
    @ApiOperation(value = "Update dynamic serviceconfiguration into zk only. This operation requires Pulsar super-user privileges.")
132 133 134 135 136 137
    @ApiResponses(value = {
        @ApiResponse(code = 204, message = "Service configuration updated successfully"),
        @ApiResponse(code = 403, message = "You don't have admin permission to update service-configuration"),
        @ApiResponse(code = 404, message = "Configuration not found"),
        @ApiResponse(code = 412, message = "Invalid dynamic-config value"),
        @ApiResponse(code = 500, message = "Internal server error")})
A
Ali Ahmed 已提交
138
    public void updateDynamicConfiguration(@PathParam("configName") String configName, @PathParam("configValue") String configValue) throws Exception {
139 140 141 142
        validateSuperUserAccess();
        updateDynamicConfigurationOnZk(configName, configValue);
    }

143 144 145 146 147 148 149 150 151 152 153 154
    @DELETE
    @Path("/configuration/{configName}")
    @ApiOperation(value = "Delete dynamic serviceconfiguration into zk only. This operation requires Pulsar super-user privileges.")
    @ApiResponses(value = { @ApiResponse(code = 204, message = "Service configuration updated successfully"),
            @ApiResponse(code = 403, message = "You don't have admin permission to update service-configuration"),
            @ApiResponse(code = 412, message = "Invalid dynamic-config value"),
            @ApiResponse(code = 500, message = "Internal server error") })
    public void deleteDynamicConfiguration(@PathParam("configName") String configName) throws Exception {
        validateSuperUserAccess();
        deleteDynamicConfigurationOnZk(configName);
    }
    
155 156 157
    @GET
    @Path("/configuration/values")
    @ApiOperation(value = "Get value of all dynamic configurations' value overridden on local config")
158
    @ApiResponses(value = {
159
        @ApiResponse(code = 403, message = "You don't have admin permission to view configuration"),
160 161
        @ApiResponse(code = 404, message = "Configuration not found"),
        @ApiResponse(code = 500, message = "Internal server error")})
162
    public Map<String, String> getAllDynamicConfigurations() throws Exception {
163 164
        validateSuperUserAccess();

165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
        ZooKeeperDataCache<Map<String, String>> dynamicConfigurationCache = pulsar().getBrokerService()
                .getDynamicConfigurationCache();
        Map<String, String> configurationMap = null;
        try {
            configurationMap = dynamicConfigurationCache.get(BROKER_SERVICE_CONFIGURATION_PATH)
                    .orElseThrow(() -> new RestException(Status.NOT_FOUND, "Couldn't find configuration in zk"));
        } catch (RestException e) {
            LOG.error("[{}] couldn't find any configuration in zk {}", clientAppId(), e.getMessage(), e);
            throw e;
        } catch (Exception e) {
            LOG.error("[{}] Failed to retrieve configuration from zk {}", clientAppId(), e.getMessage(), e);
            throw new RestException(e);
        }
        return configurationMap;
    }

    @GET
    @Path("/configuration")
    @ApiOperation(value = "Get all updatable dynamic configurations's name")
184 185
    @ApiResponses(value = {
            @ApiResponse(code = 403, message = "You don't have admin permission to get configuration")})
186
    public List<String> getDynamicConfigurationName() {
187
        validateSuperUserAccess();
188
        return BrokerService.getDynamicConfiguration();
189
    }
190

191 192 193 194 195 196 197 198 199
    @GET
    @Path("/configuration/runtime")
    @ApiOperation(value = "Get all runtime configurations. This operation requires Pulsar super-user privileges.")
    @ApiResponses(value = { @ApiResponse(code = 403, message = "Don't have admin permission") })
    public Map<String, String> getRuntimeConfiguration() {
        validateSuperUserAccess();
        return pulsar().getBrokerService().getRuntimeConfiguration();
    }

200 201 202
    /**
     * if {@link ServiceConfiguration}-field is allowed to be modified dynamically, update configuration-map into zk, so
     * all other brokers get the watch and can see the change and take appropriate action on the change.
203
     *
204 205 206 207 208 209 210
     * @param configName
     *            : configuration key
     * @param configValue
     *            : configuration value
     */
    private synchronized void updateDynamicConfigurationOnZk(String configName, String configValue) {
        try {
211 212 213 214
            if (!BrokerService.validateDynamicConfiguration(configName, configValue)) {
                throw new RestException(Status.PRECONDITION_FAILED, " Invalid dynamic-config value");
            }
            if (BrokerService.isDynamicConfiguration(configName)) {
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
                ZooKeeperDataCache<Map<String, String>> dynamicConfigurationCache = pulsar().getBrokerService()
                        .getDynamicConfigurationCache();
                Map<String, String> configurationMap = dynamicConfigurationCache.get(BROKER_SERVICE_CONFIGURATION_PATH)
                        .orElse(null);
                if (configurationMap != null) {
                    configurationMap.put(configName, configValue);
                    byte[] content = ObjectMapperFactory.getThreadLocal().writeValueAsBytes(configurationMap);
                    dynamicConfigurationCache.invalidate(BROKER_SERVICE_CONFIGURATION_PATH);
                    serviceConfigZkVersion = localZk()
                            .setData(BROKER_SERVICE_CONFIGURATION_PATH, content, serviceConfigZkVersion).getVersion();
                } else {
                    configurationMap = Maps.newHashMap();
                    configurationMap.put(configName, configValue);
                    byte[] content = ObjectMapperFactory.getThreadLocal().writeValueAsBytes(configurationMap);
                    ZkUtils.createFullPathOptimistic(localZk(), BROKER_SERVICE_CONFIGURATION_PATH, content,
                            ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                }
                LOG.info("[{}] Updated Service configuration {}/{}", clientAppId(), configName, configValue);
            } else {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("[{}] Can't update non-dynamic configuration {}/{}", clientAppId(), configName,
                            configValue);
                }
                throw new RestException(Status.PRECONDITION_FAILED, " Can't update non-dynamic configuration");
            }
        } catch (RestException re) {
            throw re;
        } catch (Exception ie) {
            LOG.error("[{}] Failed to update configuration {}/{}, {}", clientAppId(), configName, configValue,
                    ie.getMessage(), ie);
            throw new RestException(ie);
        }
    }

249 250 251
    @GET
    @Path("/internal-configuration")
    @ApiOperation(value = "Get the internal configuration data", response = InternalConfigurationData.class)
252
    @ApiResponses(value = { @ApiResponse(code = 403, message = "Don't have admin permission") })
253
    public InternalConfigurationData getInternalConfigurationData() {
254
        validateSuperUserAccess();
255
        return pulsar().getInternalConfigurationData();
256 257
    }

I
Ivan Kelly 已提交
258 259 260
    @GET
    @Path("/health")
    @ApiOperation(value = "Run a healthcheck against the broker")
261 262 263 264 265
    @ApiResponses(value = {
        @ApiResponse(code = 200, message = "Everything is OK"),
        @ApiResponse(code = 403, message = "Don't have admin permission"),
        @ApiResponse(code = 404, message = "Cluster doesn't exist"),
        @ApiResponse(code = 500, message = "Internal server error")})
I
Ivan Kelly 已提交
266 267 268 269 270 271 272 273 274
    public void healthcheck(@Suspended AsyncResponse asyncResponse) throws Exception {
        validateSuperUserAccess();
        String heartbeatNamespace = NamespaceService.getHeartbeatNamespace(
                pulsar().getAdvertisedAddress(), pulsar().getConfiguration());
        String topic = String.format("persistent://%s/healthcheck", heartbeatNamespace);

        PulsarClient client = pulsar().getClient();

        String messageStr = UUID.randomUUID().toString();
275
        // create non-partitioned topic manually and close the previous reader if present.
276
        try {
277
            pulsar().getBrokerService().getTopic(topic, true).get().ifPresent(t -> {
278 279 280 281 282 283 284
                for (Subscription value : t.getSubscriptions().values()) {
                    try {
                        value.deleteForcefully();
                    } catch (Exception e) {
                        LOG.warn("Failed to delete previous subscription {} for health check", value.getName(), e);
                    }
                }
285
            });
286
        } catch (Exception e) {
287
            LOG.warn("Failed to try to delete subscriptions for health check", e);
288
        }
I
Ivan Kelly 已提交
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
        CompletableFuture<Producer<String>> producerFuture =
            client.newProducer(Schema.STRING).topic(topic).createAsync();
        CompletableFuture<Reader<String>> readerFuture = client.newReader(Schema.STRING)
            .topic(topic).startMessageId(MessageId.latest).createAsync();

        CompletableFuture<Void> completePromise = new CompletableFuture<>();

        CompletableFuture.allOf(producerFuture, readerFuture).whenComplete(
                (ignore, exception) -> {
                    if (exception != null) {
                        completePromise.completeExceptionally(exception);
                    } else {
                        producerFuture.thenCompose((producer) -> producer.sendAsync(messageStr))
                            .whenComplete((ignore2, exception2) -> {
                                    if (exception2 != null) {
                                        completePromise.completeExceptionally(exception2);
                                    }
                                });

                        healthcheckReadLoop(readerFuture, completePromise, messageStr);

                        // timeout read loop after 10 seconds
                        ScheduledFuture<?> timeout = pulsar().getExecutor().schedule(() -> {
                                completePromise.completeExceptionally(new TimeoutException("Timed out reading"));
                            }, 10, TimeUnit.SECONDS);
                        // don't leave timeout dangling
                        completePromise.whenComplete((ignore2, exception2) -> {
                                timeout.cancel(false);
                            });
                    }
                });

        completePromise.whenComplete((ignore, exception) -> {
                producerFuture.thenAccept((producer) -> {
                        producer.closeAsync().whenComplete((ignore2, exception2) -> {
                                if (exception2 != null) {
                                    LOG.warn("Error closing producer for healthcheck", exception2);
                                }
                            });
                    });
                readerFuture.thenAccept((reader) -> {
                        reader.closeAsync().whenComplete((ignore2, exception2) -> {
                                if (exception2 != null) {
                                    LOG.warn("Error closing reader for healthcheck", exception2);
                                }
                            });
                    });
                if (exception != null) {
                    asyncResponse.resume(new RestException(exception));
                } else {
                    asyncResponse.resume("ok");
                }
            });
    }

    private void healthcheckReadLoop(CompletableFuture<Reader<String>> readerFuture,
                                     CompletableFuture<?> completablePromise,
                                     String messageStr) {
        readerFuture.thenAccept((reader) -> {
                CompletableFuture<Message<String>> readFuture = reader.readNextAsync()
                    .whenComplete((m, exception) -> {
                            if (exception != null) {
                                completablePromise.completeExceptionally(exception);
                            } else if (m.getValue().equals(messageStr)) {
                                completablePromise.complete(null);
                            } else {
                                healthcheckReadLoop(readerFuture, completablePromise, messageStr);
                            }
                        });
            });
    }
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
    
    private synchronized void deleteDynamicConfigurationOnZk(String configName) {
        try {
            if (BrokerService.isDynamicConfiguration(configName)) {
                ZooKeeperDataCache<Map<String, String>> dynamicConfigurationCache = pulsar().getBrokerService()
                        .getDynamicConfigurationCache();
                Map<String, String> configurationMap = dynamicConfigurationCache.get(BROKER_SERVICE_CONFIGURATION_PATH)
                        .orElse(null);
                if (configurationMap != null && configurationMap.containsKey(configName)) {
                    configurationMap.remove(configName);
                    byte[] content = ObjectMapperFactory.getThreadLocal().writeValueAsBytes(configurationMap);
                    dynamicConfigurationCache.invalidate(BROKER_SERVICE_CONFIGURATION_PATH);
                    serviceConfigZkVersion = localZk()
                            .setData(BROKER_SERVICE_CONFIGURATION_PATH, content, serviceConfigZkVersion).getVersion();
                }
                LOG.info("[{}] Deleted Service configuration {}", clientAppId(), configName);
            } else {
                if (LOG.isDebugEnabled()) {
378
                    LOG.debug("[{}] Can't update non-dynamic configuration {}", clientAppId(), configName);
379 380 381 382 383 384 385 386 387 388
                }
                throw new RestException(Status.PRECONDITION_FAILED, " Can't update non-dynamic configuration");
            }
        } catch (RestException re) {
            throw re;
        } catch (Exception ie) {
            LOG.error("[{}] Failed to update configuration {}, {}", clientAppId(), configName, ie.getMessage(), ie);
            throw new RestException(ie);
        }
    }
M
Matteo Merli 已提交
389
}
I
Ivan Kelly 已提交
390