TopicCommands.java 10.9 KB
Newer Older
Z
zengqiao 已提交
1 2
package com.xiaojukeji.kafka.manager.service.utils;

Z
zengqiao 已提交
3
import com.alibaba.fastjson.JSON;
Z
zengqiao 已提交
4 5 6 7 8 9 10 11 12 13 14
import com.xiaojukeji.kafka.manager.common.constant.Constant;
import com.xiaojukeji.kafka.manager.common.entity.ResultStatus;
import com.xiaojukeji.kafka.manager.common.entity.pojo.ClusterDO;
import kafka.admin.AdminOperationException;
import kafka.admin.AdminUtils;
import kafka.admin.BrokerMetadata;
import kafka.common.TopicAndPartition;
import kafka.utils.ZkUtils;
import org.I0Itec.zkclient.exception.ZkNodeExistsException;
import org.apache.kafka.common.errors.*;
import org.apache.kafka.common.security.JaasUtils;
Z
zengqiao 已提交
15 16
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Z
zengqiao 已提交
17 18 19 20 21 22 23 24 25 26 27
import scala.Option;
import scala.collection.JavaConversions;
import scala.collection.Seq;

import java.util.*;

/**
 * @author zengqiao
 * @date 20/4/22
 */
public class TopicCommands {
Z
zengqiao 已提交
28 29 30
    private static final Logger LOGGER = LoggerFactory.getLogger(TopicCommands.class);


Z
zengqiao 已提交
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
    public static ResultStatus createTopic(ClusterDO clusterDO,
                                           String topicName,
                                           Integer partitionNum,
                                           Integer replicaNum,
                                           List<Integer> brokerIdList,
                                           Properties config) {
        ZkUtils zkUtils = null;
        try {
            zkUtils = ZkUtils.apply(
                    clusterDO.getZookeeper(),
                    Constant.DEFAULT_SESSION_TIMEOUT_UNIT_MS,
                    Constant.DEFAULT_SESSION_TIMEOUT_UNIT_MS,
                    JaasUtils.isZkSecurityEnabled()
            );

            // 生成分配策略
Z
zengqiao 已提交
47
            scala.collection.Map<Object, Seq<Object>> replicaAssignment =
Z
zengqiao 已提交
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
                    AdminUtils.assignReplicasToBrokers(
                            convert2BrokerMetadataSeq(brokerIdList),
                            partitionNum,
                            replicaNum,
                            randomFixedStartIndex(),
                            -1
            );

            // 写ZK
            AdminUtils.createOrUpdateTopicPartitionAssignmentPathInZK(
                    zkUtils,
                    topicName,
                    replicaAssignment,
                    config,
                    false
            );
        } catch (NullPointerException e) {
Z
zengqiao 已提交
65 66
            LOGGER.error("class=TopicCommands||method=createTopic||errMsg={}||clusterDO={}||topicName={}||partitionNum={}||replicaNum={}||brokerIdList={}||config={}",
                    e.getMessage(), clusterDO, topicName, partitionNum, replicaNum, JSON.toJSONString(brokerIdList), config, e);
Z
zengqiao 已提交
67 68
            return ResultStatus.TOPIC_OPERATION_PARAM_NULL_POINTER;
        } catch (InvalidPartitionsException e) {
Z
zengqiao 已提交
69 70
            LOGGER.error("class=TopicCommands||method=createTopic||errMsg={}||clusterDO={}||topicName={}||partitionNum={}||replicaNum={}||brokerIdList={}||config={}",
                    e.getMessage(), clusterDO, topicName,partitionNum,replicaNum,JSON.toJSONString(brokerIdList),config, e);
Z
zengqiao 已提交
71 72
            return ResultStatus.TOPIC_OPERATION_PARTITION_NUM_ILLEGAL;
        } catch (InvalidReplicationFactorException e) {
Z
zengqiao 已提交
73 74
            LOGGER.error("class=TopicCommands||method=createTopic||errMsg={}||clusterDO={}||topicName={}||partitionNum={}||replicaNum={}||brokerIdList={}||config={}",
                    e.getMessage(), clusterDO, topicName,partitionNum,replicaNum,JSON.toJSONString(brokerIdList),config, e);
Z
zengqiao 已提交
75 76
            return ResultStatus.BROKER_NUM_NOT_ENOUGH;
        } catch (TopicExistsException | ZkNodeExistsException e) {
Z
zengqiao 已提交
77 78
            LOGGER.error("class=TopicCommands||method=createTopic||errMsg={}||clusterDO={}||topicName={}||partitionNum={}||replicaNum={}||brokerIdList={}||config={}",
                    e.getMessage(), clusterDO, topicName,partitionNum,replicaNum,JSON.toJSONString(brokerIdList),config, e);
Z
zengqiao 已提交
79 80
            return ResultStatus.TOPIC_OPERATION_TOPIC_EXISTED;
        } catch (InvalidTopicException e) {
Z
zengqiao 已提交
81 82
            LOGGER.error("class=TopicCommands||method=createTopic||errMsg={}||clusterDO={}||topicName={}||partitionNum={}||replicaNum={}||brokerIdList={}||config={}",
                    e.getMessage(), clusterDO, topicName,partitionNum,replicaNum,JSON.toJSONString(brokerIdList),config, e);
Z
zengqiao 已提交
83 84
            return ResultStatus.TOPIC_OPERATION_TOPIC_NAME_ILLEGAL;
        } catch (Throwable t) {
Z
zengqiao 已提交
85 86
            LOGGER.error("class=TopicCommands||method=createTopic||errMsg={}||clusterDO={}||topicName={}||partitionNum={}||replicaNum={}||brokerIdList={}||config={}",
                    t.getMessage(), clusterDO, topicName,partitionNum,replicaNum,JSON.toJSONString(brokerIdList),config, t);
Z
zengqiao 已提交
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
            return ResultStatus.TOPIC_OPERATION_UNKNOWN_ERROR;
        } finally {
            if (zkUtils != null) {
                zkUtils.close();
            }
        }
        return ResultStatus.SUCCESS;
    }

