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