KafkaAclServiceImpl.java 11.9 KB
Newer Older
Z
zengqiao 已提交
1 2 3 4 5
package com.xiaojukeji.know.streaming.km.core.service.acl.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.didiglobal.logi.log.ILog;
import com.didiglobal.logi.log.LogFactory;
Z
zengqiao 已提交
6
import com.xiaojukeji.know.streaming.km.common.bean.entity.cluster.ClusterPhy;
Z
zengqiao 已提交
7 8 9 10 11 12 13
import com.xiaojukeji.know.streaming.km.common.bean.entity.param.cluster.ClusterPhyParam;
import com.xiaojukeji.know.streaming.km.common.bean.entity.param.VersionItemParam;
import com.xiaojukeji.know.streaming.km.common.bean.entity.result.Result;
import com.xiaojukeji.know.streaming.km.common.bean.entity.result.ResultStatus;
import com.xiaojukeji.know.streaming.km.common.bean.po.KafkaAclPO;
import com.xiaojukeji.know.streaming.km.common.constant.MsgConstant;
import com.xiaojukeji.know.streaming.km.common.constant.KafkaConstant;
14
import com.xiaojukeji.know.streaming.km.common.converter.KafkaAclConverter;
Z
zengqiao 已提交
15
import com.xiaojukeji.know.streaming.km.common.enums.cluster.ClusterAuthTypeEnum;
Z
zengqiao 已提交
16 17 18 19
import com.xiaojukeji.know.streaming.km.common.enums.version.VersionItemTypeEnum;
import com.xiaojukeji.know.streaming.km.common.exception.VCHandlerNotExistException;
import com.xiaojukeji.know.streaming.km.common.utils.ValidateUtils;
import com.xiaojukeji.know.streaming.km.core.service.acl.KafkaAclService;
Z
zengqiao 已提交
20
import com.xiaojukeji.know.streaming.km.core.service.cluster.ClusterPhyService;
Z
zengqiao 已提交
21
import com.xiaojukeji.know.streaming.km.core.service.version.BaseKafkaVersionControlService;
Z
zengqiao 已提交
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
import com.xiaojukeji.know.streaming.km.persistence.kafka.KafkaAdminClient;
import com.xiaojukeji.know.streaming.km.persistence.kafka.KafkaAdminZKClient;
import com.xiaojukeji.know.streaming.km.persistence.mysql.KafkaAclDAO;
import kafka.security.authorizer.AclAuthorizer;
import kafka.zk.KafkaZkClient;
import kafka.zk.ZkAclStore;
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.DescribeAclsOptions;
import org.apache.kafka.clients.admin.DescribeAclsResult;
import org.apache.kafka.common.acl.*;
import org.apache.kafka.common.resource.PatternType;
import org.apache.kafka.common.resource.ResourcePattern;
import org.apache.kafka.common.resource.ResourceType;
import org.apache.kafka.common.security.auth.KafkaPrincipal;
import org.apache.kafka.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
38
import org.springframework.dao.DuplicateKeyException;
Z
zengqiao 已提交
39 40 41
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
42 43 44
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
Z
zengqiao 已提交
45 46 47 48 49 50 51

import scala.jdk.javaapi.CollectionConverters;

import static com.xiaojukeji.know.streaming.km.common.enums.version.VersionEnum.*;


@Service
Z
zengqiao 已提交
52
public class KafkaAclServiceImpl extends BaseKafkaVersionControlService implements KafkaAclService {
Z
zengqiao 已提交
53 54 55 56 57 58 59 60 61 62 63 64 65
    private static final ILog log = LogFactory.getLog(KafkaAclServiceImpl.class);

    private static final String ACL_GET_FROM_KAFKA    = "getAclFromKafka";

    @Autowired
    private KafkaAclDAO kafkaAclDAO;

    @Autowired
    private KafkaAdminClient kafkaAdminClient;

    @Autowired
    private KafkaAdminZKClient kafkaAdminZKClient;

Z
zengqiao 已提交
66 67 68
    @Autowired
    private ClusterPhyService clusterPhyService;

Z
zengqiao 已提交
69 70 71 72 73 74 75 76 77 78 79 80
    @Override
    protected VersionItemTypeEnum getVersionItemType() {
        return VersionItemTypeEnum.SERVICE_OP_ACL;
    }

    @PostConstruct
    private void init() {
        registerVCHandler(ACL_GET_FROM_KAFKA,     V_0_10_0_0, V_2_8_0, "getAclByZKClient",          this::getAclByZKClient);
        registerVCHandler(ACL_GET_FROM_KAFKA,     V_2_8_0, V_MAX,      "getAclByKafkaClient",       this::getAclByKafkaClient);
    }

