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