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