View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  
20  
21  package org.apache.hadoop.hbase.master;
22  
23  
24  import io.netty.bootstrap.Bootstrap;
25  import io.netty.buffer.Unpooled;
26  import io.netty.channel.ChannelHandlerContext;
27  import io.netty.channel.ChannelOption;
28  import io.netty.channel.EventLoopGroup;
29  import io.netty.channel.nio.NioEventLoopGroup;
30  import io.netty.channel.socket.DatagramChannel;
31  import io.netty.channel.socket.DatagramPacket;
32  import io.netty.channel.socket.nio.NioDatagramChannel;
33  import io.netty.handler.codec.MessageToMessageEncoder;
34  import org.apache.hadoop.classification.InterfaceAudience;
35  import org.apache.hadoop.conf.Configuration;
36  import org.apache.hadoop.hbase.Chore;
37  import org.apache.hadoop.hbase.ClusterStatus;
38  import org.apache.hadoop.hbase.HConstants;
39  import org.apache.hadoop.hbase.ServerName;
40  import org.apache.hadoop.hbase.protobuf.generated.ClusterStatusProtos;
41  import org.apache.hadoop.hbase.util.Addressing;
42  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
43  import org.apache.hadoop.hbase.util.ExceptionUtil;
44  import org.apache.hadoop.hbase.util.Pair;
45  import org.apache.hadoop.hbase.util.Threads;
46  import org.apache.hadoop.hbase.util.VersionInfo;
47  
48  import java.io.Closeable;
49  import java.io.IOException;
50  import java.net.InetAddress;
51  import java.net.InetSocketAddress;
52  import java.net.NetworkInterface;
53  import java.net.UnknownHostException;
54  import java.util.ArrayList;
55  import java.util.Collections;
56  import java.util.Comparator;
57  import java.util.List;
58  import java.util.Map;
59  import java.util.concurrent.ConcurrentHashMap;
60  import java.util.concurrent.ConcurrentMap;
61  
62  /**
63   * Class to publish the cluster status to the client. This allows them to know immediately
64   *  the dead region servers, hence to cut the connection they have with them, eventually stop
65   *  waiting on the socket. This improves the mean time to recover, and as well allows to increase
66   *  on the client the different timeouts, as the dead servers will be detected separately.
67   */
68  @InterfaceAudience.Private
69  public class ClusterStatusPublisher extends Chore {
70    /**
71     * The implementation class used to publish the status. Default is null (no publish).
72     * Use org.apache.hadoop.hbase.master.ClusterStatusPublisher.MulticastPublisher to multicast the
73     * status.
74     */
75    public static final String STATUS_PUBLISHER_CLASS = "hbase.status.publisher.class";
76    public static final Class<? extends ClusterStatusPublisher.Publisher>
77        DEFAULT_STATUS_PUBLISHER_CLASS =
78        org.apache.hadoop.hbase.master.ClusterStatusPublisher.MulticastPublisher.class;
79  
80    /**
81     * The minimum time between two status messages, in milliseconds.
82     */
83    public static final String STATUS_PUBLISH_PERIOD = "hbase.status.publish.period";
84    public static final int DEFAULT_STATUS_PUBLISH_PERIOD = 10000;
85  
86    private long lastMessageTime = 0;
87    private final HMaster master;
88    private final int messagePeriod; // time between two message
89    private final ConcurrentMap<ServerName, Integer> lastSent =
90        new ConcurrentHashMap<ServerName, Integer>();
91    private Publisher publisher;
92    private boolean connected = false;
93  
94    /**
95     * We want to limit the size of the protobuf message sent, do fit into a single packet.
96     * a reasonable size for ip / ethernet is less than 1Kb.
97     */
98    public final static int MAX_SERVER_PER_MESSAGE = 10;
99  
100   /**
101    * If a server dies, we're sending the information multiple times in case a receiver misses the
102    * message.
103    */
104   public final static int NB_SEND = 5;
105 
106   public ClusterStatusPublisher(HMaster master, Configuration conf,
107                                 Class<? extends Publisher> publisherClass)
108       throws IOException {
109     super("HBase clusterStatusPublisher for " + master.getName(),
110         conf.getInt(STATUS_PUBLISH_PERIOD, DEFAULT_STATUS_PUBLISH_PERIOD), master);
111     this.master = master;
112     this.messagePeriod = conf.getInt(STATUS_PUBLISH_PERIOD, DEFAULT_STATUS_PUBLISH_PERIOD);
113     try {
114       this.publisher = publisherClass.newInstance();
115     } catch (InstantiationException e) {
116       throw new IOException("Can't create publisher " + publisherClass.getName(), e);
117     } catch (IllegalAccessException e) {
118       throw new IOException("Can't create publisher " + publisherClass.getName(), e);
119     }
120     this.publisher.connect(conf);
121     connected = true;
122   }
123 
124   // For tests only
125   protected ClusterStatusPublisher() {
126     master = null;
127     messagePeriod = 0;
128   }
129 
130   @Override
131   protected void chore() {
132     if (!connected) {
133       return;
134     }
135 
136     List<ServerName> sns = generateDeadServersListToSend();
137     if (sns.isEmpty()) {
138       // Nothing to send. Done.
139       return;
140     }
141 
142     final long curTime = EnvironmentEdgeManager.currentTimeMillis();
143     if (lastMessageTime > curTime - messagePeriod) {
144       // We already sent something less than 10 second ago. Done.
145       return;
146     }
147 
148     // Ok, we're going to send something then.
149     lastMessageTime = curTime;
150 
151     // We're reusing an existing protobuf message, but we don't send everything.
152     // This could be extended in the future, for example if we want to send stuff like the
153     //  hbase:meta server name.
154     ClusterStatus cs = new ClusterStatus(VersionInfo.getVersion(),
155         master.getMasterFileSystem().getClusterId().toString(),
156         null,
157         sns,
158         master.getServerName(),
159         null,
160         null,
161         null,
162         null);
163 
164 
165     publisher.publish(cs);
166   }
167 
168   protected void cleanup() {
169     connected = false;
170     publisher.close();
171   }
172 
173   /**
174    * Create the dead server to send. A dead server is sent NB_SEND times. We send at max
175    * MAX_SERVER_PER_MESSAGE at a time. if there are too many dead servers, we send the newly
176    * dead first.
177    */
178   protected List<ServerName> generateDeadServersListToSend() {
179     // We're getting the message sent since last time, and add them to the list
180     long since = EnvironmentEdgeManager.currentTimeMillis() - messagePeriod * 2;
181     for (Pair<ServerName, Long> dead : getDeadServers(since)) {
182       lastSent.putIfAbsent(dead.getFirst(), 0);
183     }
184 
185     // We're sending the new deads first.
186     List<Map.Entry<ServerName, Integer>> entries = new ArrayList<Map.Entry<ServerName, Integer>>();
187     entries.addAll(lastSent.entrySet());
188     Collections.sort(entries, new Comparator<Map.Entry<ServerName, Integer>>() {
189       @Override
190       public int compare(Map.Entry<ServerName, Integer> o1, Map.Entry<ServerName, Integer> o2) {
191         return o1.getValue().compareTo(o2.getValue());
192       }
193     });
194 
195     // With a limit of MAX_SERVER_PER_MESSAGE
196     int max = entries.size() > MAX_SERVER_PER_MESSAGE ? MAX_SERVER_PER_MESSAGE : entries.size();
197     List<ServerName> res = new ArrayList<ServerName>(max);
198 
199     for (int i = 0; i < max; i++) {
200       Map.Entry<ServerName, Integer> toSend = entries.get(i);
201       if (toSend.getValue() >= (NB_SEND - 1)) {
202         lastSent.remove(toSend.getKey());
203       } else {
204         lastSent.replace(toSend.getKey(), toSend.getValue(), toSend.getValue() + 1);
205       }
206 
207       res.add(toSend.getKey());
208     }
209 
210     return res;
211   }
212 
213   /**
214    * Get the servers which died since a given timestamp.
215    * protected because it can be subclassed by the tests.
216    */
217   protected List<Pair<ServerName, Long>> getDeadServers(long since) {
218     if (master.getServerManager() == null) {
219       return Collections.emptyList();
220     }
221 
222     return master.getServerManager().getDeadServers().copyDeadServersSince(since);
223   }
224 
225 
226   public interface Publisher extends Closeable {
227 
228     void connect(Configuration conf) throws IOException;
229 
230     void publish(ClusterStatus cs);
231 
232     @Override
233     void close();
234   }
235 
236   public static class MulticastPublisher implements Publisher {
237     private DatagramChannel channel;
238     private final EventLoopGroup group = new NioEventLoopGroup(
239         1, Threads.newDaemonThreadFactory("hbase-master-clusterStatusPublisher"));
240 
241     public MulticastPublisher() {
242     }
243 
244     @Override
245     public void connect(Configuration conf) throws IOException {
246       NetworkInterface ni = NetworkInterface.getByInetAddress(Addressing.getIpAddress());
247 
248       String mcAddress = conf.get(HConstants.STATUS_MULTICAST_ADDRESS,
249           HConstants.DEFAULT_STATUS_MULTICAST_ADDRESS);
250       int port = conf.getInt(HConstants.STATUS_MULTICAST_PORT,
251           HConstants.DEFAULT_STATUS_MULTICAST_PORT);
252 
253       final InetAddress ina;
254       try {
255         ina = InetAddress.getByName(mcAddress);
256       } catch (UnknownHostException e) {
257         close();
258         throw new IOException("Can't connect to " + mcAddress, e);
259       }
260 
261       final InetSocketAddress isa = new InetSocketAddress(mcAddress, port);
262 
263       Bootstrap b = new Bootstrap();
264       b.group(group)
265           .channel(NioDatagramChannel.class)
266           .option(ChannelOption.SO_REUSEADDR, true)
267           .handler(new ClusterStatusEncoder(isa));
268 
269       try {
270         channel = (DatagramChannel) b.bind(new InetSocketAddress(0)).sync().channel();
271         channel.joinGroup(ina, ni, null, channel.newPromise()).sync();
272         channel.connect(isa).sync();
273       } catch (InterruptedException e) {
274         close();
275         throw ExceptionUtil.asInterrupt(e);
276       }
277     }
278 
279     private static class ClusterStatusEncoder extends MessageToMessageEncoder<ClusterStatus> {
280       final private InetSocketAddress isa;
281 
282       private ClusterStatusEncoder(InetSocketAddress isa) {
283         this.isa = isa;
284       }
285 
286       @Override
287       protected void encode(ChannelHandlerContext channelHandlerContext,
288                             ClusterStatus clusterStatus, List<Object> objects) {
289         ClusterStatusProtos.ClusterStatus csp = clusterStatus.convert();
290         objects.add(new DatagramPacket(Unpooled.wrappedBuffer(csp.toByteArray()), isa));
291       }
292     }
293 
294     @Override
295     public void publish(ClusterStatus cs) {
296       channel.writeAndFlush(cs).syncUninterruptibly();
297     }
298 
299     @Override
300     public void close() {
301       if (channel != null) {
302         channel.close();
303       }
304       group.shutdownGracefully();
305     }
306   }
307 }