    public static ResultStatus deleteTopic(ClusterDO clusterDO, String topicName) {
        ZkUtils zkUtils = null;
        try {
            zkUtils = ZkUtils.apply(
                    clusterDO.getZookeeper(),
                    Constant.DEFAULT_SESSION_TIMEOUT_UNIT_MS,
                    Constant.DEFAULT_SESSION_TIMEOUT_UNIT_MS,
                    JaasUtils.isZkSecurityEnabled()
            );
            AdminUtils.deleteTopic(zkUtils, topicName);
        } catch (UnknownTopicOrPartitionException e) {
Z
zengqiao 已提交
107
            LOGGER.error("class=TopicCommands||method=deleteTopic||errMsg={}||clusterDO={}||topicName={}", e.getMessage(), clusterDO, topicName, e);
Z
zengqiao 已提交
108 109
            return ResultStatus.TOPIC_OPERATION_UNKNOWN_TOPIC_PARTITION;
        } catch (ZkNodeExistsException e) {
Z
zengqiao 已提交
110
            LOGGER.error("class=TopicCommands||method=deleteTopic||errMsg={}||clusterDO={}||topicName={}", e.getMessage(), clusterDO, topicName, e);
Z
zengqiao 已提交
111 112
            return ResultStatus.TOPIC_OPERATION_TOPIC_IN_DELETING;
        } catch (Throwable t) {
Z
zengqiao 已提交
113
            LOGGER.error("class=TopicCommands||method=deleteTopic||errMsg={}||clusterDO={}||topicName={}", t.getMessage(), clusterDO, topicName, t);
Z
zengqiao 已提交
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
            return ResultStatus.TOPIC_OPERATION_UNKNOWN_ERROR;
        } finally {
            if (zkUtils != null) {
                zkUtils.close();
            }
        }
        return ResultStatus.SUCCESS;
    }

