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