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 java.io.Serializable;
22  import java.util.ArrayList;
23  import java.util.List;
24  import java.util.regex.Pattern;
25  
26  import org.apache.hadoop.hbase.classification.InterfaceAudience;
27  import org.apache.hadoop.hbase.classification.InterfaceStability;
28  import org.apache.hadoop.hbase.exceptions.DeserializationException;
29  import org.apache.hadoop.hbase.protobuf.ProtobufMagic;
30  import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos;
31  import org.apache.hadoop.hbase.util.Addressing;
32  import org.apache.hadoop.hbase.util.Bytes;
33  
34  import com.google.common.net.InetAddresses;
35  import com.google.protobuf.InvalidProtocolBufferException;
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);
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     return (int)(this.getStartcode() - other.getStartcode());
292   }
293 
294   @Override
295   public int hashCode() {
296     return getServerName().hashCode();
297   }
298 
299   @Override
300   public boolean equals(Object o) {
301     if (this == o) return true;
302     if (o == null) return false;
303     if (!(o instanceof ServerName)) return false;
304     return this.compareTo((ServerName)o) == 0;
305   }
306 
307   /**
308    * @param left
309    * @param right
310    * @return True if <code>other</code> has same hostname and port.
311    */
312   public static boolean isSameHostnameAndPort(final ServerName left,
313       final ServerName right) {
314     if (left == null) return false;
315     if (right == null) return false;
316     return left.getHostname().equals(right.getHostname()) &&
317       left.getPort() == right.getPort();
318   }
319 
320   /**
321    * Use this method instantiating a {@link ServerName} from bytes
322    * gotten from a call to {@link #getVersionedBytes()}.  Will take care of the
323    * case where bytes were written by an earlier version of hbase.
324    * @param versionedBytes Pass bytes gotten from a call to {@link #getVersionedBytes()}
325    * @return A ServerName instance.
326    * @see #getVersionedBytes()
327    */
328   public static ServerName parseVersionedServerName(final byte [] versionedBytes) {
329     // Version is a short.
330     short version = Bytes.toShort(versionedBytes);
331     if (version == VERSION) {
332       int length = versionedBytes.length - Bytes.SIZEOF_SHORT;
333       return valueOf(Bytes.toString(versionedBytes, Bytes.SIZEOF_SHORT, length));
334     }
335     // Presume the bytes were written with an old version of hbase and that the
336     // bytes are actually a String of the form "'<hostname>' ':' '<port>'".
337     return valueOf(Bytes.toString(versionedBytes), NON_STARTCODE);
338   }
339 
340   /**
341    * @param str Either an instance of {@link ServerName#toString()} or a
342    * "'<hostname>' ':' '<port>'".
343    * @return A ServerName instance.
344    */
345   public static ServerName parseServerName(final String str) {
346     return SERVERNAME_PATTERN.matcher(str).matches()? valueOf(str) :
347         valueOf(str, NON_STARTCODE);
348   }
349 
350 
351   /**
352    * @return true if the String follows the pattern of {@link ServerName#toString()}, false
353    *  otherwise.
354    */
355   public static boolean isFullServerName(final String str){
356     if (str == null ||str.isEmpty()) return false;
357     return SERVERNAME_PATTERN.matcher(str).matches();
358   }
359 
360   /**
361    * Get a ServerName from the passed in data bytes.
362    * @param data Data with a serialize server name in it; can handle the old style
363    * servername where servername was host and port.  Works too with data that
364    * begins w/ the pb 'PBUF' magic and that is then followed by a protobuf that
365    * has a serialized {@link ServerName} in it.
366    * @return Returns null if <code>data</code> is null else converts passed data
367    * to a ServerName instance.
368    * @throws DeserializationException 
369    */
370   public static ServerName parseFrom(final byte [] data) throws DeserializationException {
371     if (data == null || data.length <= 0) return null;
372     if (ProtobufMagic.isPBMagicPrefix(data)) {
373       int prefixLen = ProtobufMagic.lengthOfPBMagic();
374       try {
375         ZooKeeperProtos.Master rss =
376           ZooKeeperProtos.Master.PARSER.parseFrom(data, prefixLen, data.length - prefixLen);
377         org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.ServerName sn = rss.getMaster();
378         return valueOf(sn.getHostName(), sn.getPort(), sn.getStartCode());
379       } catch (InvalidProtocolBufferException e) {
380         // A failed parse of the znode is pretty catastrophic. Rather than loop
381         // retrying hoping the bad bytes will changes, and rather than change
382         // the signature on this method to add an IOE which will send ripples all
383         // over the code base, throw a RuntimeException.  This should "never" happen.
384         // Fail fast if it does.
385         throw new DeserializationException(e);
386       }
387     }
388     // The str returned could be old style -- pre hbase-1502 -- which was
389     // hostname and port seperated by a colon rather than hostname, port and
390     // startcode delimited by a ','.
391     String str = Bytes.toString(data);
392     int index = str.indexOf(ServerName.SERVERNAME_SEPARATOR);
393     if (index != -1) {
394       // Presume its ServerName serialized with versioned bytes.
395       return ServerName.parseVersionedServerName(data);
396     }
397     // Presume it a hostname:port format.
398     String hostname = Addressing.parseHostname(str);
399     int port = Addressing.parsePort(str);
400     return valueOf(hostname, port, -1L);
401   }
402 }