    public static ResultStatus modifyTopicConfig(ClusterDO clusterDO, String topicName, Properties config) {
        ZkUtils zkUtils = null;
        try {
            zkUtils = ZkUtils.apply(
                    clusterDO.getZookeeper(),
                    Constant.DEFAULT_SESSION_TIMEOUT_UNIT_MS,
                    Constant.DEFAULT_SESSION_TIMEOUT_UNIT_MS,
                    JaasUtils.isZkSecurityEnabled()
            );
            AdminUtils.changeTopicConfig(zkUtils, topicName, config);
        } catch (AdminOperationException e) {
Z
zengqiao 已提交
134
            LOGGER.error("class=TopicCommands||method=modifyTopicConfig||errMsg={}||clusterDO={}||topicName={}||config={}", e.getMessage(), clusterDO, topicName,config, e);
Z
zengqiao 已提交
135 136
            return ResultStatus.TOPIC_OPERATION_UNKNOWN_TOPIC_PARTITION;
        } catch (InvalidConfigurationException e) {
Z
zengqiao 已提交
137
            LOGGER.error("class=TopicCommands||method=modifyTopicConfig||errMsg={}||clusterDO={}||topicName={}||config={}", e.getMessage(), clusterDO, topicName,config, e);
Z
zengqiao 已提交
138 139
            return ResultStatus.TOPIC_OPERATION_TOPIC_CONFIG_ILLEGAL;
        } catch (Throwable t) {
Z
zengqiao 已提交
140
            LOGGER.error("class=TopicCommands||method=modifyTopicConfig||errMsg={}||clusterDO={}||topicName={}||config={}", t.getMessage(), clusterDO, topicName,config, t);
Z
zengqiao 已提交
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
            return ResultStatus.TOPIC_OPERATION_UNKNOWN_ERROR;
        } finally {
            if (zkUtils != null) {
                zkUtils.close();
            }
        }

        return ResultStatus.SUCCESS;
    }

    public static ResultStatus expandTopic(ClusterDO clusterDO,
                                           String topicName,
                                           Integer partitionNum,
                                           List<Integer> brokerIdList) {
        ZkUtils zkUtils = null;
        try {
            zkUtils = ZkUtils.apply(
                    clusterDO.getZookeeper(),
                    Constant.DEFAULT_SESSION_TIMEOUT_UNIT_MS,
                    Constant.DEFAULT_SESSION_TIMEOUT_UNIT_MS,
                    JaasUtils.isZkSecurityEnabled()
            );

            // 已有分区的分配策略
            scala.collection.mutable.Map<TopicAndPartition, Seq<Object>> existingAssignScalaMap =
                    zkUtils.getReplicaAssignmentForTopics(JavaConversions.asScalaBuffer(Arrays.asList(topicName)));


            // 新增分区的分配策略
            Map<Object, Seq<Object>> newAssignMap = JavaConversions.asJavaMap(
                    AdminUtils.assignReplicasToBrokers(
                            convert2BrokerMetadataSeq(brokerIdList),
                            partitionNum,
                            existingAssignScalaMap.head()._2().size(),
                            randomFixedStartIndex(),
                            existingAssignScalaMap.size()
                    )
            );

Z
zengqiao 已提交
180
            Map<TopicAndPartition, Seq<Object>> existingAssignJavaMap =
Z
zengqiao 已提交
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
                    JavaConversions.asJavaMap(existingAssignScalaMap);
            // 新增分区的分配策略和旧的分配策略合并
            Map<Object, Seq<Object>> targetMap = new HashMap<>();
            for (Map.Entry<TopicAndPartition, Seq<Object>> entry : existingAssignJavaMap.entrySet()) {
                targetMap.put(entry.getKey().partition(), entry.getValue());
            }
            for (Map.Entry<Object, Seq<Object>> entry : newAssignMap.entrySet()) {
                targetMap.put(entry.getKey(), entry.getValue());
            }

            // 更新ZK上的assign
            AdminUtils.createOrUpdateTopicPartitionAssignmentPathInZK(
                    zkUtils,
                    topicName,
                    JavaConversions.asScalaMap(targetMap),
                    null,
                    true
            );
        } catch (Throwable t) {
Z
zengqiao 已提交
200 201
            LOGGER.error("class=TopicCommands||method=expandTopic||errMsg={}||clusterDO={}||topicName={}||partitionNum={}||brokerIdList={}"
                    , t.getMessage(), clusterDO, topicName, partitionNum, JSON.toJSONString(brokerIdList), t);
Z
zengqiao 已提交
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
            return ResultStatus.TOPIC_OPERATION_UNKNOWN_ERROR;
        } finally {
            if (zkUtils != null) {
                zkUtils.close();
            }
        }

        return ResultStatus.SUCCESS;
    }

    private static Seq<BrokerMetadata> convert2BrokerMetadataSeq(List<Integer> brokerIdList) {
        List<BrokerMetadata> brokerMetadataList = new ArrayList<>();
        for (Integer brokerId: brokerIdList) {
            brokerMetadataList.add(new BrokerMetadata(brokerId, Option.<String>empty()));
        }
        return JavaConversions.asScalaBuffer(brokerMetadataList).toSeq();
    }

    /**
     * 生成一个伪随机数, 即随机选择一个起始位置的Broker
     */
    private static int randomFixedStartIndex() {
        return (int) System.currentTimeMillis() % 1013;
    }
}