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.hbase.classification.InterfaceAudience;
25  import org.apache.hadoop.hbase.classification.InterfaceStability;
26  import org.apache.hadoop.hbase.exceptions.DeserializationException;
27  import org.apache.hadoop.hbase.net.Address;
28  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
29  import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos;
30  import org.apache.hadoop.hbase.util.Addressing;
31  import org.apache.hadoop.hbase.util.Bytes;
32  
33  import java.io.Serializable;
34  import java.util.ArrayList;
35  import java.util.List;
36  import java.util.Locale;
37  import java.util.regex.Pattern;
38  
39  /**
40   * Instance of an HBase ServerName.
41   * A server name is used uniquely identifying a server instance in a cluster and is made
42   * of the combination of hostname, port, and startcode.  The startcode distingushes restarted
43   * servers on same hostname and port (startcode is usually timestamp of server startup). The
44   * {@link #toString()} format of ServerName is safe to use in the  filesystem and as znode name
45   * up in ZooKeeper.  Its format is:
46   * <code>&lt;hostname&gt; '{@link #SERVERNAME_SEPARATOR}' &lt;port&gt;
47   * '{@link #SERVERNAME_SEPARATOR}' &lt;startcode&gt;</code>.
48   * For example, if hostname is <code>www.example.org</code>, port is <code>1234</code>,
49   * and the startcode for the regionserver is <code>1212121212</code>, then
50   * the {@link #toString()} would be <code>www.example.org,1234,1212121212</code>.
51   * 
52   * <p>You can obtain a versioned serialized form of this class by calling
53   * {@link #getVersionedBytes()}.  To deserialize, call {@link #parseVersionedServerName(byte[])}
54   * 
55   * <p>Immutable.
56   */
57  @InterfaceAudience.Public
58  @InterfaceStability.Evolving
59  public class ServerName implements Comparable<ServerName>, Serializable {
60    private static final long serialVersionUID = 1367463982557264981L;
61  
62    /**
63     * Version for this class.
64     * Its a short rather than a byte so I can for sure distinguish between this
65     * version of this class and the version previous to this which did not have
66     * a version.
67     */
68    private static final short VERSION = 0;
69    static final byte [] VERSION_BYTES = Bytes.toBytes(VERSION);
70  
71    /**
72     * What to use if no startcode supplied.
73     */
74    public static final int NON_STARTCODE = -1;
75  
76    /**
77     * This character is used as separator between server hostname, port and
78     * startcode.
79     */
80    public static final String SERVERNAME_SEPARATOR = ",";
81  
82    public static final Pattern SERVERNAME_PATTERN =
83      Pattern.compile("[^" + SERVERNAME_SEPARATOR + "]+" +
84        SERVERNAME_SEPARATOR + Addressing.VALID_PORT_REGEX +
85        SERVERNAME_SEPARATOR + Addressing.VALID_PORT_REGEX + "$");
86  
87    /**
88     * What to use if server name is unknown.
89     */
90    public static final String UNKNOWN_SERVERNAME = "#unknown#";
91  
92    private final String servername;
93    private final String hostnameOnly;
94    private final int port;
95    private final long startcode;
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(getHostNameMinusDomain(this.hostnameOnly), this.port);
195   }
196 
197   /**
198    * @return {@link #getServerName()} as bytes with a short-sized prefix with
199    * the ServerName#VERSION of this class.
200    */
201   public synchronized byte [] getVersionedBytes() {
202     if (this.bytes == null) {
203       this.bytes = Bytes.add(VERSION_BYTES, Bytes.toBytes(getServerName()));
204     }
205     return this.bytes;
206   }
207 
208   public String getServerName() {
209     return servername;
210   }
211 
212   public String getHostname() {
213     return hostnameOnly;
214   }
215 
216   public String getHostnameLowerCase() {
217     return hostnameOnly.toLowerCase(Locale.ROOT);
218   }
219 
220   public int getPort() {
221     return port;
222   }
223 
224   public long getStartcode() {
225     return startcode;
226   }
227 
228   /**
229    * For internal use only.
230    * @param hostName
231    * @param port
232    * @param startcode
233    * @return Server name made of the concatenation of hostname, port and
234    * startcode formatted as <code>&lt;hostname&gt; ',' &lt;port&gt; ',' &lt;startcode&gt;</code>
235    */
236   static String getServerName(String hostName, int port, long startcode) {
237     final StringBuilder name = new StringBuilder(hostName.length() + 1 + 5 + 1 + 13);
238     name.append(hostName.toLowerCase(Locale.ROOT));
239     name.append(SERVERNAME_SEPARATOR);
240     name.append(port);
241     name.append(SERVERNAME_SEPARATOR);
242     name.append(startcode);
243     return name.toString();
244   }
245 
246   /**
247    * @param hostAndPort String in form of &lt;hostname&gt; ':' &lt;port&gt;
248    * @param startcode
249    * @return Server name made of the concatenation of hostname, port and
250    * startcode formatted as <code>&lt;hostname&gt; ',' &lt;port&gt; ',' &lt;startcode&gt;</code>
251    */
252   public static String getServerName(final String hostAndPort,
253       final long startcode) {
254     int index = hostAndPort.indexOf(":");
255     if (index <= 0) throw new IllegalArgumentException("Expected <hostname> ':' <port>");
256     return getServerName(hostAndPort.substring(0, index),
257       Integer.parseInt(hostAndPort.substring(index + 1)), startcode);
258   }
259 
260   /**
261    * @return Hostname and port formatted as described at
262    * {@link Addressing#createHostAndPortStr(String, int)}
263    */
264   public String getHostAndPort() {
265     return Addressing.createHostAndPortStr(this.hostnameOnly, this.port);
266   }
267 
268   /**
269    * @param serverName ServerName in form specified by {@link #getServerName()}
270    * @return The server start code parsed from <code>servername</code>
271    */
272   public static long getServerStartcodeFromServerName(final String serverName) {
273     int index = serverName.lastIndexOf(SERVERNAME_SEPARATOR);
274     return Long.parseLong(serverName.substring(index + 1));
275   }
276 
277   /**
278    * Utility method to excise the start code from a server name
279    * @param inServerName full server name
280    * @return server name less its start code
281    */
282   public static String getServerNameLessStartCode(String inServerName) {
283     if (inServerName != null && inServerName.length() > 0) {
284       int index = inServerName.lastIndexOf(SERVERNAME_SEPARATOR);
285       if (index > 0) {
286         return inServerName.substring(0, index);
287       }
288     }
289     return inServerName;
290   }
291 
292   @Override
293   public int compareTo(ServerName other) {
294     int compare;
295     if (other == null) {
296       return -1;
297     }
298     if (this.getHostname() == null) {
299       if (other.getHostname() != null) {
300         return 1;
301       }
302     } else {
303       if (other.getHostname() == null) {
304         return -1;
305       }
306       compare = this.getHostname().compareToIgnoreCase(other.getHostname());
307       if (compare != 0) {
308         return compare;
309       }
310     }
311     compare = this.getPort() - other.getPort();
312     if (compare != 0) {
313       return compare;
314     }
315     return Long.compare(this.getStartcode(), other.getStartcode());
316   }
317 
318   @Override
319   public int hashCode() {
320     return getServerName().hashCode();
321   }
322 
323   @Override
324   public boolean equals(Object o) {
325     if (this == o) return true;
326     if (o == null) return false;
327     if (!(o instanceof ServerName)) return false;
328     return this.compareTo((ServerName)o) == 0;
329   }
330 
331   /**
332    * @param left
333    * @param right
334    * @return True if <code>other</code> has same hostname and port.
335    */
336   public static boolean isSameHostnameAndPort(final ServerName left,
337       final ServerName right) {
338     if (left == null) return false;
339     if (right == null) return false;
340     return left.getHostname().compareToIgnoreCase(right.getHostname()) == 0 &&
341       left.getPort() == right.getPort();
342   }
343 
344   /**
345    * Use this method instantiating a {@link ServerName} from bytes
346    * gotten from a call to {@link #getVersionedBytes()}.  Will take care of the
347    * case where bytes were written by an earlier version of hbase.
348    * @param versionedBytes Pass bytes gotten from a call to {@link #getVersionedBytes()}
349    * @return A ServerName instance.
350    * @see #getVersionedBytes()
351    */
352   public static ServerName parseVersionedServerName(final byte [] versionedBytes) {
353     // Version is a short.
354     short version = Bytes.toShort(versionedBytes);
355     if (version == VERSION) {
356       int length = versionedBytes.length - Bytes.SIZEOF_SHORT;
357       return valueOf(Bytes.toString(versionedBytes, Bytes.SIZEOF_SHORT, length));
358     }
359     // Presume the bytes were written with an old version of hbase and that the
360     // bytes are actually a String of the form "'<hostname>' ':' '<port>'".
361     return valueOf(Bytes.toString(versionedBytes), NON_STARTCODE);
362   }
363 
364   /**
365    * @param str Either an instance of {@link ServerName#toString()} or a
366    * "'&lt;hostname&gt;' ':' '&lt;port&gt;'".
367    * @return A ServerName instance.
368    */
369   public static ServerName parseServerName(final String str) {
370     return SERVERNAME_PATTERN.matcher(str).matches()? valueOf(str) :
371         valueOf(str, NON_STARTCODE);
372   }
373 
374 
375   /**
376    * @return true if the String follows the pattern of {@link ServerName#toString()}, false
377    *  otherwise.
378    */
379   public static boolean isFullServerName(final String str){
380     if (str == null ||str.isEmpty()) return false;
381     return SERVERNAME_PATTERN.matcher(str).matches();
382   }
383 
384   /**
385    * Get a ServerName from the passed in data bytes.
386    * @param data Data with a serialize server name in it; can handle the old style
387    * servername where servername was host and port.  Works too with data that
388    * begins w/ the pb 'PBUF' magic and that is then followed by a protobuf that
389    * has a serialized {@link ServerName} in it.
390    * @return Returns null if <code>data</code> is null else converts passed data
391    * to a ServerName instance.
392    * @throws DeserializationException 
393    */
394   public static ServerName parseFrom(final byte [] data) throws DeserializationException {
395     if (data == null || data.length <= 0) return null;
396     if (ProtobufUtil.isPBMagicPrefix(data)) {
397       int prefixLen = ProtobufUtil.lengthOfPBMagic();
398       try {
399         ZooKeeperProtos.Master rss =
400           ZooKeeperProtos.Master.PARSER.parseFrom(data, prefixLen, data.length - prefixLen);
401         org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.ServerName sn = rss.getMaster();
402         return valueOf(sn.getHostName(), sn.getPort(), sn.getStartCode());
403       } catch (InvalidProtocolBufferException e) {
404         // A failed parse of the znode is pretty catastrophic. Rather than loop
405         // retrying hoping the bad bytes will changes, and rather than change
406         // the signature on this method to add an IOE which will send ripples all
407         // over the code base, throw a RuntimeException.  This should "never" happen.
408         // Fail fast if it does.
409         throw new DeserializationException(e);
410       }
411     }
412     // The str returned could be old style -- pre hbase-1502 -- which was
413     // hostname and port seperated by a colon rather than hostname, port and
414     // startcode delimited by a ','.
415     String str = Bytes.toString(data);
416     int index = str.indexOf(ServerName.SERVERNAME_SEPARATOR);
417     if (index != -1) {
418       // Presume its ServerName serialized with versioned bytes.
419       return ServerName.parseVersionedServerName(data);
420     }
421     // Presume it a hostname:port format.
422     String hostname = Addressing.parseHostname(str);
423     int port = Addressing.parsePort(str);
424     return valueOf(hostname, port, -1L);
425   }
426 
427   /**
428    * @return an Address constructed from the hostname and port carried by this ServerName
429    */
430   public Address getAddress() {
431     return Address.fromParts(getHostname(), getPort());
432   }
433 
434   /**
435    * @param left
436    * @param right
437    * @return True if <code>other</code> has same hostname and port.
438    */
439   public static boolean isSameAddress(final ServerName left,
440                                       final ServerName right) {
441     // TODO: Make this left.getAddress().equals(right.getAddress())
442     if (left == null) return false;
443     if (right == null) return false;
444     return left.getHostname().compareToIgnoreCase(right.getHostname()) == 0 &&
445       left.getPort() == right.getPort();
446   }
447 
448 }