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