    @Override
81
    public Result<List<AclBinding>> getDataFromKafka(ClusterPhy clusterPhy) {
Z
zengqiao 已提交
82
        try {
83 84 85 86 87 88
            Result<List<AclBinding>> dataResult = (Result<List<AclBinding>>) versionControlService.doHandler(getVersionItemType(), getMethodName(clusterPhy.getId(), ACL_GET_FROM_KAFKA), new ClusterPhyParam(clusterPhy.getId()));
            if (dataResult.failed()) {
                Result.buildFromIgnoreData(dataResult);
            }

            return Result.buildSuc(dataResult.getData());
Z
zengqiao 已提交
89 90 91 92 93
        } catch (VCHandlerNotExistException e) {
            return Result.buildFailure(e.getResultStatus());
        }
    }

94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
    @Override
    public void writeToDB(Long clusterPhyId, List<AclBinding> dataList) {
        Map<String, KafkaAclPO> dbPOMap = this.getKafkaAclFromDB(clusterPhyId).stream().collect(Collectors.toMap(KafkaAclPO::getUniqueField, Function.identity()));

        long now = System.currentTimeMillis();
        for (AclBinding aclBinding: dataList) {
            KafkaAclPO newPO = KafkaAclConverter.convert2KafkaAclPO(clusterPhyId, aclBinding, now);
            KafkaAclPO oldPO = dbPOMap.remove(newPO.getUniqueField());
            if (oldPO == null) {
                // 新增的ACL
                this.insertAndIgnoreDuplicate(newPO);
            }

            // 不需要update
        }

        // 删除已经不存在的
        for (KafkaAclPO dbPO: dbPOMap.values()) {
            kafkaAclDAO.deleteById(dbPO);
        }
    }

    @Override
    public int deleteInDBByKafkaClusterId(Long clusterPhyId) {
        LambdaQueryWrapper<KafkaAclPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(KafkaAclPO::getClusterPhyId, clusterPhyId);

        return kafkaAclDAO.delete(lambdaQueryWrapper);
    }

Z
zengqiao 已提交
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
    @Override
    public List<KafkaAclPO> getKafkaAclFromDB(Long clusterPhyId) {
        LambdaQueryWrapper<KafkaAclPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(KafkaAclPO::getClusterPhyId, clusterPhyId);
        queryWrapper.orderByDesc(KafkaAclPO::getUpdateTime);
        return kafkaAclDAO.selectList(queryWrapper);
    }

    @Override
    public Integer countKafkaAclFromDB(Long clusterPhyId) {
        LambdaQueryWrapper<KafkaAclPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(KafkaAclPO::getClusterPhyId, clusterPhyId);
        return kafkaAclDAO.selectCount(queryWrapper);
    }

    @Override
    public Integer countResTypeAndDistinctFromDB(Long clusterPhyId, ResourceType resourceType) {
        LambdaQueryWrapper<KafkaAclPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(KafkaAclPO::getClusterPhyId, clusterPhyId);
        lambdaQueryWrapper.eq(KafkaAclPO::getResourceType, resourceType.code());
        lambdaQueryWrapper.ne(KafkaAclPO::getResourceName, "*"); // 等于*的不做统计

        List<KafkaAclPO> poList = kafkaAclDAO.selectList(lambdaQueryWrapper);
        if (ValidateUtils.isEmptyList(poList)) {
            return 0;
        }

151
        return (int)poList.stream().map(KafkaAclPO::getResourceName).distinct().count();
Z
zengqiao 已提交
152 153 154 155 156 157 158 159 160 161 162 163 164
    }

    @Override
    public Integer countKafkaUserAndDistinctFromDB(Long clusterPhyId) {
        LambdaQueryWrapper<KafkaAclPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(KafkaAclPO::getClusterPhyId, clusterPhyId);
        lambdaQueryWrapper.ne(KafkaAclPO::getPrincipal, new KafkaPrincipal(KafkaPrincipal.USER_TYPE, "*").toString()); // 等于*的不做统计

        List<KafkaAclPO> poList = kafkaAclDAO.selectList(lambdaQueryWrapper);
        if (ValidateUtils.isEmptyList(poList)) {
            return 0;
        }

165
        return (int)poList.stream().map(KafkaAclPO::getPrincipal).distinct().count();
Z
zengqiao 已提交
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
    }

    @Override
    public List<KafkaAclPO> getTopicAclFromDB(Long clusterPhyId, String topicName) {
        // Topic自身 & Topic为*的情况
        LambdaQueryWrapper<KafkaAclPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(KafkaAclPO::getClusterPhyId, clusterPhyId);
        queryWrapper.eq(KafkaAclPO::getResourceType, ResourceType.TOPIC.code());
        queryWrapper.and(qw -> qw.eq(KafkaAclPO::getResourceName, topicName).or().eq(KafkaAclPO::getResourceName, "*"));

        return kafkaAclDAO.selectList(queryWrapper);
    }

