View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *     http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.shardingsphere.proxy.frontend.netty;
19  
20  import io.netty.channel.ChannelHandlerContext;
21  import io.netty.channel.ChannelInboundHandlerAdapter;
22  import lombok.RequiredArgsConstructor;
23  import lombok.extern.slf4j.Slf4j;
24  import org.apache.shardingsphere.proxy.frontend.connection.ConnectionLimitContext;
25  import org.apache.shardingsphere.infra.exception.dialect.exception.connection.TooManyConnectionsException;
26  import org.apache.shardingsphere.proxy.frontend.spi.DatabaseProtocolFrontendEngine;
27  
28  /**
29   * Frontend channel limitation inbound handler.
30   */
31  @RequiredArgsConstructor
32  @Slf4j
33  public class FrontendChannelLimitationInboundHandler extends ChannelInboundHandlerAdapter {
34      
35      private final DatabaseProtocolFrontendEngine databaseProtocolFrontendEngine;
36      
37      @Override
38      public void channelActive(final ChannelHandlerContext ctx) {
39          if (ConnectionLimitContext.getInstance().connectionAllowed()) {
40              ctx.fireChannelActive();
41              return;
42          }
43          log.debug("Closing channel {} due to the number of server connections has reached max connections {}", ctx.channel().remoteAddress(), ConnectionLimitContext.getInstance().getMaxConnections());
44          // TODO This is not how actual databases does and should be refactored.
45          ctx.writeAndFlush(databaseProtocolFrontendEngine.getCommandExecuteEngine().getErrorPacket(new TooManyConnectionsException()));
46          ctx.close();
47      }
48      
49      @Override
50      public void channelInactive(final ChannelHandlerContext ctx) {
51          ctx.fireChannelInactive();
52          ConnectionLimitContext.getInstance().connectionInactive();
53      }
54  }