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  package org.apache.hadoop.hbase;
20  
21  import com.google.common.net.InetAddresses;
22  import com.google.protobuf.InvalidProtocolBufferException;
23  import org.apache.hadoop.classification.InterfaceAudience;
24  import org.apache.hadoop.classification.InterfaceStability;
25  import org.apache.hadoop.hbase.exceptions.DeserializationException;
26  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
27  import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos.MetaRegionServer;
28  import org.apache.hadoop.hbase.util.Addressing;
29  import org.apache.hadoop.hbase.util.Bytes;
30  
31  import java.util.ArrayList;
32  import java.util.List;
33  import java.util.regex.Pattern;
34  
35  /**
36   * Instance of an HBase ServerName.
37   * A server name is used uniquely identifying a server instance in a cluster and is made
38   * of the combination of hostname, port, and startcode.  The startcode distingushes restarted
39   * servers on same hostname and port (startcode is usually timestamp of server startup). The
40   * {@link #toString()} format of ServerName is safe to use in the  filesystem and as znode name
41   * up in ZooKeeper.  Its format is:
42   * <code>&lt;hostname> '{@link #SERVERNAME_SEPARATOR}' &lt;port> '{@link #SERVERNAME_SEPARATOR}' &lt;startcode></code>.
43   * For example, if hostname is <code>www.example.org</code>, port is <code>1234</code>,
44   * and the startcode for the regionserver is <code>1212121212</code>, then
45   * the {@link #toString()} would be <code>www.example.org,1234,1212121212</code>.
46   * 
47   * <p>You can obtain a versioned serialized form of this class by calling
48   * {@link #getVersionedBytes()}.  To deserialize, call {@link #parseVersionedServerName(byte[])}
49   * 
50   * <p>Immutable.
51   */
52  @InterfaceAudience.Public
53  @InterfaceStability.Evolving
54  public class ServerName implements Comparable<ServerName> {
55    /**
56     * Version for this class.
57     * Its a short rather than a byte so I can for sure distinguish between this
58     * version of this class and the version previous to this which did not have
59     * a version.
60     */
61    private static final short VERSION = 0;
62    static final byte [] VERSION_BYTES = Bytes.toBytes(VERSION);
63  
64    /**
65     * What to use if no startcode supplied.
66     */
67    public static final int NON_STARTCODE = -1;
68  
69    /**
70     * This character is used as separator between server hostname, port and
71     * startcode.
72     */
73    public static final String SERVERNAME_SEPARATOR = ",";
74  
75    public static final Pattern SERVERNAME_PATTERN =
76      Pattern.compile("[^" + SERVERNAME_SEPARATOR + "]+" +
77        SERVERNAME_SEPARATOR + Addressing.VALID_PORT_REGEX +
78        SERVERNAME_SEPARATOR + Addressing.VALID_PORT_REGEX + "$");
79  
80    /**
81     * What to use if server name is unknown.
82     */
83    public static final String UNKNOWN_SERVERNAME = "#unknown#";
84  
85    private final String servername;
86    private final String hostnameOnly;
87    private final int port;
88    private final long startcode;
89  
90    /**
91     * Cached versioned bytes of this ServerName instance.
92     * @see #getVersionedBytes()
93     */
94    private byte [] bytes;
95    public static final List<ServerName> EMPTY_SERVER_LIST = new ArrayList<ServerName>(0);
96  
97    public ServerName(final String hostname, final int port, final long startcode) {
98      // Drop the domain is there is one; no need of it in a local cluster.  With it, we get long
99      // unwieldy names.
100     this.hostnameOnly = hostname;
101     this.port = port;
102     this.startcode = startcode;
103     this.servername = getServerName(this.hostnameOnly, port, startcode);
104   }
105 
106   /**
107    * @param hostname
108    * @return hostname minus the domain, if there is one (will do pass-through on ip addresses)
109    */
110   static String getHostNameMinusDomain(final String hostname) {
111     if (InetAddresses.isInetAddress(hostname)) return hostname;
112     String [] parts = hostname.split("\\.");
113     if (parts == null || parts.length == 0) return hostname;
114     return parts[0];
115   }
116 
117   public ServerName(final String serverName) {
118     this(parseHostname(serverName), parsePort(serverName),
119       parseStartcode(serverName));
120   }
121 
122   public ServerName(final String hostAndPort, final long startCode) {
123     this(Addressing.parseHostname(hostAndPort),
124       Addressing.parsePort(hostAndPort), startCode);
125   }
126 
127   public static String parseHostname(final String serverName) {
128     if (serverName == null || serverName.length() <= 0) {
129       throw new IllegalArgumentException("Passed hostname is null or empty");
130     }
131     if (!Character.isLetterOrDigit(serverName.charAt(0))) {
132       throw new IllegalArgumentException("Bad passed hostname, serverName=" + serverName);
133     }
134     int index = serverName.indexOf(SERVERNAME_SEPARATOR);
135     return serverName.substring(0, index);
136   }
137 
138   public static int parsePort(final String serverName) {
139     String [] split = serverName.split(SERVERNAME_SEPARATOR);
140     return Integer.parseInt(split[1]);
141   }
142 
143   public static long parseStartcode(final String serverName) {
144     int index = serverName.lastIndexOf(SERVERNAME_SEPARATOR);
145     return Long.parseLong(serverName.substring(index + 1));
146   }
147 
148   @Override
149   public String toString() {
150     return getServerName();
151   }
152 
153   /**
154    * @return Return a SHORT version of {@link ServerName#toString()}, one that has the host only,
155    * minus the domain, and the port only -- no start code; the String is for us internally mostly
156    * tying threads to their server.  Not for external use.  It is lossy and will not work in
157    * in compares, etc.
158    */
159   public String toShortString() {
160     return Addressing.createHostAndPortStr(getHostNameMinusDomain(this.hostnameOnly), this.port);
161   }
162 
163   /**
164    * @return {@link #getServerName()} as bytes with a short-sized prefix with
165    * the ServerName#VERSION of this class.
166    */
167   public synchronized byte [] getVersionedBytes() {
168     if (this.bytes == null) {
169       this.bytes = Bytes.add(VERSION_BYTES, Bytes.toBytes(getServerName()));
170     }
171     return this.bytes;
172   }
173 
174   public String getServerName() {
175     return servername;
176   }
177 
178   public String getHostname() {
179     return hostnameOnly;
180   }
181 
182   public int getPort() {
183     return port;
184   }
185 
186   public long getStartcode() {
187     return startcode;
188   }
189 
190   /**
191    * For internal use only.
192    * @param hostName
193    * @param port
194    * @param startcode
195    * @return Server name made of the concatenation of hostname, port and
196    * startcode formatted as <code>&lt;hostname> ',' &lt;port> ',' &lt;startcode></code>
197    */
198   static String getServerName(String hostName, int port, long startcode) {
199     final StringBuilder name = new StringBuilder(hostName.length() + 1 + 5 + 1 + 13);
200     name.append(hostName);
201     name.append(SERVERNAME_SEPARATOR);
202     name.append(port);
203     name.append(SERVERNAME_SEPARATOR);
204     name.append(startcode);
205     return name.toString();
206   }
207 
208   /**
209    * @param hostAndPort String in form of &lt;hostname> ':' &lt;port>
210    * @param startcode
211    * @return Server name made of the concatenation of hostname, port and
212    * startcode formatted as <code>&lt;hostname> ',' &lt;port> ',' &lt;startcode></code>
213    */
214   public static String getServerName(final String hostAndPort,
215       final long startcode) {
216     int index = hostAndPort.indexOf(":");
217     if (index <= 0) throw new IllegalArgumentException("Expected <hostname> ':' <port>");
218     return getServerName(hostAndPort.substring(0, index),
219       Integer.parseInt(hostAndPort.substring(index + 1)), startcode);
220   }
221 
222   /**
223    * @return Hostname and port formatted as described at
224    * {@link Addressing#createHostAndPortStr(String, int)}
225    */
226   public String getHostAndPort() {
227     return Addressing.createHostAndPortStr(this.hostnameOnly, this.port);
228   }
229 
230   /**
231    * @param serverName ServerName in form specified by {@link #getServerName()}
232    * @return The server start code parsed from <code>servername</code>
233    */
234   public static long getServerStartcodeFromServerName(final String serverName) {
235     int index = serverName.lastIndexOf(SERVERNAME_SEPARATOR);
236     return Long.parseLong(serverName.substring(index + 1));
237   }
238 
239   /**
240    * Utility method to excise the start code from a server name
241    * @param inServerName full server name
242    * @return server name less its start code
243    */
244   public static String getServerNameLessStartCode(String inServerName) {
245     if (inServerName != null && inServerName.length() > 0) {
246       int index = inServerName.lastIndexOf(SERVERNAME_SEPARATOR);
247       if (index > 0) {
248         return inServerName.substring(0, index);
249       }
250     }
251     return inServerName;
252   }
253 
254   @Override
255   public int compareTo(ServerName other) {
256     int compare = this.getHostname().toLowerCase().
257       compareTo(other.getHostname().toLowerCase());
258     if (compare != 0) return compare;
259     compare = this.getPort() - other.getPort();
260     if (compare != 0) return compare;
261     return (int)(this.getStartcode() - other.getStartcode());
262   }
263 
264   @Override
265   public int hashCode() {
266     return getServerName().hashCode();
267   }
268 
269   @Override
270   public boolean equals(Object o) {
271     if (this == o) return true;
272     if (o == null) return false;
273     if (!(o instanceof ServerName)) return false;
274     return this.compareTo((ServerName)o) == 0;
275   }
276 
277   /**
278    * @param left
279    * @param right
280    * @return True if <code>other</code> has same hostname and port.
281    */
282   public static boolean isSameHostnameAndPort(final ServerName left,
283       final ServerName right) {
284     if (left == null) return false;
285     if (right == null) return false;
286     return left.getHostname().equals(right.getHostname()) &&
287       left.getPort() == right.getPort();
288   }
289 
290   /**
291    * Use this method instantiating a {@link ServerName} from bytes
292    * gotten from a call to {@link #getVersionedBytes()}.  Will take care of the
293    * case where bytes were written by an earlier version of hbase.
294    * @param versionedBytes Pass bytes gotten from a call to {@link #getVersionedBytes()}
295    * @return A ServerName instance.
296    * @see #getVersionedBytes()
297    */
298   public static ServerName parseVersionedServerName(final byte [] versionedBytes) {
299     // Version is a short.
300     short version = Bytes.toShort(versionedBytes);
301     if (version == VERSION) {
302       int length = versionedBytes.length - Bytes.SIZEOF_SHORT;
303       return new ServerName(Bytes.toString(versionedBytes, Bytes.SIZEOF_SHORT, length));
304     }
305     // Presume the bytes were written with an old version of hbase and that the
306     // bytes are actually a String of the form "'<hostname>' ':' '<port>'".
307     return new ServerName(Bytes.toString(versionedBytes), NON_STARTCODE);
308   }
309 
310   /**
311    * @param str Either an instance of {@link ServerName#toString()} or a
312    * "'<hostname>' ':' '<port>'".
313    * @return A ServerName instance.
314    */
315   public static ServerName parseServerName(final String str) {
316     return SERVERNAME_PATTERN.matcher(str).matches()? new ServerName(str):
317       new ServerName(str, NON_STARTCODE);
318   }
319 
320 
321   /**
322    * @return true if the String follows the pattern of {@link ServerName#toString()}, false
323    *  otherwise.
324    */
325   public static boolean isFullServerName(final String str){
326     if (str == null ||str.isEmpty()) return false;
327     return SERVERNAME_PATTERN.matcher(str).matches();
328   }
329 
330   /**
331    * Get a ServerName from the passed in data bytes.
332    * @param data Data with a serialize server name in it; can handle the old style
333    * servername where servername was host and port.  Works too with data that
334    * begins w/ the pb 'PBUF' magic and that is then followed by a protobuf that
335    * has a serialized {@link ServerName} in it.
336    * @return Returns null if <code>data</code> is null else converts passed data
337    * to a ServerName instance.
338    * @throws DeserializationException 
339    */
340   public static ServerName parseFrom(final byte [] data) throws DeserializationException {
341     if (data == null || data.length <= 0) return null;
342     if (ProtobufUtil.isPBMagicPrefix(data)) {
343       int prefixLen = ProtobufUtil.lengthOfPBMagic();
344       try {
345         MetaRegionServer rss =
346           MetaRegionServer.newBuilder().mergeFrom(data, prefixLen, data.length - prefixLen).build();
347         org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.ServerName sn = rss.getServer();
348         return new ServerName(sn.getHostName(), sn.getPort(), sn.getStartCode());
349       } catch (InvalidProtocolBufferException e) {
350         // A failed parse of the znode is pretty catastrophic. Rather than loop
351         // retrying hoping the bad bytes will changes, and rather than change
352         // the signature on this method to add an IOE which will send ripples all
353         // over the code base, throw a RuntimeException.  This should "never" happen.
354         // Fail fast if it does.
355         throw new DeserializationException(e);
356       }
357     }
358     // The str returned could be old style -- pre hbase-1502 -- which was
359     // hostname and port seperated by a colon rather than hostname, port and
360     // startcode delimited by a ','.
361     String str = Bytes.toString(data);
362     int index = str.indexOf(ServerName.SERVERNAME_SEPARATOR);
363     if (index != -1) {
364       // Presume its ServerName serialized with versioned bytes.
365       return ServerName.parseVersionedServerName(data);
366     }
367     // Presume it a hostname:port format.
368     String hostname = Addressing.parseHostname(str);
369     int port = Addressing.parsePort(str);
370     return new ServerName(hostname, port, -1L);
371   }
372 }