    /**************************************************** private method ****************************************************/

    private Result<List<AclBinding>> getAclByZKClient(VersionItemParam itemParam){
        ClusterPhyParam param = (ClusterPhyParam) itemParam;

        List<AclBinding> aclList = new ArrayList<>();
        for (ZkAclStore store: CollectionConverters.asJava(ZkAclStore.stores())) {
            Result<List<AclBinding>> rl = this.getSpecifiedTypeAclByZKClient(param.getClusterPhyId(), store.patternType());
            if (rl.failed()) {
188
                return Result.buildFromIgnoreData(rl);
Z
zengqiao 已提交
189 190 191 192 193 194 195 196 197 198 199
            }

            aclList.addAll(rl.getData());
        }

        return Result.buildSuc(aclList);
    }

    private Result<List<AclBinding>> getAclByKafkaClient(VersionItemParam itemParam) {
        ClusterPhyParam param = (ClusterPhyParam) itemParam;
        try {
Z
zengqiao 已提交
200 201 202 203 204 205 206 207 208 209 210 211
            // 获取集群
            ClusterPhy clusterPhy = clusterPhyService.getClusterByCluster(param.getClusterPhyId());
            if (clusterPhy == null) {
                return Result.buildFromRSAndMsg(ResultStatus.CLUSTER_NOT_EXIST, MsgConstant.getClusterPhyNotExist(param.getClusterPhyId()));
            }

            // 判断是否开启认证
            if (!ClusterAuthTypeEnum.enableAuth(clusterPhy.getAuthType())) {
                log.warn("method=getAclByKafkaClient||clusterPhyId={}||msg=not open auth and ignore get acls", clusterPhy.getId());
                return Result.buildSuc(new ArrayList<>());
            }

Z
zengqiao 已提交
212 213 214 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
            AdminClient adminClient = kafkaAdminClient.getClient(param.getClusterPhyId());

            DescribeAclsResult describeAclsResult =
                    adminClient.describeAcls(AclBindingFilter.ANY, new DescribeAclsOptions().timeoutMs(KafkaConstant.ADMIN_CLIENT_REQUEST_TIME_OUT_UNIT_MS));

            return Result.buildSuc(new ArrayList<>(describeAclsResult.values().get()));
        } catch (Exception e) {
            log.error("method=getAclByKafkaClient||clusterPhyId={}||errMsg={}", param.getClusterPhyId(), e.getMessage());

            return Result.buildFromRSAndMsg(ResultStatus.KAFKA_OPERATE_FAILED, e.getMessage());
        }
    }

    private Result<List<AclBinding>> getSpecifiedTypeAclByZKClient(Long clusterPhyId, PatternType patternType) {
        List<AclBinding> kafkaAclList = new ArrayList<>();
        try {
            KafkaZkClient kafkaZkClient = kafkaAdminZKClient.getClient(clusterPhyId);

            for (String rType: CollectionConverters.asJava(kafkaZkClient.getResourceTypes(patternType))) {
                ResourceType resourceType = SecurityUtils.resourceType(rType);
                for (String resourceName : CollectionConverters.asJava(kafkaZkClient.getResourceNames(patternType, resourceType))) {
                    ResourcePattern resourcePattern = new ResourcePattern(resourceType, resourceName, patternType);
                    AclAuthorizer.VersionedAcls versionedAcls = kafkaZkClient.getVersionedAclsForResource(resourcePattern);

                    CollectionConverters.asJava(versionedAcls.acls()).forEach(elem -> kafkaAclList.add(new AclBinding(resourcePattern, elem.ace())));
                }
            }
        } catch (Exception e) {
            log.error("method=getSpecifiedTypeAclByZKClient||clusterPhyId={}||patternType={}||errMsg={}", clusterPhyId, patternType, e.getMessage());

            return Result.buildFromRSAndMsg(ResultStatus.ZK_OPERATE_FAILED, e.getMessage());
        }

        return Result.buildSuc(kafkaAclList);
    }
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261

    private Result<Void> insertAndIgnoreDuplicate(KafkaAclPO kafkaAclPO) {
        try {
            kafkaAclDAO.insert(kafkaAclPO);

            return Result.buildSuc();
        } catch (DuplicateKeyException dke) {
            // 直接写入,如果出现key冲突则直接忽略,因为key冲突时,表示该数据已完整存在,不需要替换任何数据
            return Result.buildSuc();
        } catch (Exception e) {
            log.error("method=insertAndIgnoreDuplicate||kafkaAclPO={}||errMsg=exception", kafkaAclPO, e);

            return Result.buildFromRSAndMsg(ResultStatus.MYSQL_OPERATE_FAILED, e.getMessage());
        }
    }
Z
zengqiao 已提交
262
}