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