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