Search in sources :

Example 1 with UnSubscribeRequestBody

use of org.apache.eventmesh.common.protocol.http.body.client.UnSubscribeRequestBody in project incubator-eventmesh by apache.

the class UnSubscribeProcessor method processRequest.

@Override
public void processRequest(ChannelHandlerContext ctx, AsyncContext<HttpCommand> asyncContext) throws Exception {
    HttpCommand responseEventMeshCommand;
    httpLogger.info("cmd={}|{}|client2eventMesh|from={}|to={}", RequestCode.get(Integer.valueOf(asyncContext.getRequest().getRequestCode())), EventMeshConstants.PROTOCOL_HTTP, RemotingHelper.parseChannelRemoteAddr(ctx.channel()), IPUtils.getLocalAddress());
    UnSubscribeRequestHeader unSubscribeRequestHeader = (UnSubscribeRequestHeader) asyncContext.getRequest().getHeader();
    UnSubscribeRequestBody unSubscribeRequestBody = (UnSubscribeRequestBody) asyncContext.getRequest().getBody();
    UnSubscribeResponseHeader unSubscribeResponseHeader = UnSubscribeResponseHeader.buildHeader(Integer.valueOf(asyncContext.getRequest().getRequestCode()), eventMeshHTTPServer.getEventMeshHttpConfiguration().eventMeshCluster, IPUtils.getLocalAddress(), eventMeshHTTPServer.getEventMeshHttpConfiguration().eventMeshEnv, eventMeshHTTPServer.getEventMeshHttpConfiguration().eventMeshIDC);
    // validate header
    if (StringUtils.isBlank(unSubscribeRequestHeader.getIdc()) || StringUtils.isBlank(unSubscribeRequestHeader.getPid()) || !StringUtils.isNumeric(unSubscribeRequestHeader.getPid()) || StringUtils.isBlank(unSubscribeRequestHeader.getSys())) {
        responseEventMeshCommand = asyncContext.getRequest().createHttpCommandResponse(unSubscribeResponseHeader, UnSubscribeResponseBody.buildBody(EventMeshRetCode.EVENTMESH_PROTOCOL_HEADER_ERR.getRetCode(), EventMeshRetCode.EVENTMESH_PROTOCOL_HEADER_ERR.getErrMsg()));
        asyncContext.onComplete(responseEventMeshCommand);
        return;
    }
    // validate body
    if (StringUtils.isBlank(unSubscribeRequestBody.getUrl()) || CollectionUtils.isEmpty(unSubscribeRequestBody.getTopics()) || StringUtils.isBlank(unSubscribeRequestBody.getConsumerGroup())) {
        responseEventMeshCommand = asyncContext.getRequest().createHttpCommandResponse(unSubscribeResponseHeader, UnSubscribeResponseBody.buildBody(EventMeshRetCode.EVENTMESH_PROTOCOL_BODY_ERR.getRetCode(), EventMeshRetCode.EVENTMESH_PROTOCOL_BODY_ERR.getErrMsg()));
        asyncContext.onComplete(responseEventMeshCommand);
        return;
    }
    String env = unSubscribeRequestHeader.getEnv();
    String idc = unSubscribeRequestHeader.getIdc();
    String sys = unSubscribeRequestHeader.getSys();
    String ip = unSubscribeRequestHeader.getIp();
    String pid = unSubscribeRequestHeader.getPid();
    String consumerGroup = unSubscribeRequestBody.getConsumerGroup();
    String unSubscribeUrl = unSubscribeRequestBody.getUrl();
    List<String> unSubTopicList = unSubscribeRequestBody.getTopics();
    final CompleteHandler<HttpCommand> handler = new CompleteHandler<HttpCommand>() {

        @Override
        public void onResponse(HttpCommand httpCommand) {
            try {
                if (httpLogger.isDebugEnabled()) {
                    httpLogger.debug("{}", httpCommand);
                }
                eventMeshHTTPServer.sendResponse(ctx, httpCommand.httpResponse());
                eventMeshHTTPServer.metrics.getSummaryMetrics().recordHTTPReqResTimeCost(System.currentTimeMillis() - asyncContext.getRequest().getReqTime());
            } catch (Exception ex) {
            // ignore
            }
        }
    };
    synchronized (eventMeshHTTPServer.localClientInfoMapping) {
        boolean isChange = true;
        registerClient(unSubscribeRequestHeader, consumerGroup, unSubTopicList, unSubscribeUrl);
        for (String unSubTopic : unSubTopicList) {
            List<Client> groupTopicClients = eventMeshHTTPServer.localClientInfoMapping.get(consumerGroup + "@" + unSubTopic);
            Iterator<Client> clientIterator = groupTopicClients.iterator();
            while (clientIterator.hasNext()) {
                Client client = clientIterator.next();
                if (StringUtils.equals(client.pid, pid) && StringUtils.equals(client.url, unSubscribeUrl)) {
                    httpLogger.warn("client {} start unsubscribe", JsonUtils.serialize(client));
                    clientIterator.remove();
                }
            }
            if (groupTopicClients.size() > 0) {
                // change url
                Map<String, List<String>> idcUrls = new HashMap<>();
                Set<String> clientUrls = new HashSet<>();
                for (Client client : groupTopicClients) {
                    // remove subscribed url
                    if (!StringUtils.equals(unSubscribeUrl, client.url)) {
                        clientUrls.add(client.url);
                        if (idcUrls.containsKey(client.idc)) {
                            idcUrls.get(client.idc).add(StringUtils.deleteWhitespace(client.url));
                        } else {
                            List<String> urls = new ArrayList<>();
                            urls.add(client.url);
                            idcUrls.put(client.idc, urls);
                        }
                    }
                }
                synchronized (eventMeshHTTPServer.localConsumerGroupMapping) {
                    ConsumerGroupConf consumerGroupConf = eventMeshHTTPServer.localConsumerGroupMapping.get(consumerGroup);
                    Map<String, ConsumerGroupTopicConf> map = consumerGroupConf.getConsumerGroupTopicConf();
                    for (String topicKey : map.keySet()) {
                        // only modify the topic to subscribe
                        if (StringUtils.equals(unSubTopic, topicKey)) {
                            ConsumerGroupTopicConf latestTopicConf = new ConsumerGroupTopicConf();
                            latestTopicConf.setConsumerGroup(consumerGroup);
                            latestTopicConf.setTopic(unSubTopic);
                            latestTopicConf.setSubscriptionItem(map.get(topicKey).getSubscriptionItem());
                            latestTopicConf.setUrls(clientUrls);
                            latestTopicConf.setIdcUrls(idcUrls);
                            map.put(unSubTopic, latestTopicConf);
                        }
                    }
                    eventMeshHTTPServer.localConsumerGroupMapping.put(consumerGroup, consumerGroupConf);
                }
            } else {
                isChange = false;
                break;
            }
        }
        long startTime = System.currentTimeMillis();
        if (isChange) {
            try {
                eventMeshHTTPServer.getConsumerManager().notifyConsumerManager(consumerGroup, eventMeshHTTPServer.localConsumerGroupMapping.get(consumerGroup));
                responseEventMeshCommand = asyncContext.getRequest().createHttpCommandResponse(EventMeshRetCode.SUCCESS);
                asyncContext.onComplete(responseEventMeshCommand, handler);
            } catch (Exception e) {
                HttpCommand err = asyncContext.getRequest().createHttpCommandResponse(unSubscribeResponseHeader, UnSubscribeResponseBody.buildBody(EventMeshRetCode.EVENTMESH_UNSUBSCRIBE_ERR.getRetCode(), EventMeshRetCode.EVENTMESH_UNSUBSCRIBE_ERR.getErrMsg() + EventMeshUtil.stackTrace(e, 2)));
                asyncContext.onComplete(err);
                long endTime = System.currentTimeMillis();
                httpLogger.error("message|eventMesh2mq|REQ|ASYNC|send2MQCost={}ms" + "|topic={}|bizSeqNo={}|uniqueId={}", endTime - startTime, JsonUtils.serialize(unSubscribeRequestBody.getTopics()), unSubscribeRequestBody.getUrl(), e);
                eventMeshHTTPServer.metrics.getSummaryMetrics().recordSendMsgFailed();
                eventMeshHTTPServer.metrics.getSummaryMetrics().recordSendMsgCost(endTime - startTime);
            }
        } else {
            // remove
            try {
                eventMeshHTTPServer.getConsumerManager().notifyConsumerManager(consumerGroup, null);
                responseEventMeshCommand = asyncContext.getRequest().createHttpCommandResponse(EventMeshRetCode.SUCCESS);
                asyncContext.onComplete(responseEventMeshCommand, handler);
                // clean ClientInfo
                eventMeshHTTPServer.localClientInfoMapping.keySet().removeIf(s -> StringUtils.contains(s, consumerGroup));
                // clean ConsumerGroupInfo
                eventMeshHTTPServer.localConsumerGroupMapping.keySet().removeIf(s -> StringUtils.equals(consumerGroup, s));
            } catch (Exception e) {
                HttpCommand err = asyncContext.getRequest().createHttpCommandResponse(unSubscribeResponseHeader, UnSubscribeResponseBody.buildBody(EventMeshRetCode.EVENTMESH_UNSUBSCRIBE_ERR.getRetCode(), EventMeshRetCode.EVENTMESH_UNSUBSCRIBE_ERR.getErrMsg() + EventMeshUtil.stackTrace(e, 2)));
                asyncContext.onComplete(err);
                long endTime = System.currentTimeMillis();
                httpLogger.error("message|eventMesh2mq|REQ|ASYNC|send2MQCost={}ms" + "|topic={}|bizSeqNo={}|uniqueId={}", endTime - startTime, JsonUtils.serialize(unSubscribeRequestBody.getTopics()), unSubscribeRequestBody.getUrl(), e);
                eventMeshHTTPServer.metrics.getSummaryMetrics().recordSendMsgFailed();
                eventMeshHTTPServer.metrics.getSummaryMetrics().recordSendMsgCost(endTime - startTime);
            }
        }
    }
}
Also used : UnSubscribeRequestBody(org.apache.eventmesh.common.protocol.http.body.client.UnSubscribeRequestBody) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ConsumerGroupTopicConf(org.apache.eventmesh.runtime.core.consumergroup.ConsumerGroupTopicConf) UnSubscribeRequestHeader(org.apache.eventmesh.common.protocol.http.header.client.UnSubscribeRequestHeader) UnSubscribeResponseHeader(org.apache.eventmesh.common.protocol.http.header.client.UnSubscribeResponseHeader) CompleteHandler(org.apache.eventmesh.runtime.core.protocol.http.async.CompleteHandler) ArrayList(java.util.ArrayList) List(java.util.List) ConsumerGroupConf(org.apache.eventmesh.runtime.core.consumergroup.ConsumerGroupConf) Client(org.apache.eventmesh.runtime.core.protocol.http.processor.inf.Client) HttpCommand(org.apache.eventmesh.common.protocol.http.HttpCommand) HashSet(java.util.HashSet)

Aggregations

ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 List (java.util.List)1 HttpCommand (org.apache.eventmesh.common.protocol.http.HttpCommand)1 UnSubscribeRequestBody (org.apache.eventmesh.common.protocol.http.body.client.UnSubscribeRequestBody)1 UnSubscribeRequestHeader (org.apache.eventmesh.common.protocol.http.header.client.UnSubscribeRequestHeader)1 UnSubscribeResponseHeader (org.apache.eventmesh.common.protocol.http.header.client.UnSubscribeResponseHeader)1 ConsumerGroupConf (org.apache.eventmesh.runtime.core.consumergroup.ConsumerGroupConf)1 ConsumerGroupTopicConf (org.apache.eventmesh.runtime.core.consumergroup.ConsumerGroupTopicConf)1 CompleteHandler (org.apache.eventmesh.runtime.core.protocol.http.async.CompleteHandler)1 Client (org.apache.eventmesh.runtime.core.protocol.http.processor.inf.Client)1