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