1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.hadoop.hbase.protobuf;
19
20
21 import static com.google.protobuf.HBaseZeroCopyByteString.zeroCopyGetBytes;
22 import static org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.RegionSpecifier.RegionSpecifierType.REGION_NAME;
23
24 import java.io.ByteArrayOutputStream;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.io.InterruptedIOException;
28 import java.lang.reflect.Constructor;
29 import java.lang.reflect.InvocationTargetException;
30 import java.lang.reflect.Method;
31 import java.lang.reflect.ParameterizedType;
32 import java.lang.reflect.Type;
33 import java.nio.ByteBuffer;
34 import java.security.PrivilegedExceptionAction;
35 import java.util.ArrayList;
36 import java.util.Collection;
37 import java.util.Collections;
38 import java.util.HashMap;
39 import java.util.HashSet;
40 import java.util.List;
41 import java.util.Map;
42 import java.util.Map.Entry;
43 import java.util.NavigableSet;
44 import java.util.Set;
45 import java.util.concurrent.TimeUnit;
46
47 import org.apache.hadoop.conf.Configuration;
48 import org.apache.hadoop.fs.Path;
49 import org.apache.hadoop.hbase.Cell;
50 import org.apache.hadoop.hbase.CellScanner;
51 import org.apache.hadoop.hbase.CellUtil;
52 import org.apache.hadoop.hbase.DoNotRetryIOException;
53 import org.apache.hadoop.hbase.HBaseConfiguration;
54 import org.apache.hadoop.hbase.HConstants;
55 import org.apache.hadoop.hbase.HRegionInfo;
56 import org.apache.hadoop.hbase.HTableDescriptor;
57 import org.apache.hadoop.hbase.KeyValue;
58 import org.apache.hadoop.hbase.NamespaceDescriptor;
59 import org.apache.hadoop.hbase.ServerName;
60 import org.apache.hadoop.hbase.TableName;
61 import org.apache.hadoop.hbase.Tag;
62 import org.apache.hadoop.hbase.classification.InterfaceAudience;
63 import org.apache.hadoop.hbase.client.Append;
64 import org.apache.hadoop.hbase.client.Consistency;
65 import org.apache.hadoop.hbase.client.Delete;
66 import org.apache.hadoop.hbase.client.Durability;
67 import org.apache.hadoop.hbase.client.Get;
68 import org.apache.hadoop.hbase.client.Increment;
69 import org.apache.hadoop.hbase.client.Mutation;
70 import org.apache.hadoop.hbase.client.Put;
71 import org.apache.hadoop.hbase.client.Result;
72 import org.apache.hadoop.hbase.client.Scan;
73 import org.apache.hadoop.hbase.client.metrics.ScanMetrics;
74 import org.apache.hadoop.hbase.client.security.SecurityCapability;
75 import org.apache.hadoop.hbase.exceptions.DeserializationException;
76 import org.apache.hadoop.hbase.filter.ByteArrayComparable;
77 import org.apache.hadoop.hbase.filter.Filter;
78 import org.apache.hadoop.hbase.io.LimitInputStream;
79 import org.apache.hadoop.hbase.io.TimeRange;
80 import org.apache.hadoop.hbase.protobuf.generated.AccessControlProtos;
81 import org.apache.hadoop.hbase.protobuf.generated.AccessControlProtos.AccessControlService;
82 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.AdminService;
83 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.CloseRegionRequest;
84 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.CloseRegionResponse;
85 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetOnlineRegionRequest;
86 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetOnlineRegionResponse;
87 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetRegionInfoRequest;
88 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetRegionInfoResponse;
89 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetServerInfoRequest;
90 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetServerInfoResponse;
91 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetStoreFileRequest;
92 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetStoreFileResponse;
93 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.MergeRegionsRequest;
94 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.OpenRegionRequest;
95 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.ServerInfo;
96 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.SplitRegionRequest;
97 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.WarmupRegionRequest;
98 import org.apache.hadoop.hbase.protobuf.generated.AuthenticationProtos;
99 import org.apache.hadoop.hbase.protobuf.generated.CellProtos;
100 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos;
101 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.BulkLoadHFileRequest;
102 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.BulkLoadHFileResponse;
103 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ClientService;
104 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.Column;
105 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.CoprocessorServiceCall;
106 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.CoprocessorServiceRequest;
107 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.CoprocessorServiceResponse;
108 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.GetRequest;
109 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.GetResponse;
110 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutationProto;
111 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutationProto.ColumnValue;
112 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutationProto.ColumnValue.QualifierValue;
113 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutationProto.DeleteType;
114 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutationProto.MutationType;
115 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ScanRequest;
116 import org.apache.hadoop.hbase.protobuf.generated.ClusterStatusProtos;
117 import org.apache.hadoop.hbase.protobuf.generated.ClusterStatusProtos.RegionLoad;
118 import org.apache.hadoop.hbase.protobuf.generated.ComparatorProtos;
119 import org.apache.hadoop.hbase.protobuf.generated.FilterProtos;
120 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos;
121 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.NameBytesPair;
122 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.RegionInfo;
123 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.RegionSpecifier;
124 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.RegionSpecifier.RegionSpecifierType;
125 import org.apache.hadoop.hbase.protobuf.generated.HFileProtos;
126 import org.apache.hadoop.hbase.protobuf.generated.MapReduceProtos;
127 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos;
128 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.CreateTableRequest;
129 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetTableDescriptorsResponse;
130 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.MasterService;
131 import org.apache.hadoop.hbase.protobuf.generated.QuotaProtos;
132 import org.apache.hadoop.hbase.protobuf.generated.RegionServerStatusProtos.RegionServerReportRequest;
133 import org.apache.hadoop.hbase.protobuf.generated.RegionServerStatusProtos.RegionServerStartupRequest;
134 import org.apache.hadoop.hbase.protobuf.generated.WALProtos;
135 import org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor;
136 import org.apache.hadoop.hbase.protobuf.generated.WALProtos.FlushDescriptor;
137 import org.apache.hadoop.hbase.protobuf.generated.WALProtos.FlushDescriptor.FlushAction;
138 import org.apache.hadoop.hbase.protobuf.generated.WALProtos.RegionEventDescriptor;
139 import org.apache.hadoop.hbase.protobuf.generated.WALProtos.RegionEventDescriptor.EventType;
140 import org.apache.hadoop.hbase.protobuf.generated.WALProtos.BulkLoadDescriptor;
141 import org.apache.hadoop.hbase.protobuf.generated.WALProtos.StoreDescriptor;
142 import org.apache.hadoop.hbase.quotas.QuotaScope;
143 import org.apache.hadoop.hbase.quotas.QuotaType;
144 import org.apache.hadoop.hbase.quotas.ThrottleType;
145 import org.apache.hadoop.hbase.replication.ReplicationLoadSink;
146 import org.apache.hadoop.hbase.replication.ReplicationLoadSource;
147 import org.apache.hadoop.hbase.security.User;
148 import org.apache.hadoop.hbase.security.access.Permission;
149 import org.apache.hadoop.hbase.security.access.TablePermission;
150 import org.apache.hadoop.hbase.security.access.UserPermission;
151 import org.apache.hadoop.hbase.security.token.AuthenticationTokenIdentifier;
152 import org.apache.hadoop.hbase.security.visibility.Authorizations;
153 import org.apache.hadoop.hbase.security.visibility.CellVisibility;
154 import org.apache.hadoop.hbase.util.ByteStringer;
155 import org.apache.hadoop.hbase.util.Bytes;
156 import org.apache.hadoop.hbase.util.DynamicClassLoader;
157 import org.apache.hadoop.hbase.util.ExceptionUtil;
158 import org.apache.hadoop.hbase.util.Methods;
159 import org.apache.hadoop.hbase.util.Pair;
160 import org.apache.hadoop.hbase.util.VersionInfo;
161 import org.apache.hadoop.io.Text;
162 import org.apache.hadoop.ipc.RemoteException;
163 import org.apache.hadoop.security.token.Token;
164
165 import com.google.common.collect.ArrayListMultimap;
166 import com.google.common.collect.ListMultimap;
167 import com.google.common.collect.Lists;
168 import com.google.protobuf.ByteString;
169 import com.google.protobuf.CodedInputStream;
170 import com.google.protobuf.InvalidProtocolBufferException;
171 import com.google.protobuf.Message;
172 import com.google.protobuf.Parser;
173 import com.google.protobuf.RpcChannel;
174 import com.google.protobuf.RpcController;
175 import com.google.protobuf.Service;
176 import com.google.protobuf.ServiceException;
177 import com.google.protobuf.TextFormat;
178
179
180
181
182 @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="DP_CREATE_CLASSLOADER_INSIDE_DO_PRIVILEGED",
183 justification="None. Address sometime.")
184 @InterfaceAudience.Private
185 public final class ProtobufUtil {
186
187 private ProtobufUtil() {
188 }
189
190
191
192
193 private final static Map<String, Class<?>>
194 PRIMITIVES = new HashMap<String, Class<?>>();
195
196
197
198
199
200
201 private final static Cell[] EMPTY_CELL_ARRAY = new Cell[]{};
202 private final static Result EMPTY_RESULT = Result.create(EMPTY_CELL_ARRAY);
203 final static Result EMPTY_RESULT_EXISTS_TRUE = Result.create(null, true);
204 final static Result EMPTY_RESULT_EXISTS_FALSE = Result.create(null, false);
205 private final static Result EMPTY_RESULT_STALE = Result.create(EMPTY_CELL_ARRAY, null, true);
206 private final static Result EMPTY_RESULT_EXISTS_TRUE_STALE
207 = Result.create((Cell[])null, true, true);
208 private final static Result EMPTY_RESULT_EXISTS_FALSE_STALE
209 = Result.create((Cell[])null, false, true);
210
211 private final static ClientProtos.Result EMPTY_RESULT_PB;
212 private final static ClientProtos.Result EMPTY_RESULT_PB_EXISTS_TRUE;
213 private final static ClientProtos.Result EMPTY_RESULT_PB_EXISTS_FALSE;
214 private final static ClientProtos.Result EMPTY_RESULT_PB_STALE;
215 private final static ClientProtos.Result EMPTY_RESULT_PB_EXISTS_TRUE_STALE;
216 private final static ClientProtos.Result EMPTY_RESULT_PB_EXISTS_FALSE_STALE;
217
218
219 static {
220 ClientProtos.Result.Builder builder = ClientProtos.Result.newBuilder();
221
222 builder.setExists(true);
223 builder.setAssociatedCellCount(0);
224 EMPTY_RESULT_PB_EXISTS_TRUE = builder.build();
225
226 builder.setStale(true);
227 EMPTY_RESULT_PB_EXISTS_TRUE_STALE = builder.build();
228 builder.clear();
229
230 builder.setExists(false);
231 builder.setAssociatedCellCount(0);
232 EMPTY_RESULT_PB_EXISTS_FALSE = builder.build();
233 builder.setStale(true);
234 EMPTY_RESULT_PB_EXISTS_FALSE_STALE = builder.build();
235
236 builder.clear();
237 builder.setAssociatedCellCount(0);
238 EMPTY_RESULT_PB = builder.build();
239 builder.setStale(true);
240 EMPTY_RESULT_PB_STALE = builder.build();
241 }
242
243
244
245
246 private final static ClassLoader CLASS_LOADER;
247
248 static {
249 ClassLoader parent = ProtobufUtil.class.getClassLoader();
250 Configuration conf = HBaseConfiguration.create();
251 CLASS_LOADER = new DynamicClassLoader(conf, parent);
252
253 PRIMITIVES.put(Boolean.TYPE.getName(), Boolean.TYPE);
254 PRIMITIVES.put(Byte.TYPE.getName(), Byte.TYPE);
255 PRIMITIVES.put(Character.TYPE.getName(), Character.TYPE);
256 PRIMITIVES.put(Short.TYPE.getName(), Short.TYPE);
257 PRIMITIVES.put(Integer.TYPE.getName(), Integer.TYPE);
258 PRIMITIVES.put(Long.TYPE.getName(), Long.TYPE);
259 PRIMITIVES.put(Float.TYPE.getName(), Float.TYPE);
260 PRIMITIVES.put(Double.TYPE.getName(), Double.TYPE);
261 PRIMITIVES.put(Void.TYPE.getName(), Void.TYPE);
262 }
263
264
265
266
267
268
269 public static final byte [] PB_MAGIC = new byte [] {'P', 'B', 'U', 'F'};
270 private static final String PB_MAGIC_STR = Bytes.toString(PB_MAGIC);
271
272
273
274
275
276
277
278
279 public static byte [] prependPBMagic(final byte [] bytes) {
280 return Bytes.add(PB_MAGIC, bytes);
281 }
282
283
284
285
286
287 public static boolean isPBMagicPrefix(final byte [] bytes) {
288 if (bytes == null) return false;
289 return isPBMagicPrefix(bytes, 0, bytes.length);
290 }
291
292
293
294
295
296
297
298 public static boolean isPBMagicPrefix(final byte [] bytes, int offset, int len) {
299 if (bytes == null || len < PB_MAGIC.length) return false;
300 return Bytes.compareTo(PB_MAGIC, 0, PB_MAGIC.length, bytes, offset, PB_MAGIC.length) == 0;
301 }
302
303
304
305
306
307 public static void expectPBMagicPrefix(final byte [] bytes) throws DeserializationException {
308 if (!isPBMagicPrefix(bytes)) {
309 throw new DeserializationException("Missing pb magic " + PB_MAGIC_STR + " prefix");
310 }
311 }
312
313
314
315
316 public static int lengthOfPBMagic() {
317 return PB_MAGIC.length;
318 }
319
320
321
322
323
324
325
326
327
328 public static IOException getRemoteException(ServiceException se) {
329 Throwable e = se.getCause();
330 if (e == null) {
331 return new IOException(se);
332 }
333 if (ExceptionUtil.isInterrupt(e)) {
334 return ExceptionUtil.asInterrupt(e);
335 }
336 if (e instanceof RemoteException) {
337 e = ((RemoteException) e).unwrapRemoteException();
338 }
339 return e instanceof IOException ? (IOException) e : new IOException(se);
340 }
341
342
343
344
345
346
347
348
349 public static HBaseProtos.ServerName
350 toServerName(final ServerName serverName) {
351 if (serverName == null) return null;
352 HBaseProtos.ServerName.Builder builder =
353 HBaseProtos.ServerName.newBuilder();
354 builder.setHostName(serverName.getHostname());
355 if (serverName.getPort() >= 0) {
356 builder.setPort(serverName.getPort());
357 }
358 if (serverName.getStartcode() >= 0) {
359 builder.setStartCode(serverName.getStartcode());
360 }
361 return builder.build();
362 }
363
364
365
366
367
368
369
370 public static ServerName toServerName(final HBaseProtos.ServerName proto) {
371 if (proto == null) return null;
372 String hostName = proto.getHostName();
373 long startCode = -1;
374 int port = -1;
375 if (proto.hasPort()) {
376 port = proto.getPort();
377 }
378 if (proto.hasStartCode()) {
379 startCode = proto.getStartCode();
380 }
381 return ServerName.valueOf(hostName, port, startCode);
382 }
383
384
385
386
387
388
389
390 public static HTableDescriptor[] getHTableDescriptorArray(GetTableDescriptorsResponse proto) {
391 if (proto == null) return null;
392
393 HTableDescriptor[] ret = new HTableDescriptor[proto.getTableSchemaCount()];
394 for (int i = 0; i < proto.getTableSchemaCount(); ++i) {
395 ret[i] = HTableDescriptor.convert(proto.getTableSchema(i));
396 }
397 return ret;
398 }
399
400
401
402
403
404
405
406 public static byte [][] getSplitKeysArray(final CreateTableRequest proto) {
407 byte [][] splitKeys = new byte[proto.getSplitKeysCount()][];
408 for (int i = 0; i < proto.getSplitKeysCount(); ++i) {
409 splitKeys[i] = proto.getSplitKeys(i).toByteArray();
410 }
411 return splitKeys;
412 }
413
414
415
416
417 public static Durability toDurability(
418 final ClientProtos.MutationProto.Durability proto) {
419 switch(proto) {
420 case USE_DEFAULT:
421 return Durability.USE_DEFAULT;
422 case SKIP_WAL:
423 return Durability.SKIP_WAL;
424 case ASYNC_WAL:
425 return Durability.ASYNC_WAL;
426 case SYNC_WAL:
427 return Durability.SYNC_WAL;
428 case FSYNC_WAL:
429 return Durability.FSYNC_WAL;
430 default:
431 return Durability.USE_DEFAULT;
432 }
433 }
434
435
436
437
438 public static ClientProtos.MutationProto.Durability toDurability(
439 final Durability d) {
440 switch(d) {
441 case USE_DEFAULT:
442 return ClientProtos.MutationProto.Durability.USE_DEFAULT;
443 case SKIP_WAL:
444 return ClientProtos.MutationProto.Durability.SKIP_WAL;
445 case ASYNC_WAL:
446 return ClientProtos.MutationProto.Durability.ASYNC_WAL;
447 case SYNC_WAL:
448 return ClientProtos.MutationProto.Durability.SYNC_WAL;
449 case FSYNC_WAL:
450 return ClientProtos.MutationProto.Durability.FSYNC_WAL;
451 default:
452 return ClientProtos.MutationProto.Durability.USE_DEFAULT;
453 }
454 }
455
456
457
458
459
460
461
462
463 public static Get toGet(
464 final ClientProtos.Get proto) throws IOException {
465 if (proto == null) return null;
466 byte[] row = zeroCopyGetBytes(proto.getRow());
467 Get get = new Get(row);
468 if (proto.hasCacheBlocks()) {
469 get.setCacheBlocks(proto.getCacheBlocks());
470 }
471 if (proto.hasMaxVersions()) {
472 get.setMaxVersions(proto.getMaxVersions());
473 }
474 if (proto.hasStoreLimit()) {
475 get.setMaxResultsPerColumnFamily(proto.getStoreLimit());
476 }
477 if (proto.hasStoreOffset()) {
478 get.setRowOffsetPerColumnFamily(proto.getStoreOffset());
479 }
480 if (proto.getCfTimeRangeCount() > 0) {
481 for (HBaseProtos.ColumnFamilyTimeRange cftr : proto.getCfTimeRangeList()) {
482 TimeRange timeRange = protoToTimeRange(cftr.getTimeRange());
483 get.setColumnFamilyTimeRange(cftr.getColumnFamily().toByteArray(),
484 timeRange.getMin(), timeRange.getMax());
485 }
486 }
487 if (proto.hasTimeRange()) {
488 TimeRange timeRange = protoToTimeRange(proto.getTimeRange());
489 get.setTimeRange(timeRange.getMin(), timeRange.getMax());
490 }
491 if (proto.hasFilter()) {
492 FilterProtos.Filter filter = proto.getFilter();
493 get.setFilter(ProtobufUtil.toFilter(filter));
494 }
495 for (NameBytesPair attribute: proto.getAttributeList()) {
496 get.setAttribute(attribute.getName(), attribute.getValue().toByteArray());
497 }
498 if (proto.getColumnCount() > 0) {
499 for (Column column: proto.getColumnList()) {
500 byte[] family = column.getFamily().toByteArray();
501 if (column.getQualifierCount() > 0) {
502 for (ByteString qualifier: column.getQualifierList()) {
503 get.addColumn(family, qualifier.toByteArray());
504 }
505 } else {
506 get.addFamily(family);
507 }
508 }
509 }
510 if (proto.hasExistenceOnly() && proto.getExistenceOnly()){
511 get.setCheckExistenceOnly(true);
512 }
513 if (proto.hasClosestRowBefore() && proto.getClosestRowBefore()){
514 get.setClosestRowBefore(true);
515 }
516 if (proto.hasConsistency()) {
517 get.setConsistency(toConsistency(proto.getConsistency()));
518 }
519 if (proto.hasLoadColumnFamiliesOnDemand()) {
520 get.setLoadColumnFamiliesOnDemand(proto.getLoadColumnFamiliesOnDemand());
521 }
522 return get;
523 }
524
525 public static Consistency toConsistency(ClientProtos.Consistency consistency) {
526 switch (consistency) {
527 case STRONG : return Consistency.STRONG;
528 case TIMELINE : return Consistency.TIMELINE;
529 default : return Consistency.STRONG;
530 }
531 }
532
533 public static ClientProtos.Consistency toConsistency(Consistency consistency) {
534 switch (consistency) {
535 case STRONG : return ClientProtos.Consistency.STRONG;
536 case TIMELINE : return ClientProtos.Consistency.TIMELINE;
537 default : return ClientProtos.Consistency.STRONG;
538 }
539 }
540
541
542
543
544
545
546
547
548 public static Put toPut(final MutationProto proto)
549 throws IOException {
550 return toPut(proto, null);
551 }
552
553
554
555
556
557
558
559
560
561 public static Put toPut(final MutationProto proto, final CellScanner cellScanner)
562 throws IOException {
563
564 MutationType type = proto.getMutateType();
565 assert type == MutationType.PUT: type.name();
566 long timestamp = proto.hasTimestamp()? proto.getTimestamp(): HConstants.LATEST_TIMESTAMP;
567 Put put = proto.hasRow() ? new Put(zeroCopyGetBytes(proto.getRow()), timestamp) : null;
568 int cellCount = proto.hasAssociatedCellCount()? proto.getAssociatedCellCount(): 0;
569 if (cellCount > 0) {
570
571 if (cellScanner == null) {
572 throw new DoNotRetryIOException("Cell count of " + cellCount + " but no cellScanner: " +
573 toShortString(proto));
574 }
575 for (int i = 0; i < cellCount; i++) {
576 if (!cellScanner.advance()) {
577 throw new DoNotRetryIOException("Cell count of " + cellCount + " but at index " + i +
578 " no cell returned: " + toShortString(proto));
579 }
580 Cell cell = cellScanner.current();
581 if (put == null) {
582 put = new Put(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength(), timestamp);
583 }
584 put.add(cell);
585 }
586 } else {
587 if (put == null) {
588 throw new IllegalArgumentException("row cannot be null");
589 }
590
591 for (ColumnValue column: proto.getColumnValueList()) {
592 byte[] family = zeroCopyGetBytes(column.getFamily());
593 for (QualifierValue qv: column.getQualifierValueList()) {
594 if (!qv.hasValue()) {
595 throw new DoNotRetryIOException(
596 "Missing required field: qualifier value");
597 }
598 ByteBuffer qualifier =
599 qv.hasQualifier() ? qv.getQualifier().asReadOnlyByteBuffer() : null;
600 ByteBuffer value =
601 qv.hasValue() ? qv.getValue().asReadOnlyByteBuffer() : null;
602 long ts = timestamp;
603 if (qv.hasTimestamp()) {
604 ts = qv.getTimestamp();
605 }
606 byte[] tags;
607 if (qv.hasTags()) {
608 tags = zeroCopyGetBytes(qv.getTags());
609 Object[] array = Tag.asList(tags, 0, (short)tags.length).toArray();
610 Tag[] tagArray = new Tag[array.length];
611 for(int i = 0; i< array.length; i++) {
612 tagArray[i] = (Tag)array[i];
613 }
614 if(qv.hasDeleteType()) {
615 byte[] qual = qv.hasQualifier() ? zeroCopyGetBytes(qv.getQualifier()) : null;
616 put.add(new KeyValue(zeroCopyGetBytes(proto.getRow()), family, qual, ts,
617 fromDeleteType(qv.getDeleteType()), null, tags));
618 } else {
619 put.addImmutable(family, qualifier, ts, value, tagArray);
620 }
621 } else {
622 if(qv.hasDeleteType()) {
623 byte[] qual = qv.hasQualifier() ? zeroCopyGetBytes(qv.getQualifier()) : null;
624 put.add(new KeyValue(zeroCopyGetBytes(proto.getRow()), family, qual, ts,
625 fromDeleteType(qv.getDeleteType())));
626 } else{
627 put.addImmutable(family, qualifier, ts, value);
628 }
629 }
630 }
631 }
632 }
633 put.setDurability(toDurability(proto.getDurability()));
634 for (NameBytesPair attribute: proto.getAttributeList()) {
635 put.setAttribute(attribute.getName(), attribute.getValue().toByteArray());
636 }
637 return put;
638 }
639
640
641
642
643
644
645
646
647 public static Delete toDelete(final MutationProto proto)
648 throws IOException {
649 return toDelete(proto, null);
650 }
651
652
653
654
655
656
657
658
659
660 public static Delete toDelete(final MutationProto proto, final CellScanner cellScanner)
661 throws IOException {
662 MutationType type = proto.getMutateType();
663 assert type == MutationType.DELETE : type.name();
664 long timestamp = proto.hasTimestamp() ? proto.getTimestamp() : HConstants.LATEST_TIMESTAMP;
665 Delete delete = proto.hasRow() ? new Delete(zeroCopyGetBytes(proto.getRow()), timestamp) : null;
666 int cellCount = proto.hasAssociatedCellCount()? proto.getAssociatedCellCount(): 0;
667 if (cellCount > 0) {
668
669 if (cellScanner == null) {
670
671 throw new DoNotRetryIOException("Cell count of " + cellCount + " but no cellScanner: " +
672 TextFormat.shortDebugString(proto));
673 }
674 for (int i = 0; i < cellCount; i++) {
675 if (!cellScanner.advance()) {
676
677 throw new DoNotRetryIOException("Cell count of " + cellCount + " but at index " + i +
678 " no cell returned: " + TextFormat.shortDebugString(proto));
679 }
680 Cell cell = cellScanner.current();
681 if (delete == null) {
682 delete =
683 new Delete(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength(), timestamp);
684 }
685 delete.addDeleteMarker(cell);
686 }
687 } else {
688 if (delete == null) {
689 throw new IllegalArgumentException("row cannot be null");
690 }
691 for (ColumnValue column: proto.getColumnValueList()) {
692 byte[] family = column.getFamily().toByteArray();
693 for (QualifierValue qv: column.getQualifierValueList()) {
694 DeleteType deleteType = qv.getDeleteType();
695 byte[] qualifier = null;
696 if (qv.hasQualifier()) {
697 qualifier = qv.getQualifier().toByteArray();
698 }
699 long ts = HConstants.LATEST_TIMESTAMP;
700 if (qv.hasTimestamp()) {
701 ts = qv.getTimestamp();
702 }
703 if (deleteType == DeleteType.DELETE_ONE_VERSION) {
704 delete.deleteColumn(family, qualifier, ts);
705 } else if (deleteType == DeleteType.DELETE_MULTIPLE_VERSIONS) {
706 delete.deleteColumns(family, qualifier, ts);
707 } else if (deleteType == DeleteType.DELETE_FAMILY_VERSION) {
708 delete.deleteFamilyVersion(family, ts);
709 } else {
710 delete.deleteFamily(family, ts);
711 }
712 }
713 }
714 }
715 delete.setDurability(toDurability(proto.getDurability()));
716 for (NameBytesPair attribute: proto.getAttributeList()) {
717 delete.setAttribute(attribute.getName(), attribute.getValue().toByteArray());
718 }
719 return delete;
720 }
721
722
723
724
725
726
727
728
729 public static Append toAppend(final MutationProto proto, final CellScanner cellScanner)
730 throws IOException {
731 MutationType type = proto.getMutateType();
732 assert type == MutationType.APPEND : type.name();
733 byte [] row = proto.hasRow()? zeroCopyGetBytes(proto.getRow()): null;
734 Append append = null;
735 int cellCount = proto.hasAssociatedCellCount()? proto.getAssociatedCellCount(): 0;
736 if (cellCount > 0) {
737
738 if (cellScanner == null) {
739 throw new DoNotRetryIOException("Cell count of " + cellCount + " but no cellScanner: " +
740 toShortString(proto));
741 }
742 for (int i = 0; i < cellCount; i++) {
743 if (!cellScanner.advance()) {
744 throw new DoNotRetryIOException("Cell count of " + cellCount + " but at index " + i +
745 " no cell returned: " + toShortString(proto));
746 }
747 Cell cell = cellScanner.current();
748 if (append == null) {
749 append = new Append(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength());
750 }
751 append.add(cell);
752 }
753 } else {
754 append = new Append(row);
755 for (ColumnValue column: proto.getColumnValueList()) {
756 byte[] family = zeroCopyGetBytes(column.getFamily());
757 for (QualifierValue qv: column.getQualifierValueList()) {
758 byte[] qualifier = zeroCopyGetBytes(qv.getQualifier());
759 if (!qv.hasValue()) {
760 throw new DoNotRetryIOException(
761 "Missing required field: qualifier value");
762 }
763 byte[] value = zeroCopyGetBytes(qv.getValue());
764 byte[] tags = null;
765 if (qv.hasTags()) {
766 tags = zeroCopyGetBytes(qv.getTags());
767 }
768 append.add(CellUtil.createCell(row, family, qualifier, qv.getTimestamp(),
769 KeyValue.Type.Put, value, tags));
770 }
771 }
772 }
773 append.setDurability(toDurability(proto.getDurability()));
774 for (NameBytesPair attribute: proto.getAttributeList()) {
775 append.setAttribute(attribute.getName(), attribute.getValue().toByteArray());
776 }
777 return append;
778 }
779
780
781
782
783
784
785
786
787 public static Mutation toMutation(final MutationProto proto) throws IOException {
788 MutationType type = proto.getMutateType();
789 if (type == MutationType.APPEND) {
790 return toAppend(proto, null);
791 }
792 if (type == MutationType.DELETE) {
793 return toDelete(proto, null);
794 }
795 if (type == MutationType.PUT) {
796 return toPut(proto, null);
797 }
798 throw new IOException("Unknown mutation type " + type);
799 }
800
801
802
803
804
805
806
807
808 public static Increment toIncrement(final MutationProto proto, final CellScanner cellScanner)
809 throws IOException {
810 MutationType type = proto.getMutateType();
811 assert type == MutationType.INCREMENT : type.name();
812 byte [] row = proto.hasRow()? zeroCopyGetBytes(proto.getRow()): null;
813 Increment increment = null;
814 int cellCount = proto.hasAssociatedCellCount()? proto.getAssociatedCellCount(): 0;
815 if (cellCount > 0) {
816
817 if (cellScanner == null) {
818 throw new DoNotRetryIOException("Cell count of " + cellCount + " but no cellScanner: " +
819 TextFormat.shortDebugString(proto));
820 }
821 for (int i = 0; i < cellCount; i++) {
822 if (!cellScanner.advance()) {
823 throw new DoNotRetryIOException("Cell count of " + cellCount + " but at index " + i +
824 " no cell returned: " + TextFormat.shortDebugString(proto));
825 }
826 Cell cell = cellScanner.current();
827 if (increment == null) {
828 increment = new Increment(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength());
829 }
830 increment.add(cell);
831 }
832 } else {
833 increment = new Increment(row);
834 for (ColumnValue column: proto.getColumnValueList()) {
835 byte[] family = zeroCopyGetBytes(column.getFamily());
836 for (QualifierValue qv: column.getQualifierValueList()) {
837 byte[] qualifier = zeroCopyGetBytes(qv.getQualifier());
838 if (!qv.hasValue()) {
839 throw new DoNotRetryIOException("Missing required field: qualifier value");
840 }
841 byte[] value = zeroCopyGetBytes(qv.getValue());
842 byte[] tags = null;
843 if (qv.hasTags()) {
844 tags = zeroCopyGetBytes(qv.getTags());
845 }
846 increment.add(CellUtil.createCell(row, family, qualifier, qv.getTimestamp(),
847 KeyValue.Type.Put, value, tags));
848 }
849 }
850 }
851 if (proto.hasTimeRange()) {
852 TimeRange timeRange = protoToTimeRange(proto.getTimeRange());
853 increment.setTimeRange(timeRange.getMin(), timeRange.getMax());
854 }
855 increment.setDurability(toDurability(proto.getDurability()));
856 for (NameBytesPair attribute : proto.getAttributeList()) {
857 increment.setAttribute(attribute.getName(), attribute.getValue().toByteArray());
858 }
859 return increment;
860 }
861
862
863
864
865
866
867
868
869 public static Get toGet(final MutationProto proto, final CellScanner cellScanner)
870 throws IOException {
871 MutationType type = proto.getMutateType();
872 assert type == MutationType.INCREMENT || type == MutationType.APPEND : type.name();
873 byte[] row = proto.hasRow() ? zeroCopyGetBytes(proto.getRow()) : null;
874 Get get = null;
875 int cellCount = proto.hasAssociatedCellCount() ? proto.getAssociatedCellCount() : 0;
876 if (cellCount > 0) {
877
878 if (cellScanner == null) {
879 throw new DoNotRetryIOException("Cell count of " + cellCount + " but no cellScanner: "
880 + TextFormat.shortDebugString(proto));
881 }
882 for (int i = 0; i < cellCount; i++) {
883 if (!cellScanner.advance()) {
884 throw new DoNotRetryIOException("Cell count of " + cellCount + " but at index " + i
885 + " no cell returned: " + TextFormat.shortDebugString(proto));
886 }
887 Cell cell = cellScanner.current();
888 if (get == null) {
889 get = new Get(Bytes.copy(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength()));
890 }
891 get.addColumn(Bytes.copy(cell.getFamilyArray(), cell.getFamilyOffset(),
892 cell.getFamilyLength()), Bytes.copy(cell.getQualifierArray(), cell.getQualifierOffset(),
893 cell.getQualifierLength()));
894 }
895 } else {
896 get = new Get(row);
897 for (ColumnValue column : proto.getColumnValueList()) {
898 byte[] family = zeroCopyGetBytes(column.getFamily());
899 for (QualifierValue qv : column.getQualifierValueList()) {
900 byte[] qualifier = zeroCopyGetBytes(qv.getQualifier());
901 if (!qv.hasValue()) {
902 throw new DoNotRetryIOException("Missing required field: qualifier value");
903 }
904 get.addColumn(family, qualifier);
905 }
906 }
907 }
908 if (proto.hasTimeRange()) {
909 TimeRange timeRange = protoToTimeRange(proto.getTimeRange());
910 get.setTimeRange(timeRange.getMin(), timeRange.getMax());
911 }
912 for (NameBytesPair attribute : proto.getAttributeList()) {
913 get.setAttribute(attribute.getName(), attribute.getValue().toByteArray());
914 }
915 return get;
916 }
917
918
919
920
921
922
923
924
925 public static ClientProtos.Scan toScan(
926 final Scan scan) throws IOException {
927 ClientProtos.Scan.Builder scanBuilder =
928 ClientProtos.Scan.newBuilder();
929 scanBuilder.setCacheBlocks(scan.getCacheBlocks());
930 if (scan.getBatch() > 0) {
931 scanBuilder.setBatchSize(scan.getBatch());
932 }
933 if (scan.getMaxResultSize() > 0) {
934 scanBuilder.setMaxResultSize(scan.getMaxResultSize());
935 }
936 if (scan.isSmall()) {
937 scanBuilder.setSmall(scan.isSmall());
938 }
939 if (scan.getAllowPartialResults()) {
940 scanBuilder.setAllowPartialResults(scan.getAllowPartialResults());
941 }
942 Boolean loadColumnFamiliesOnDemand = scan.getLoadColumnFamiliesOnDemandValue();
943 if (loadColumnFamiliesOnDemand != null) {
944 scanBuilder.setLoadColumnFamiliesOnDemand(loadColumnFamiliesOnDemand);
945 }
946 scanBuilder.setMaxVersions(scan.getMaxVersions());
947 for (Entry<byte[], TimeRange> cftr : scan.getColumnFamilyTimeRange().entrySet()) {
948 HBaseProtos.ColumnFamilyTimeRange.Builder b = HBaseProtos.ColumnFamilyTimeRange.newBuilder();
949 b.setColumnFamily(ByteString.copyFrom(cftr.getKey()));
950 b.setTimeRange(timeRangeToProto(cftr.getValue()));
951 scanBuilder.addCfTimeRange(b);
952 }
953 TimeRange timeRange = scan.getTimeRange();
954 if (!timeRange.isAllTime()) {
955 HBaseProtos.TimeRange.Builder timeRangeBuilder =
956 HBaseProtos.TimeRange.newBuilder();
957 timeRangeBuilder.setFrom(timeRange.getMin());
958 timeRangeBuilder.setTo(timeRange.getMax());
959 scanBuilder.setTimeRange(timeRangeBuilder.build());
960 }
961 Map<String, byte[]> attributes = scan.getAttributesMap();
962 if (!attributes.isEmpty()) {
963 NameBytesPair.Builder attributeBuilder = NameBytesPair.newBuilder();
964 for (Map.Entry<String, byte[]> attribute: attributes.entrySet()) {
965 attributeBuilder.setName(attribute.getKey());
966 attributeBuilder.setValue(ByteStringer.wrap(attribute.getValue()));
967 scanBuilder.addAttribute(attributeBuilder.build());
968 }
969 }
970 byte[] startRow = scan.getStartRow();
971 if (startRow != null && startRow.length > 0) {
972 scanBuilder.setStartRow(ByteStringer.wrap(startRow));
973 }
974 byte[] stopRow = scan.getStopRow();
975 if (stopRow != null && stopRow.length > 0) {
976 scanBuilder.setStopRow(ByteStringer.wrap(stopRow));
977 }
978 if (scan.hasFilter()) {
979 scanBuilder.setFilter(ProtobufUtil.toFilter(scan.getFilter()));
980 }
981 if (scan.hasFamilies()) {
982 Column.Builder columnBuilder = Column.newBuilder();
983 for (Map.Entry<byte[],NavigableSet<byte []>>
984 family: scan.getFamilyMap().entrySet()) {
985 columnBuilder.setFamily(ByteStringer.wrap(family.getKey()));
986 NavigableSet<byte []> qualifiers = family.getValue();
987 columnBuilder.clearQualifier();
988 if (qualifiers != null && qualifiers.size() > 0) {
989 for (byte [] qualifier: qualifiers) {
990 columnBuilder.addQualifier(ByteStringer.wrap(qualifier));
991 }
992 }
993 scanBuilder.addColumn(columnBuilder.build());
994 }
995 }
996 if (scan.getMaxResultsPerColumnFamily() >= 0) {
997 scanBuilder.setStoreLimit(scan.getMaxResultsPerColumnFamily());
998 }
999 if (scan.getRowOffsetPerColumnFamily() > 0) {
1000 scanBuilder.setStoreOffset(scan.getRowOffsetPerColumnFamily());
1001 }
1002 if (scan.isReversed()) {
1003 scanBuilder.setReversed(scan.isReversed());
1004 }
1005 if (scan.getConsistency() == Consistency.TIMELINE) {
1006 scanBuilder.setConsistency(toConsistency(scan.getConsistency()));
1007 }
1008 if (scan.getCaching() > 0) {
1009 scanBuilder.setCaching(scan.getCaching());
1010 }
1011 return scanBuilder.build();
1012 }
1013
1014
1015
1016
1017
1018
1019
1020
1021 public static Scan toScan(
1022 final ClientProtos.Scan proto) throws IOException {
1023 byte [] startRow = HConstants.EMPTY_START_ROW;
1024 byte [] stopRow = HConstants.EMPTY_END_ROW;
1025 if (proto.hasStartRow()) {
1026 startRow = proto.getStartRow().toByteArray();
1027 }
1028 if (proto.hasStopRow()) {
1029 stopRow = proto.getStopRow().toByteArray();
1030 }
1031 Scan scan = new Scan(startRow, stopRow);
1032 if (proto.hasCacheBlocks()) {
1033 scan.setCacheBlocks(proto.getCacheBlocks());
1034 }
1035 if (proto.hasMaxVersions()) {
1036 scan.setMaxVersions(proto.getMaxVersions());
1037 }
1038 if (proto.hasStoreLimit()) {
1039 scan.setMaxResultsPerColumnFamily(proto.getStoreLimit());
1040 }
1041 if (proto.hasStoreOffset()) {
1042 scan.setRowOffsetPerColumnFamily(proto.getStoreOffset());
1043 }
1044 if (proto.hasLoadColumnFamiliesOnDemand()) {
1045 scan.setLoadColumnFamiliesOnDemand(proto.getLoadColumnFamiliesOnDemand());
1046 }
1047 if (proto.getCfTimeRangeCount() > 0) {
1048 for (HBaseProtos.ColumnFamilyTimeRange cftr : proto.getCfTimeRangeList()) {
1049 TimeRange timeRange = protoToTimeRange(cftr.getTimeRange());
1050 scan.setColumnFamilyTimeRange(cftr.getColumnFamily().toByteArray(),
1051 timeRange.getMin(), timeRange.getMax());
1052 }
1053 }
1054 if (proto.hasTimeRange()) {
1055 TimeRange timeRange = protoToTimeRange(proto.getTimeRange());
1056 scan.setTimeRange(timeRange.getMin(), timeRange.getMax());
1057 }
1058 if (proto.hasFilter()) {
1059 FilterProtos.Filter filter = proto.getFilter();
1060 scan.setFilter(ProtobufUtil.toFilter(filter));
1061 }
1062 if (proto.hasBatchSize()) {
1063 scan.setBatch(proto.getBatchSize());
1064 }
1065 if (proto.hasMaxResultSize()) {
1066 scan.setMaxResultSize(proto.getMaxResultSize());
1067 }
1068 if (proto.hasSmall()) {
1069 scan.setSmall(proto.getSmall());
1070 }
1071 if (proto.hasAllowPartialResults()) {
1072 scan.setAllowPartialResults(proto.getAllowPartialResults());
1073 }
1074 for (NameBytesPair attribute: proto.getAttributeList()) {
1075 scan.setAttribute(attribute.getName(), attribute.getValue().toByteArray());
1076 }
1077 if (proto.getColumnCount() > 0) {
1078 for (Column column: proto.getColumnList()) {
1079 byte[] family = column.getFamily().toByteArray();
1080 if (column.getQualifierCount() > 0) {
1081 for (ByteString qualifier: column.getQualifierList()) {
1082 scan.addColumn(family, qualifier.toByteArray());
1083 }
1084 } else {
1085 scan.addFamily(family);
1086 }
1087 }
1088 }
1089 if (proto.hasReversed()) {
1090 scan.setReversed(proto.getReversed());
1091 }
1092 if (proto.hasConsistency()) {
1093 scan.setConsistency(toConsistency(proto.getConsistency()));
1094 }
1095 if (proto.hasCaching()) {
1096 scan.setCaching(proto.getCaching());
1097 }
1098 return scan;
1099 }
1100
1101
1102
1103
1104
1105
1106
1107
1108 public static ClientProtos.Get toGet(
1109 final Get get) throws IOException {
1110 ClientProtos.Get.Builder builder =
1111 ClientProtos.Get.newBuilder();
1112 builder.setRow(ByteStringer.wrap(get.getRow()));
1113 builder.setCacheBlocks(get.getCacheBlocks());
1114 builder.setMaxVersions(get.getMaxVersions());
1115 if (get.getFilter() != null) {
1116 builder.setFilter(ProtobufUtil.toFilter(get.getFilter()));
1117 }
1118 for (Entry<byte[], TimeRange> cftr : get.getColumnFamilyTimeRange().entrySet()) {
1119 HBaseProtos.ColumnFamilyTimeRange.Builder b = HBaseProtos.ColumnFamilyTimeRange.newBuilder();
1120 b.setColumnFamily(ByteString.copyFrom(cftr.getKey()));
1121 b.setTimeRange(timeRangeToProto(cftr.getValue()));
1122 builder.addCfTimeRange(b);
1123 }
1124 TimeRange timeRange = get.getTimeRange();
1125 if (!timeRange.isAllTime()) {
1126 HBaseProtos.TimeRange.Builder timeRangeBuilder =
1127 HBaseProtos.TimeRange.newBuilder();
1128 timeRangeBuilder.setFrom(timeRange.getMin());
1129 timeRangeBuilder.setTo(timeRange.getMax());
1130 builder.setTimeRange(timeRangeBuilder.build());
1131 }
1132 Map<String, byte[]> attributes = get.getAttributesMap();
1133 if (!attributes.isEmpty()) {
1134 NameBytesPair.Builder attributeBuilder = NameBytesPair.newBuilder();
1135 for (Map.Entry<String, byte[]> attribute: attributes.entrySet()) {
1136 attributeBuilder.setName(attribute.getKey());
1137 attributeBuilder.setValue(ByteStringer.wrap(attribute.getValue()));
1138 builder.addAttribute(attributeBuilder.build());
1139 }
1140 }
1141 if (get.hasFamilies()) {
1142 Column.Builder columnBuilder = Column.newBuilder();
1143 Map<byte[], NavigableSet<byte[]>> families = get.getFamilyMap();
1144 for (Map.Entry<byte[], NavigableSet<byte[]>> family: families.entrySet()) {
1145 NavigableSet<byte[]> qualifiers = family.getValue();
1146 columnBuilder.setFamily(ByteStringer.wrap(family.getKey()));
1147 columnBuilder.clearQualifier();
1148 if (qualifiers != null && qualifiers.size() > 0) {
1149 for (byte[] qualifier: qualifiers) {
1150 columnBuilder.addQualifier(ByteStringer.wrap(qualifier));
1151 }
1152 }
1153 builder.addColumn(columnBuilder.build());
1154 }
1155 }
1156 if (get.getMaxResultsPerColumnFamily() >= 0) {
1157 builder.setStoreLimit(get.getMaxResultsPerColumnFamily());
1158 }
1159 if (get.getRowOffsetPerColumnFamily() > 0) {
1160 builder.setStoreOffset(get.getRowOffsetPerColumnFamily());
1161 }
1162 if (get.isCheckExistenceOnly()){
1163 builder.setExistenceOnly(true);
1164 }
1165 if (get.isClosestRowBefore()){
1166 builder.setClosestRowBefore(true);
1167 }
1168 if (get.getConsistency() != null && get.getConsistency() != Consistency.STRONG) {
1169 builder.setConsistency(toConsistency(get.getConsistency()));
1170 }
1171 Boolean loadColumnFamiliesOnDemand = get.getLoadColumnFamiliesOnDemandValue();
1172 if (loadColumnFamiliesOnDemand != null) {
1173 builder.setLoadColumnFamiliesOnDemand(loadColumnFamiliesOnDemand);
1174 }
1175
1176 return builder.build();
1177 }
1178
1179 static void setTimeRange(final MutationProto.Builder builder, final TimeRange timeRange) {
1180 if (!timeRange.isAllTime()) {
1181 HBaseProtos.TimeRange.Builder timeRangeBuilder =
1182 HBaseProtos.TimeRange.newBuilder();
1183 timeRangeBuilder.setFrom(timeRange.getMin());
1184 timeRangeBuilder.setTo(timeRange.getMax());
1185 builder.setTimeRange(timeRangeBuilder.build());
1186 }
1187 }
1188
1189
1190
1191
1192
1193
1194
1195 public static MutationProto toMutation(
1196 final Increment increment, final MutationProto.Builder builder, long nonce) {
1197 builder.setRow(ByteStringer.wrap(increment.getRow()));
1198 builder.setMutateType(MutationType.INCREMENT);
1199 builder.setDurability(toDurability(increment.getDurability()));
1200 if (nonce != HConstants.NO_NONCE) {
1201 builder.setNonce(nonce);
1202 }
1203 TimeRange timeRange = increment.getTimeRange();
1204 setTimeRange(builder, timeRange);
1205 ColumnValue.Builder columnBuilder = ColumnValue.newBuilder();
1206 QualifierValue.Builder valueBuilder = QualifierValue.newBuilder();
1207 for (Map.Entry<byte[], List<Cell>> family: increment.getFamilyCellMap().entrySet()) {
1208 columnBuilder.setFamily(ByteStringer.wrap(family.getKey()));
1209 columnBuilder.clearQualifierValue();
1210 List<Cell> values = family.getValue();
1211 if (values != null && values.size() > 0) {
1212 for (Cell cell: values) {
1213 valueBuilder.clear();
1214 valueBuilder.setQualifier(ByteStringer.wrap(
1215 cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength()));
1216 valueBuilder.setValue(ByteStringer.wrap(
1217 cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()));
1218 if (cell.getTagsLength() > 0) {
1219 valueBuilder.setTags(ByteStringer.wrap(cell.getTagsArray(),
1220 cell.getTagsOffset(), cell.getTagsLength()));
1221 }
1222 columnBuilder.addQualifierValue(valueBuilder.build());
1223 }
1224 }
1225 builder.addColumnValue(columnBuilder.build());
1226 }
1227 Map<String, byte[]> attributes = increment.getAttributesMap();
1228 if (!attributes.isEmpty()) {
1229 NameBytesPair.Builder attributeBuilder = NameBytesPair.newBuilder();
1230 for (Map.Entry<String, byte[]> attribute : attributes.entrySet()) {
1231 attributeBuilder.setName(attribute.getKey());
1232 attributeBuilder.setValue(ByteStringer.wrap(attribute.getValue()));
1233 builder.addAttribute(attributeBuilder.build());
1234 }
1235 }
1236 return builder.build();
1237 }
1238
1239 public static MutationProto toMutation(final MutationType type, final Mutation mutation)
1240 throws IOException {
1241 return toMutation(type, mutation, HConstants.NO_NONCE);
1242 }
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252 public static MutationProto toMutation(final MutationType type, final Mutation mutation,
1253 final long nonce) throws IOException {
1254 return toMutation(type, mutation, MutationProto.newBuilder(), nonce);
1255 }
1256
1257 public static MutationProto toMutation(final MutationType type, final Mutation mutation,
1258 MutationProto.Builder builder) throws IOException {
1259 return toMutation(type, mutation, builder, HConstants.NO_NONCE);
1260 }
1261
1262 public static MutationProto toMutation(final MutationType type, final Mutation mutation,
1263 MutationProto.Builder builder, long nonce)
1264 throws IOException {
1265 builder = getMutationBuilderAndSetCommonFields(type, mutation, builder);
1266 if (nonce != HConstants.NO_NONCE) {
1267 builder.setNonce(nonce);
1268 }
1269 ColumnValue.Builder columnBuilder = ColumnValue.newBuilder();
1270 QualifierValue.Builder valueBuilder = QualifierValue.newBuilder();
1271 for (Map.Entry<byte[],List<Cell>> family: mutation.getFamilyCellMap().entrySet()) {
1272 columnBuilder.clear();
1273 columnBuilder.setFamily(ByteStringer.wrap(family.getKey()));
1274 for (Cell cell: family.getValue()) {
1275 valueBuilder.clear();
1276 valueBuilder.setQualifier(ByteStringer.wrap(
1277 cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength()));
1278 valueBuilder.setValue(ByteStringer.wrap(
1279 cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()));
1280 valueBuilder.setTimestamp(cell.getTimestamp());
1281 if (type == MutationType.DELETE || (type == MutationType.PUT && CellUtil.isDelete(cell))) {
1282 KeyValue.Type keyValueType = KeyValue.Type.codeToType(cell.getTypeByte());
1283 valueBuilder.setDeleteType(toDeleteType(keyValueType));
1284 }
1285 columnBuilder.addQualifierValue(valueBuilder.build());
1286 }
1287 builder.addColumnValue(columnBuilder.build());
1288 }
1289 return builder.build();
1290 }
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301 public static MutationProto toMutationNoData(final MutationType type, final Mutation mutation,
1302 final MutationProto.Builder builder) throws IOException {
1303 return toMutationNoData(type, mutation, builder, HConstants.NO_NONCE);
1304 }
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314 public static MutationProto toMutationNoData(final MutationType type, final Mutation mutation)
1315 throws IOException {
1316 MutationProto.Builder builder = MutationProto.newBuilder();
1317 return toMutationNoData(type, mutation, builder);
1318 }
1319
1320 public static MutationProto toMutationNoData(final MutationType type, final Mutation mutation,
1321 final MutationProto.Builder builder, long nonce) throws IOException {
1322 getMutationBuilderAndSetCommonFields(type, mutation, builder);
1323 builder.setAssociatedCellCount(mutation.size());
1324 if (mutation instanceof Increment) {
1325 setTimeRange(builder, ((Increment)mutation).getTimeRange());
1326 }
1327 if (nonce != HConstants.NO_NONCE) {
1328 builder.setNonce(nonce);
1329 }
1330 return builder.build();
1331 }
1332
1333
1334
1335
1336
1337
1338
1339
1340 private static MutationProto.Builder getMutationBuilderAndSetCommonFields(final MutationType type,
1341 final Mutation mutation, MutationProto.Builder builder) {
1342 builder.setRow(ByteStringer.wrap(mutation.getRow()));
1343 builder.setMutateType(type);
1344 builder.setDurability(toDurability(mutation.getDurability()));
1345 builder.setTimestamp(mutation.getTimeStamp());
1346 Map<String, byte[]> attributes = mutation.getAttributesMap();
1347 if (!attributes.isEmpty()) {
1348 NameBytesPair.Builder attributeBuilder = NameBytesPair.newBuilder();
1349 for (Map.Entry<String, byte[]> attribute: attributes.entrySet()) {
1350 attributeBuilder.setName(attribute.getKey());
1351 attributeBuilder.setValue(ByteStringer.wrap(attribute.getValue()));
1352 builder.addAttribute(attributeBuilder.build());
1353 }
1354 }
1355 return builder;
1356 }
1357
1358
1359
1360
1361
1362
1363
1364 public static ClientProtos.Result toResult(final Result result) {
1365 if (result.getExists() != null) {
1366 return toResult(result.getExists(), result.isStale());
1367 }
1368
1369 Cell[] cells = result.rawCells();
1370 if (cells == null || cells.length == 0) {
1371 return result.isStale() ? EMPTY_RESULT_PB_STALE : EMPTY_RESULT_PB;
1372 }
1373
1374 ClientProtos.Result.Builder builder = ClientProtos.Result.newBuilder();
1375 for (Cell c : cells) {
1376 builder.addCell(toCell(c));
1377 }
1378
1379 builder.setStale(result.isStale());
1380 builder.setPartial(result.isPartial());
1381
1382 return builder.build();
1383 }
1384
1385
1386
1387
1388
1389
1390
1391 public static ClientProtos.Result toResult(final boolean existence, boolean stale) {
1392 if (stale){
1393 return existence ? EMPTY_RESULT_PB_EXISTS_TRUE_STALE : EMPTY_RESULT_PB_EXISTS_FALSE_STALE;
1394 } else {
1395 return existence ? EMPTY_RESULT_PB_EXISTS_TRUE : EMPTY_RESULT_PB_EXISTS_FALSE;
1396 }
1397 }
1398
1399
1400
1401
1402
1403
1404
1405
1406 public static ClientProtos.Result toResultNoData(final Result result) {
1407 if (result.getExists() != null) return toResult(result.getExists(), result.isStale());
1408 int size = result.size();
1409 if (size == 0) return result.isStale() ? EMPTY_RESULT_PB_STALE : EMPTY_RESULT_PB;
1410 ClientProtos.Result.Builder builder = ClientProtos.Result.newBuilder();
1411 builder.setAssociatedCellCount(size);
1412 builder.setStale(result.isStale());
1413 return builder.build();
1414 }
1415
1416
1417
1418
1419
1420
1421
1422 public static Result toResult(final ClientProtos.Result proto) {
1423 if (proto.hasExists()) {
1424 if (proto.getStale()) {
1425 return proto.getExists() ? EMPTY_RESULT_EXISTS_TRUE_STALE :EMPTY_RESULT_EXISTS_FALSE_STALE;
1426 }
1427 return proto.getExists() ? EMPTY_RESULT_EXISTS_TRUE : EMPTY_RESULT_EXISTS_FALSE;
1428 }
1429
1430 List<CellProtos.Cell> values = proto.getCellList();
1431 if (values.isEmpty()){
1432 return proto.getStale() ? EMPTY_RESULT_STALE : EMPTY_RESULT;
1433 }
1434
1435 List<Cell> cells = new ArrayList<Cell>(values.size());
1436 for (CellProtos.Cell c : values) {
1437 cells.add(toCell(c));
1438 }
1439 return Result.create(cells, null, proto.getStale(), proto.getPartial());
1440 }
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450 public static Result toResult(final ClientProtos.Result proto, final CellScanner scanner)
1451 throws IOException {
1452 List<CellProtos.Cell> values = proto.getCellList();
1453
1454 if (proto.hasExists()) {
1455 if ((values != null && !values.isEmpty()) ||
1456 (proto.hasAssociatedCellCount() && proto.getAssociatedCellCount() > 0)) {
1457 throw new IllegalArgumentException("bad proto: exists with cells is no allowed " + proto);
1458 }
1459 if (proto.getStale()) {
1460 return proto.getExists() ? EMPTY_RESULT_EXISTS_TRUE_STALE :EMPTY_RESULT_EXISTS_FALSE_STALE;
1461 }
1462 return proto.getExists() ? EMPTY_RESULT_EXISTS_TRUE : EMPTY_RESULT_EXISTS_FALSE;
1463 }
1464
1465
1466 List<Cell> cells = null;
1467 if (proto.hasAssociatedCellCount()) {
1468 int count = proto.getAssociatedCellCount();
1469 cells = new ArrayList<Cell>(count + values.size());
1470 for (int i = 0; i < count; i++) {
1471 if (!scanner.advance()) throw new IOException("Failed get " + i + " of " + count);
1472 cells.add(scanner.current());
1473 }
1474 }
1475
1476 if (!values.isEmpty()){
1477 if (cells == null) cells = new ArrayList<Cell>(values.size());
1478 for (CellProtos.Cell c: values) {
1479 cells.add(toCell(c));
1480 }
1481 }
1482
1483 return (cells == null || cells.isEmpty())
1484 ? (proto.getStale() ? EMPTY_RESULT_STALE : EMPTY_RESULT)
1485 : Result.create(cells, null, proto.getStale());
1486 }
1487
1488
1489
1490
1491
1492
1493
1494
1495 public static ComparatorProtos.Comparator toComparator(ByteArrayComparable comparator) {
1496 ComparatorProtos.Comparator.Builder builder = ComparatorProtos.Comparator.newBuilder();
1497 builder.setName(comparator.getClass().getName());
1498 builder.setSerializedComparator(ByteStringer.wrap(comparator.toByteArray()));
1499 return builder.build();
1500 }
1501
1502
1503
1504
1505
1506
1507
1508 @SuppressWarnings("unchecked")
1509 public static ByteArrayComparable toComparator(ComparatorProtos.Comparator proto)
1510 throws IOException {
1511 String type = proto.getName();
1512 String funcName = "parseFrom";
1513 byte [] value = proto.getSerializedComparator().toByteArray();
1514 try {
1515 Class<? extends ByteArrayComparable> c =
1516 (Class<? extends ByteArrayComparable>)Class.forName(type, true, CLASS_LOADER);
1517 Method parseFrom = c.getMethod(funcName, byte[].class);
1518 if (parseFrom == null) {
1519 throw new IOException("Unable to locate function: " + funcName + " in type: " + type);
1520 }
1521 return (ByteArrayComparable)parseFrom.invoke(null, value);
1522 } catch (Exception e) {
1523 throw new IOException(e);
1524 }
1525 }
1526
1527
1528
1529
1530
1531
1532
1533 @SuppressWarnings("unchecked")
1534 public static Filter toFilter(FilterProtos.Filter proto) throws IOException {
1535 String type = proto.getName();
1536 final byte [] value = proto.getSerializedFilter().toByteArray();
1537 String funcName = "parseFrom";
1538 try {
1539 Class<? extends Filter> c =
1540 (Class<? extends Filter>)Class.forName(type, true, CLASS_LOADER);
1541 Method parseFrom = c.getMethod(funcName, byte[].class);
1542 if (parseFrom == null) {
1543 throw new IOException("Unable to locate function: " + funcName + " in type: " + type);
1544 }
1545 return (Filter)parseFrom.invoke(c, value);
1546 } catch (Exception e) {
1547
1548
1549 throw new DoNotRetryIOException(e);
1550 }
1551 }
1552
1553
1554
1555
1556
1557
1558
1559 public static FilterProtos.Filter toFilter(Filter filter) throws IOException {
1560 FilterProtos.Filter.Builder builder = FilterProtos.Filter.newBuilder();
1561 builder.setName(filter.getClass().getName());
1562 builder.setSerializedFilter(ByteStringer.wrap(filter.toByteArray()));
1563 return builder.build();
1564 }
1565
1566
1567
1568
1569
1570
1571
1572
1573 public static DeleteType toDeleteType(
1574 KeyValue.Type type) throws IOException {
1575 switch (type) {
1576 case Delete:
1577 return DeleteType.DELETE_ONE_VERSION;
1578 case DeleteColumn:
1579 return DeleteType.DELETE_MULTIPLE_VERSIONS;
1580 case DeleteFamily:
1581 return DeleteType.DELETE_FAMILY;
1582 case DeleteFamilyVersion:
1583 return DeleteType.DELETE_FAMILY_VERSION;
1584 default:
1585 throw new IOException("Unknown delete type: " + type);
1586 }
1587 }
1588
1589
1590
1591
1592
1593
1594
1595
1596 public static KeyValue.Type fromDeleteType(
1597 DeleteType type) throws IOException {
1598 switch (type) {
1599 case DELETE_ONE_VERSION:
1600 return KeyValue.Type.Delete;
1601 case DELETE_MULTIPLE_VERSIONS:
1602 return KeyValue.Type.DeleteColumn;
1603 case DELETE_FAMILY:
1604 return KeyValue.Type.DeleteFamily;
1605 case DELETE_FAMILY_VERSION:
1606 return KeyValue.Type.DeleteFamilyVersion;
1607 default:
1608 throw new IOException("Unknown delete type: " + type);
1609 }
1610 }
1611
1612
1613
1614
1615
1616
1617
1618
1619 @SuppressWarnings("unchecked")
1620 public static Throwable toException(final NameBytesPair parameter) throws IOException {
1621 if (parameter == null || !parameter.hasValue()) return null;
1622 String desc = parameter.getValue().toStringUtf8();
1623 String type = parameter.getName();
1624 try {
1625 Class<? extends Throwable> c =
1626 (Class<? extends Throwable>)Class.forName(type, true, CLASS_LOADER);
1627 Constructor<? extends Throwable> cn = null;
1628 try {
1629 cn = c.getDeclaredConstructor(String.class);
1630 return cn.newInstance(desc);
1631 } catch (NoSuchMethodException e) {
1632
1633 cn = c.getDeclaredConstructor(String.class, String.class);
1634 return cn.newInstance(type, desc);
1635 }
1636 } catch (Exception e) {
1637 throw new IOException(e);
1638 }
1639 }
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654 @Deprecated
1655 public static Result getRowOrBefore(final ClientService.BlockingInterface client,
1656 final byte[] regionName, final byte[] row,
1657 final byte[] family) throws IOException {
1658 GetRequest request =
1659 RequestConverter.buildGetRowOrBeforeRequest(
1660 regionName, row, family);
1661 try {
1662 GetResponse response = client.get(null, request);
1663 if (!response.hasResult()) return null;
1664
1665 return toResult(response.getResult());
1666 } catch (ServiceException se) {
1667 throw getRemoteException(se);
1668 }
1669 }
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681 public static boolean bulkLoadHFile(final ClientService.BlockingInterface client,
1682 final List<Pair<byte[], String>> familyPaths,
1683 final byte[] regionName, boolean assignSeqNum) throws IOException {
1684 BulkLoadHFileRequest request =
1685 RequestConverter.buildBulkLoadHFileRequest(familyPaths, regionName, assignSeqNum);
1686 try {
1687 BulkLoadHFileResponse response =
1688 client.bulkLoadHFile(null, request);
1689 return response.getLoaded();
1690 } catch (ServiceException se) {
1691 throw getRemoteException(se);
1692 }
1693 }
1694
1695 public static CoprocessorServiceResponse execService(final RpcController controller,
1696 final ClientService.BlockingInterface client, final CoprocessorServiceCall call,
1697 final byte[] regionName) throws IOException {
1698 CoprocessorServiceRequest request = CoprocessorServiceRequest.newBuilder()
1699 .setCall(call).setRegion(
1700 RequestConverter.buildRegionSpecifier(REGION_NAME, regionName)).build();
1701 try {
1702 CoprocessorServiceResponse response =
1703 client.execService(controller, request);
1704 return response;
1705 } catch (ServiceException se) {
1706 throw getRemoteException(se);
1707 }
1708 }
1709
1710 public static CoprocessorServiceResponse execService(final RpcController controller,
1711 final MasterService.BlockingInterface client, final CoprocessorServiceCall call)
1712 throws IOException {
1713 CoprocessorServiceRequest request = CoprocessorServiceRequest.newBuilder()
1714 .setCall(call).setRegion(
1715 RequestConverter.buildRegionSpecifier(REGION_NAME, HConstants.EMPTY_BYTE_ARRAY)).build();
1716 try {
1717 CoprocessorServiceResponse response =
1718 client.execMasterService(controller, request);
1719 return response;
1720 } catch (ServiceException se) {
1721 throw getRemoteException(se);
1722 }
1723 }
1724
1725
1726
1727
1728
1729
1730
1731
1732 public static CoprocessorServiceResponse execRegionServerService(
1733 final RpcController controller, final ClientService.BlockingInterface client,
1734 final CoprocessorServiceCall call)
1735 throws IOException {
1736 CoprocessorServiceRequest request =
1737 CoprocessorServiceRequest
1738 .newBuilder()
1739 .setCall(call)
1740 .setRegion(
1741 RequestConverter.buildRegionSpecifier(REGION_NAME, HConstants.EMPTY_BYTE_ARRAY))
1742 .build();
1743 try {
1744 CoprocessorServiceResponse response = client.execRegionServerService(controller, request);
1745 return response;
1746 } catch (ServiceException se) {
1747 throw getRemoteException(se);
1748 }
1749 }
1750
1751 @SuppressWarnings("unchecked")
1752 public static <T extends Service> T newServiceStub(Class<T> service, RpcChannel channel)
1753 throws Exception {
1754 return (T)Methods.call(service, null, "newStub",
1755 new Class[]{ RpcChannel.class }, new Object[]{ channel });
1756 }
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770 public static HRegionInfo getRegionInfo(final RpcController controller,
1771 final AdminService.BlockingInterface admin, final byte[] regionName) throws IOException {
1772 try {
1773 GetRegionInfoRequest request =
1774 RequestConverter.buildGetRegionInfoRequest(regionName);
1775 GetRegionInfoResponse response =
1776 admin.getRegionInfo(controller, request);
1777 return HRegionInfo.convert(response.getRegionInfo());
1778 } catch (ServiceException se) {
1779 throw getRemoteException(se);
1780 }
1781 }
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792 public static void closeRegion(final RpcController controller,
1793 final AdminService.BlockingInterface admin, final ServerName server, final byte[] regionName,
1794 final boolean transitionInZK) throws IOException {
1795 CloseRegionRequest closeRegionRequest =
1796 RequestConverter.buildCloseRegionRequest(server, regionName, transitionInZK);
1797 try {
1798 admin.closeRegion(controller, closeRegionRequest);
1799 } catch (ServiceException se) {
1800 throw getRemoteException(se);
1801 }
1802 }
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814 public static boolean closeRegion(final RpcController controller,
1815 final AdminService.BlockingInterface admin,
1816 final ServerName server,
1817 final byte[] regionName,
1818 final int versionOfClosingNode, final ServerName destinationServer,
1819 final boolean transitionInZK) throws IOException {
1820 CloseRegionRequest closeRegionRequest =
1821 RequestConverter.buildCloseRegionRequest(server,
1822 regionName, versionOfClosingNode, destinationServer, transitionInZK);
1823 try {
1824 CloseRegionResponse response = admin.closeRegion(controller, closeRegionRequest);
1825 return ResponseConverter.isClosed(response);
1826 } catch (ServiceException se) {
1827 throw getRemoteException(se);
1828 }
1829 }
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839 public static void warmupRegion(final RpcController controller,
1840 final AdminService.BlockingInterface admin, final HRegionInfo regionInfo) throws IOException {
1841
1842 try {
1843 WarmupRegionRequest warmupRegionRequest =
1844 RequestConverter.buildWarmupRegionRequest(regionInfo);
1845
1846 admin.warmupRegion(controller, warmupRegionRequest);
1847 } catch (ServiceException e) {
1848 throw getRemoteException(e);
1849 }
1850 }
1851
1852
1853
1854
1855
1856
1857
1858 public static void openRegion(final RpcController controller,
1859 final AdminService.BlockingInterface admin, ServerName server, final HRegionInfo region)
1860 throws IOException {
1861 OpenRegionRequest request =
1862 RequestConverter.buildOpenRegionRequest(server, region, -1, null, null);
1863 try {
1864 admin.openRegion(controller, request);
1865 } catch (ServiceException se) {
1866 throw ProtobufUtil.getRemoteException(se);
1867 }
1868 }
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878 public static List<HRegionInfo> getOnlineRegions(final AdminService.BlockingInterface admin)
1879 throws IOException {
1880 return getOnlineRegions(null, admin);
1881 }
1882
1883
1884
1885
1886
1887
1888 public static List<HRegionInfo> getOnlineRegions(final RpcController controller,
1889 final AdminService.BlockingInterface admin)
1890 throws IOException {
1891 GetOnlineRegionRequest request = RequestConverter.buildGetOnlineRegionRequest();
1892 GetOnlineRegionResponse response = null;
1893 try {
1894 response = admin.getOnlineRegion(controller, request);
1895 } catch (ServiceException se) {
1896 throw getRemoteException(se);
1897 }
1898 return getRegionInfos(response);
1899 }
1900
1901
1902
1903
1904
1905
1906
1907 static List<HRegionInfo> getRegionInfos(final GetOnlineRegionResponse proto) {
1908 if (proto == null) return null;
1909 List<HRegionInfo> regionInfos = new ArrayList<HRegionInfo>();
1910 for (RegionInfo regionInfo: proto.getRegionInfoList()) {
1911 regionInfos.add(HRegionInfo.convert(regionInfo));
1912 }
1913 return regionInfos;
1914 }
1915
1916
1917
1918
1919
1920 public static ServerInfo getServerInfo(final RpcController controller,
1921 final AdminService.BlockingInterface admin)
1922 throws IOException {
1923 GetServerInfoRequest request = RequestConverter.buildGetServerInfoRequest();
1924 try {
1925 GetServerInfoResponse response = admin.getServerInfo(controller, request);
1926 return response.getServerInfo();
1927 } catch (ServiceException se) {
1928 throw getRemoteException(se);
1929 }
1930 }
1931
1932
1933
1934
1935
1936
1937
1938 public static List<String> getStoreFiles(final AdminService.BlockingInterface admin,
1939 final byte[] regionName, final byte[] family)
1940 throws IOException {
1941 return getStoreFiles(null, admin, regionName, family);
1942 }
1943
1944
1945
1946
1947
1948
1949
1950 public static List<String> getStoreFiles(final RpcController controller,
1951 final AdminService.BlockingInterface admin, final byte[] regionName, final byte[] family)
1952 throws IOException {
1953 GetStoreFileRequest request =
1954 RequestConverter.buildGetStoreFileRequest(regionName, family);
1955 try {
1956 GetStoreFileResponse response = admin.getStoreFile(controller, request);
1957 return response.getStoreFileList();
1958 } catch (ServiceException se) {
1959 throw ProtobufUtil.getRemoteException(se);
1960 }
1961 }
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971 public static void split(final RpcController controller,
1972 final AdminService.BlockingInterface admin, final HRegionInfo hri, byte[] splitPoint)
1973 throws IOException {
1974 SplitRegionRequest request =
1975 RequestConverter.buildSplitRegionRequest(hri.getRegionName(), splitPoint);
1976 try {
1977 admin.splitRegion(controller, request);
1978 } catch (ServiceException se) {
1979 throw ProtobufUtil.getRemoteException(se);
1980 }
1981 }
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994 public static void mergeRegions(final RpcController controller,
1995 final AdminService.BlockingInterface admin,
1996 final HRegionInfo region_a, final HRegionInfo region_b,
1997 final boolean forcible, final User user) throws IOException {
1998 final MergeRegionsRequest request = RequestConverter.buildMergeRegionsRequest(
1999 region_a.getRegionName(), region_b.getRegionName(),forcible);
2000 if (user != null) {
2001 try {
2002 user.getUGI().doAs(new PrivilegedExceptionAction<Void>() {
2003 @Override
2004 public Void run() throws Exception {
2005 try {
2006 admin.mergeRegions(controller, request);
2007 } catch (ServiceException se) {
2008 throw ProtobufUtil.getRemoteException(se);
2009 }
2010 return null;
2011 }
2012 });
2013 } catch (InterruptedException ie) {
2014 InterruptedIOException iioe = new InterruptedIOException();
2015 iioe.initCause(ie);
2016 throw iioe;
2017 }
2018 } else {
2019 try {
2020 admin.mergeRegions(controller, request);
2021 } catch (ServiceException se) {
2022 throw ProtobufUtil.getRemoteException(se);
2023 }
2024 }
2025 }
2026
2027
2028
2029
2030
2031
2032
2033
2034 public static long getTotalRequestsCount(RegionLoad rl) {
2035 if (rl == null) {
2036 return 0;
2037 }
2038
2039 return rl.getReadRequestsCount() + rl.getWriteRequestsCount();
2040 }
2041
2042
2043
2044
2045
2046 public static byte [] toDelimitedByteArray(final Message m) throws IOException {
2047
2048 ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
2049 baos.write(PB_MAGIC);
2050 m.writeDelimitedTo(baos);
2051 return baos.toByteArray();
2052 }
2053
2054
2055
2056
2057
2058
2059
2060 public static Permission toPermission(AccessControlProtos.Permission proto) {
2061 if (proto.getType() != AccessControlProtos.Permission.Type.Global) {
2062 return toTablePermission(proto);
2063 } else {
2064 List<Permission.Action> actions = toPermissionActions(proto.getGlobalPermission().getActionList());
2065 return new Permission(actions.toArray(new Permission.Action[actions.size()]));
2066 }
2067 }
2068
2069
2070
2071
2072
2073
2074
2075 public static TablePermission toTablePermission(AccessControlProtos.Permission proto) {
2076 if(proto.getType() == AccessControlProtos.Permission.Type.Global) {
2077 AccessControlProtos.GlobalPermission perm = proto.getGlobalPermission();
2078 List<Permission.Action> actions = toPermissionActions(perm.getActionList());
2079
2080 return new TablePermission(null, null, null,
2081 actions.toArray(new Permission.Action[actions.size()]));
2082 }
2083 if(proto.getType() == AccessControlProtos.Permission.Type.Namespace) {
2084 AccessControlProtos.NamespacePermission perm = proto.getNamespacePermission();
2085 List<Permission.Action> actions = toPermissionActions(perm.getActionList());
2086
2087 if(!proto.hasNamespacePermission()) {
2088 throw new IllegalStateException("Namespace must not be empty in NamespacePermission");
2089 }
2090 String namespace = perm.getNamespaceName().toStringUtf8();
2091 return new TablePermission(namespace, actions.toArray(new Permission.Action[actions.size()]));
2092 }
2093 if(proto.getType() == AccessControlProtos.Permission.Type.Table) {
2094 AccessControlProtos.TablePermission perm = proto.getTablePermission();
2095 List<Permission.Action> actions = toPermissionActions(perm.getActionList());
2096
2097 byte[] qualifier = null;
2098 byte[] family = null;
2099 TableName table = null;
2100
2101 if (!perm.hasTableName()) {
2102 throw new IllegalStateException("TableName cannot be empty");
2103 }
2104 table = ProtobufUtil.toTableName(perm.getTableName());
2105
2106 if (perm.hasFamily()) family = perm.getFamily().toByteArray();
2107 if (perm.hasQualifier()) qualifier = perm.getQualifier().toByteArray();
2108
2109 return new TablePermission(table, family, qualifier,
2110 actions.toArray(new Permission.Action[actions.size()]));
2111 }
2112 throw new IllegalStateException("Unrecognize Perm Type: "+proto.getType());
2113 }
2114
2115
2116
2117
2118
2119
2120
2121 public static AccessControlProtos.Permission toPermission(Permission perm) {
2122 AccessControlProtos.Permission.Builder ret = AccessControlProtos.Permission.newBuilder();
2123 if (perm instanceof TablePermission) {
2124 TablePermission tablePerm = (TablePermission)perm;
2125 if(tablePerm.hasNamespace()) {
2126 ret.setType(AccessControlProtos.Permission.Type.Namespace);
2127
2128 AccessControlProtos.NamespacePermission.Builder builder =
2129 AccessControlProtos.NamespacePermission.newBuilder();
2130 builder.setNamespaceName(ByteString.copyFromUtf8(tablePerm.getNamespace()));
2131 Permission.Action actions[] = perm.getActions();
2132 if (actions != null) {
2133 for (Permission.Action a : actions) {
2134 builder.addAction(toPermissionAction(a));
2135 }
2136 }
2137 ret.setNamespacePermission(builder);
2138 return ret.build();
2139 } else if (tablePerm.hasTable()) {
2140 ret.setType(AccessControlProtos.Permission.Type.Table);
2141
2142 AccessControlProtos.TablePermission.Builder builder =
2143 AccessControlProtos.TablePermission.newBuilder();
2144 builder.setTableName(ProtobufUtil.toProtoTableName(tablePerm.getTableName()));
2145 if (tablePerm.hasFamily()) {
2146 builder.setFamily(ByteStringer.wrap(tablePerm.getFamily()));
2147 }
2148 if (tablePerm.hasQualifier()) {
2149 builder.setQualifier(ByteStringer.wrap(tablePerm.getQualifier()));
2150 }
2151 Permission.Action actions[] = perm.getActions();
2152 if (actions != null) {
2153 for (Permission.Action a : actions) {
2154 builder.addAction(toPermissionAction(a));
2155 }
2156 }
2157 ret.setTablePermission(builder);
2158 return ret.build();
2159 }
2160 }
2161
2162 ret.setType(AccessControlProtos.Permission.Type.Global);
2163
2164 AccessControlProtos.GlobalPermission.Builder builder =
2165 AccessControlProtos.GlobalPermission.newBuilder();
2166 Permission.Action actions[] = perm.getActions();
2167 if (actions != null) {
2168 for (Permission.Action a: actions) {
2169 builder.addAction(toPermissionAction(a));
2170 }
2171 }
2172 ret.setGlobalPermission(builder);
2173 return ret.build();
2174 }
2175
2176
2177
2178
2179
2180
2181
2182 public static List<Permission.Action> toPermissionActions(
2183 List<AccessControlProtos.Permission.Action> protoActions) {
2184 List<Permission.Action> actions = new ArrayList<Permission.Action>(protoActions.size());
2185 for (AccessControlProtos.Permission.Action a : protoActions) {
2186 actions.add(toPermissionAction(a));
2187 }
2188 return actions;
2189 }
2190
2191
2192
2193
2194
2195
2196
2197 public static Permission.Action toPermissionAction(
2198 AccessControlProtos.Permission.Action action) {
2199 switch (action) {
2200 case READ:
2201 return Permission.Action.READ;
2202 case WRITE:
2203 return Permission.Action.WRITE;
2204 case EXEC:
2205 return Permission.Action.EXEC;
2206 case CREATE:
2207 return Permission.Action.CREATE;
2208 case ADMIN:
2209 return Permission.Action.ADMIN;
2210 }
2211 throw new IllegalArgumentException("Unknown action value "+action.name());
2212 }
2213
2214
2215
2216
2217
2218
2219
2220 public static AccessControlProtos.Permission.Action toPermissionAction(
2221 Permission.Action action) {
2222 switch (action) {
2223 case READ:
2224 return AccessControlProtos.Permission.Action.READ;
2225 case WRITE:
2226 return AccessControlProtos.Permission.Action.WRITE;
2227 case EXEC:
2228 return AccessControlProtos.Permission.Action.EXEC;
2229 case CREATE:
2230 return AccessControlProtos.Permission.Action.CREATE;
2231 case ADMIN:
2232 return AccessControlProtos.Permission.Action.ADMIN;
2233 }
2234 throw new IllegalArgumentException("Unknown action value "+action.name());
2235 }
2236
2237
2238
2239
2240
2241
2242
2243 public static AccessControlProtos.UserPermission toUserPermission(UserPermission perm) {
2244 return AccessControlProtos.UserPermission.newBuilder()
2245 .setUser(ByteStringer.wrap(perm.getUser()))
2246 .setPermission(toPermission(perm))
2247 .build();
2248 }
2249
2250
2251
2252
2253
2254
2255
2256 public static UserPermission toUserPermission(AccessControlProtos.UserPermission proto) {
2257 return new UserPermission(proto.getUser().toByteArray(),
2258 toTablePermission(proto.getPermission()));
2259 }
2260
2261
2262
2263
2264
2265
2266
2267
2268 public static AccessControlProtos.UsersAndPermissions toUserTablePermissions(
2269 ListMultimap<String, TablePermission> perm) {
2270 AccessControlProtos.UsersAndPermissions.Builder builder =
2271 AccessControlProtos.UsersAndPermissions.newBuilder();
2272 for (Map.Entry<String, Collection<TablePermission>> entry : perm.asMap().entrySet()) {
2273 AccessControlProtos.UsersAndPermissions.UserPermissions.Builder userPermBuilder =
2274 AccessControlProtos.UsersAndPermissions.UserPermissions.newBuilder();
2275 userPermBuilder.setUser(ByteString.copyFromUtf8(entry.getKey()));
2276 for (TablePermission tablePerm: entry.getValue()) {
2277 userPermBuilder.addPermissions(toPermission(tablePerm));
2278 }
2279 builder.addUserPermissions(userPermBuilder.build());
2280 }
2281 return builder.build();
2282 }
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294 public static void grant(RpcController controller,
2295 AccessControlService.BlockingInterface protocol, String userShortName,
2296 Permission.Action... actions) throws ServiceException {
2297 List<AccessControlProtos.Permission.Action> permActions =
2298 Lists.newArrayListWithCapacity(actions.length);
2299 for (Permission.Action a : actions) {
2300 permActions.add(ProtobufUtil.toPermissionAction(a));
2301 }
2302 AccessControlProtos.GrantRequest request = RequestConverter.
2303 buildGrantRequest(userShortName, permActions.toArray(
2304 new AccessControlProtos.Permission.Action[actions.length]));
2305 protocol.grant(controller, request);
2306 }
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322 public static void grant(RpcController controller,
2323 AccessControlService.BlockingInterface protocol, String userShortName, TableName tableName,
2324 byte[] f, byte[] q, Permission.Action... actions) throws ServiceException {
2325 List<AccessControlProtos.Permission.Action> permActions =
2326 Lists.newArrayListWithCapacity(actions.length);
2327 for (Permission.Action a : actions) {
2328 permActions.add(ProtobufUtil.toPermissionAction(a));
2329 }
2330 AccessControlProtos.GrantRequest request = RequestConverter.
2331 buildGrantRequest(userShortName, tableName, f, q, permActions.toArray(
2332 new AccessControlProtos.Permission.Action[actions.length]));
2333 protocol.grant(controller, request);
2334 }
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346 public static void grant(RpcController controller,
2347 AccessControlService.BlockingInterface protocol, String userShortName, String namespace,
2348 Permission.Action... actions) throws ServiceException {
2349 List<AccessControlProtos.Permission.Action> permActions =
2350 Lists.newArrayListWithCapacity(actions.length);
2351 for (Permission.Action a : actions) {
2352 permActions.add(ProtobufUtil.toPermissionAction(a));
2353 }
2354 AccessControlProtos.GrantRequest request = RequestConverter.
2355 buildGrantRequest(userShortName, namespace, permActions.toArray(
2356 new AccessControlProtos.Permission.Action[actions.length]));
2357 protocol.grant(controller, request);
2358 }
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370 public static void revoke(RpcController controller,
2371 AccessControlService.BlockingInterface protocol, String userShortName,
2372 Permission.Action... actions) throws ServiceException {
2373 List<AccessControlProtos.Permission.Action> permActions =
2374 Lists.newArrayListWithCapacity(actions.length);
2375 for (Permission.Action a : actions) {
2376 permActions.add(ProtobufUtil.toPermissionAction(a));
2377 }
2378 AccessControlProtos.RevokeRequest request = RequestConverter.
2379 buildRevokeRequest(userShortName, permActions.toArray(
2380 new AccessControlProtos.Permission.Action[actions.length]));
2381 protocol.revoke(controller, request);
2382 }
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398 public static void revoke(RpcController controller,
2399 AccessControlService.BlockingInterface protocol, String userShortName, TableName tableName,
2400 byte[] f, byte[] q, Permission.Action... actions) throws ServiceException {
2401 List<AccessControlProtos.Permission.Action> permActions =
2402 Lists.newArrayListWithCapacity(actions.length);
2403 for (Permission.Action a : actions) {
2404 permActions.add(ProtobufUtil.toPermissionAction(a));
2405 }
2406 AccessControlProtos.RevokeRequest request = RequestConverter.
2407 buildRevokeRequest(userShortName, tableName, f, q, permActions.toArray(
2408 new AccessControlProtos.Permission.Action[actions.length]));
2409 protocol.revoke(controller, request);
2410 }
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423 public static void revoke(RpcController controller,
2424 AccessControlService.BlockingInterface protocol, String userShortName, String namespace,
2425 Permission.Action... actions) throws ServiceException {
2426 List<AccessControlProtos.Permission.Action> permActions =
2427 Lists.newArrayListWithCapacity(actions.length);
2428 for (Permission.Action a : actions) {
2429 permActions.add(ProtobufUtil.toPermissionAction(a));
2430 }
2431 AccessControlProtos.RevokeRequest request = RequestConverter.
2432 buildRevokeRequest(userShortName, namespace, permActions.toArray(
2433 new AccessControlProtos.Permission.Action[actions.length]));
2434 protocol.revoke(controller, request);
2435 }
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445 public static List<UserPermission> getUserPermissions(RpcController controller,
2446 AccessControlService.BlockingInterface protocol) throws ServiceException {
2447 AccessControlProtos.GetUserPermissionsRequest.Builder builder =
2448 AccessControlProtos.GetUserPermissionsRequest.newBuilder();
2449 builder.setType(AccessControlProtos.Permission.Type.Global);
2450 AccessControlProtos.GetUserPermissionsRequest request = builder.build();
2451 AccessControlProtos.GetUserPermissionsResponse response =
2452 protocol.getUserPermissions(controller, request);
2453 List<UserPermission> perms = new ArrayList<UserPermission>(response.getUserPermissionCount());
2454 for (AccessControlProtos.UserPermission perm: response.getUserPermissionList()) {
2455 perms.add(ProtobufUtil.toUserPermission(perm));
2456 }
2457 return perms;
2458 }
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469 public static List<UserPermission> getUserPermissions(RpcController controller,
2470 AccessControlService.BlockingInterface protocol,
2471 TableName t) throws ServiceException {
2472 AccessControlProtos.GetUserPermissionsRequest.Builder builder =
2473 AccessControlProtos.GetUserPermissionsRequest.newBuilder();
2474 if (t != null) {
2475 builder.setTableName(ProtobufUtil.toProtoTableName(t));
2476 }
2477 builder.setType(AccessControlProtos.Permission.Type.Table);
2478 AccessControlProtos.GetUserPermissionsRequest request = builder.build();
2479 AccessControlProtos.GetUserPermissionsResponse response =
2480 protocol.getUserPermissions(controller, request);
2481 List<UserPermission> perms = new ArrayList<UserPermission>(response.getUserPermissionCount());
2482 for (AccessControlProtos.UserPermission perm: response.getUserPermissionList()) {
2483 perms.add(ProtobufUtil.toUserPermission(perm));
2484 }
2485 return perms;
2486 }
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497 public static List<UserPermission> getUserPermissions(RpcController controller,
2498 AccessControlService.BlockingInterface protocol,
2499 byte[] namespace) throws ServiceException {
2500 AccessControlProtos.GetUserPermissionsRequest.Builder builder =
2501 AccessControlProtos.GetUserPermissionsRequest.newBuilder();
2502 if (namespace != null) {
2503 builder.setNamespaceName(ByteStringer.wrap(namespace));
2504 }
2505 builder.setType(AccessControlProtos.Permission.Type.Namespace);
2506 AccessControlProtos.GetUserPermissionsRequest request = builder.build();
2507 AccessControlProtos.GetUserPermissionsResponse response =
2508 protocol.getUserPermissions(controller, request);
2509 List<UserPermission> perms = new ArrayList<UserPermission>(response.getUserPermissionCount());
2510 for (AccessControlProtos.UserPermission perm: response.getUserPermissionList()) {
2511 perms.add(ProtobufUtil.toUserPermission(perm));
2512 }
2513 return perms;
2514 }
2515
2516
2517
2518
2519
2520
2521
2522
2523 public static ListMultimap<String, TablePermission> toUserTablePermissions(
2524 AccessControlProtos.UsersAndPermissions proto) {
2525 ListMultimap<String, TablePermission> perms = ArrayListMultimap.create();
2526 AccessControlProtos.UsersAndPermissions.UserPermissions userPerm;
2527
2528 for (int i = 0; i < proto.getUserPermissionsCount(); i++) {
2529 userPerm = proto.getUserPermissions(i);
2530 for (int j = 0; j < userPerm.getPermissionsCount(); j++) {
2531 TablePermission tablePerm = toTablePermission(userPerm.getPermissions(j));
2532 perms.put(userPerm.getUser().toStringUtf8(), tablePerm);
2533 }
2534 }
2535
2536 return perms;
2537 }
2538
2539
2540
2541
2542
2543
2544
2545 public static AuthenticationProtos.Token toToken(Token<AuthenticationTokenIdentifier> token) {
2546 AuthenticationProtos.Token.Builder builder = AuthenticationProtos.Token.newBuilder();
2547 builder.setIdentifier(ByteStringer.wrap(token.getIdentifier()));
2548 builder.setPassword(ByteStringer.wrap(token.getPassword()));
2549 if (token.getService() != null) {
2550 builder.setService(ByteString.copyFromUtf8(token.getService().toString()));
2551 }
2552 return builder.build();
2553 }
2554
2555
2556
2557
2558
2559
2560
2561 public static Token<AuthenticationTokenIdentifier> toToken(AuthenticationProtos.Token proto) {
2562 return new Token<AuthenticationTokenIdentifier>(
2563 proto.hasIdentifier() ? proto.getIdentifier().toByteArray() : null,
2564 proto.hasPassword() ? proto.getPassword().toByteArray() : null,
2565 AuthenticationTokenIdentifier.AUTH_TOKEN_TYPE,
2566 proto.hasService() ? new Text(proto.getService().toStringUtf8()) : null);
2567 }
2568
2569
2570
2571
2572
2573
2574
2575
2576 public static String getRegionEncodedName(
2577 final RegionSpecifier regionSpecifier) throws DoNotRetryIOException {
2578 ByteString value = regionSpecifier.getValue();
2579 RegionSpecifierType type = regionSpecifier.getType();
2580 switch (type) {
2581 case REGION_NAME:
2582 return HRegionInfo.encodeRegionName(value.toByteArray());
2583 case ENCODED_REGION_NAME:
2584 return value.toStringUtf8();
2585 default:
2586 throw new DoNotRetryIOException(
2587 "Unsupported region specifier type: " + type);
2588 }
2589 }
2590
2591 public static ScanMetrics toScanMetrics(final byte[] bytes) {
2592 Parser<MapReduceProtos.ScanMetrics> parser = MapReduceProtos.ScanMetrics.PARSER;
2593 MapReduceProtos.ScanMetrics pScanMetrics = null;
2594 try {
2595 pScanMetrics = parser.parseFrom(bytes);
2596 } catch (InvalidProtocolBufferException e) {
2597
2598 }
2599 ScanMetrics scanMetrics = new ScanMetrics();
2600 if (pScanMetrics != null) {
2601 for (HBaseProtos.NameInt64Pair pair : pScanMetrics.getMetricsList()) {
2602 if (pair.hasName() && pair.hasValue()) {
2603 scanMetrics.setCounter(pair.getName(), pair.getValue());
2604 }
2605 }
2606 }
2607 return scanMetrics;
2608 }
2609
2610 public static MapReduceProtos.ScanMetrics toScanMetrics(ScanMetrics scanMetrics) {
2611 MapReduceProtos.ScanMetrics.Builder builder = MapReduceProtos.ScanMetrics.newBuilder();
2612 Map<String, Long> metrics = scanMetrics.getMetricsMap();
2613 for (Entry<String, Long> e : metrics.entrySet()) {
2614 HBaseProtos.NameInt64Pair nameInt64Pair =
2615 HBaseProtos.NameInt64Pair.newBuilder()
2616 .setName(e.getKey())
2617 .setValue(e.getValue())
2618 .build();
2619 builder.addMetrics(nameInt64Pair);
2620 }
2621 return builder.build();
2622 }
2623
2624
2625
2626
2627
2628
2629 public static void toIOException(ServiceException se) throws IOException {
2630 if (se == null) {
2631 throw new NullPointerException("Null service exception passed!");
2632 }
2633
2634 Throwable cause = se.getCause();
2635 if (cause != null && cause instanceof IOException) {
2636 throw (IOException)cause;
2637 }
2638 throw new IOException(se);
2639 }
2640
2641 public static CellProtos.Cell toCell(final Cell kv) {
2642
2643
2644 CellProtos.Cell.Builder kvbuilder = CellProtos.Cell.newBuilder();
2645 kvbuilder.setRow(ByteStringer.wrap(kv.getRowArray(), kv.getRowOffset(),
2646 kv.getRowLength()));
2647 kvbuilder.setFamily(ByteStringer.wrap(kv.getFamilyArray(),
2648 kv.getFamilyOffset(), kv.getFamilyLength()));
2649 kvbuilder.setQualifier(ByteStringer.wrap(kv.getQualifierArray(),
2650 kv.getQualifierOffset(), kv.getQualifierLength()));
2651 kvbuilder.setCellType(CellProtos.CellType.valueOf(kv.getTypeByte()));
2652 kvbuilder.setTimestamp(kv.getTimestamp());
2653 kvbuilder.setValue(ByteStringer.wrap(kv.getValueArray(), kv.getValueOffset(),
2654 kv.getValueLength()));
2655 return kvbuilder.build();
2656 }
2657
2658 public static Cell toCell(final CellProtos.Cell cell) {
2659
2660
2661 return CellUtil.createCell(cell.getRow().toByteArray(),
2662 cell.getFamily().toByteArray(),
2663 cell.getQualifier().toByteArray(),
2664 cell.getTimestamp(),
2665 (byte)cell.getCellType().getNumber(),
2666 cell.getValue().toByteArray());
2667 }
2668
2669 public static HBaseProtos.NamespaceDescriptor toProtoNamespaceDescriptor(NamespaceDescriptor ns) {
2670 HBaseProtos.NamespaceDescriptor.Builder b =
2671 HBaseProtos.NamespaceDescriptor.newBuilder()
2672 .setName(ByteString.copyFromUtf8(ns.getName()));
2673 for(Map.Entry<String, String> entry: ns.getConfiguration().entrySet()) {
2674 b.addConfiguration(HBaseProtos.NameStringPair.newBuilder()
2675 .setName(entry.getKey())
2676 .setValue(entry.getValue()));
2677 }
2678 return b.build();
2679 }
2680
2681 public static NamespaceDescriptor toNamespaceDescriptor(
2682 HBaseProtos.NamespaceDescriptor desc) throws IOException {
2683 NamespaceDescriptor.Builder b =
2684 NamespaceDescriptor.create(desc.getName().toStringUtf8());
2685 for(HBaseProtos.NameStringPair prop : desc.getConfigurationList()) {
2686 b.addConfiguration(prop.getName(), prop.getValue());
2687 }
2688 return b.build();
2689 }
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701 @SuppressWarnings("unchecked")
2702 public static <T extends Message>
2703 T getParsedGenericInstance(Class<?> runtimeClass, int position, ByteString b)
2704 throws IOException {
2705 Type type = runtimeClass.getGenericSuperclass();
2706 Type argType = ((ParameterizedType)type).getActualTypeArguments()[position];
2707 Class<T> classType = (Class<T>)argType;
2708 T inst;
2709 try {
2710 Method m = classType.getMethod("parseFrom", ByteString.class);
2711 inst = (T)m.invoke(null, b);
2712 return inst;
2713 } catch (SecurityException e) {
2714 throw new IOException(e);
2715 } catch (NoSuchMethodException e) {
2716 throw new IOException(e);
2717 } catch (IllegalArgumentException e) {
2718 throw new IOException(e);
2719 } catch (InvocationTargetException e) {
2720 throw new IOException(e);
2721 } catch (IllegalAccessException e) {
2722 throw new IOException(e);
2723 }
2724 }
2725
2726 public static CompactionDescriptor toCompactionDescriptor(HRegionInfo info, byte[] family,
2727 List<Path> inputPaths, List<Path> outputPaths, Path storeDir) {
2728 return toCompactionDescriptor(info, null, family, inputPaths, outputPaths, storeDir);
2729 }
2730
2731 @SuppressWarnings("deprecation")
2732 public static CompactionDescriptor toCompactionDescriptor(HRegionInfo info, byte[] regionName,
2733 byte[] family, List<Path> inputPaths, List<Path> outputPaths, Path storeDir) {
2734
2735
2736
2737 CompactionDescriptor.Builder builder = CompactionDescriptor.newBuilder()
2738 .setTableName(ByteStringer.wrap(info.getTableName()))
2739 .setEncodedRegionName(ByteStringer.wrap(
2740 regionName == null ? info.getEncodedNameAsBytes() : regionName))
2741 .setFamilyName(ByteStringer.wrap(family))
2742 .setStoreHomeDir(storeDir.getName());
2743 for (Path inputPath : inputPaths) {
2744 builder.addCompactionInput(inputPath.getName());
2745 }
2746 for (Path outputPath : outputPaths) {
2747 builder.addCompactionOutput(outputPath.getName());
2748 }
2749 builder.setRegionName(ByteStringer.wrap(info.getRegionName()));
2750 return builder.build();
2751 }
2752
2753 public static FlushDescriptor toFlushDescriptor(FlushAction action, HRegionInfo hri,
2754 long flushSeqId, Map<byte[], List<Path>> committedFiles) {
2755 FlushDescriptor.Builder desc = FlushDescriptor.newBuilder()
2756 .setAction(action)
2757 .setEncodedRegionName(ByteStringer.wrap(hri.getEncodedNameAsBytes()))
2758 .setRegionName(ByteStringer.wrap(hri.getRegionName()))
2759 .setFlushSequenceNumber(flushSeqId)
2760 .setTableName(ByteStringer.wrap(hri.getTable().getName()));
2761
2762 for (Map.Entry<byte[], List<Path>> entry : committedFiles.entrySet()) {
2763 WALProtos.FlushDescriptor.StoreFlushDescriptor.Builder builder =
2764 WALProtos.FlushDescriptor.StoreFlushDescriptor.newBuilder()
2765 .setFamilyName(ByteStringer.wrap(entry.getKey()))
2766 .setStoreHomeDir(Bytes.toString(entry.getKey()));
2767 if (entry.getValue() != null) {
2768 for (Path path : entry.getValue()) {
2769 builder.addFlushOutput(path.getName());
2770 }
2771 }
2772 desc.addStoreFlushes(builder);
2773 }
2774 return desc.build();
2775 }
2776
2777 public static RegionEventDescriptor toRegionEventDescriptor(
2778 EventType eventType, HRegionInfo hri, long seqId, ServerName server,
2779 Map<byte[], List<Path>> storeFiles) {
2780 final byte[] tableNameAsBytes = hri.getTable().getName();
2781 final byte[] encodedNameAsBytes = hri.getEncodedNameAsBytes();
2782 final byte[] regionNameAsBytes = hri.getRegionName();
2783 return toRegionEventDescriptor(eventType,
2784 tableNameAsBytes,
2785 encodedNameAsBytes,
2786 regionNameAsBytes,
2787 seqId,
2788
2789 server,
2790 storeFiles);
2791 }
2792
2793 public static RegionEventDescriptor toRegionEventDescriptor(EventType eventType,
2794 byte[] tableNameAsBytes,
2795 byte[] encodedNameAsBytes,
2796 byte[] regionNameAsBytes,
2797 long seqId,
2798
2799 ServerName server,
2800 Map<byte[], List<Path>> storeFiles) {
2801 RegionEventDescriptor.Builder desc = RegionEventDescriptor.newBuilder()
2802 .setEventType(eventType)
2803 .setTableName(ByteStringer.wrap(tableNameAsBytes))
2804 .setEncodedRegionName(ByteStringer.wrap(encodedNameAsBytes))
2805 .setRegionName(ByteStringer.wrap(regionNameAsBytes))
2806 .setLogSequenceNumber(seqId)
2807 .setServer(toServerName(server));
2808
2809 for (Entry<byte[], List<Path>> entry : storeFiles.entrySet()) {
2810 StoreDescriptor.Builder builder = StoreDescriptor.newBuilder()
2811 .setFamilyName(ByteStringer.wrap(entry.getKey()))
2812 .setStoreHomeDir(Bytes.toString(entry.getKey()));
2813 for (Path path : entry.getValue()) {
2814 builder.addStoreFile(path.getName());
2815 }
2816
2817 desc.addStores(builder);
2818 }
2819 return desc.build();
2820 }
2821
2822
2823
2824
2825
2826
2827
2828
2829 public static String getShortTextFormat(Message m) {
2830 if (m == null) return "null";
2831 if (m instanceof ScanRequest) {
2832
2833 return TextFormat.shortDebugString(m);
2834 } else if (m instanceof RegionServerReportRequest) {
2835
2836 RegionServerReportRequest r = (RegionServerReportRequest)m;
2837 return "server " + TextFormat.shortDebugString(r.getServer()) +
2838 " load { numberOfRequests: " + r.getLoad().getNumberOfRequests() + " }";
2839 } else if (m instanceof RegionServerStartupRequest) {
2840
2841 return TextFormat.shortDebugString(m);
2842 } else if (m instanceof MutationProto) {
2843 return toShortString((MutationProto)m);
2844 } else if (m instanceof GetRequest) {
2845 GetRequest r = (GetRequest) m;
2846 return "region= " + getStringForByteString(r.getRegion().getValue()) +
2847 ", row=" + getStringForByteString(r.getGet().getRow());
2848 } else if (m instanceof ClientProtos.MultiRequest) {
2849 ClientProtos.MultiRequest r = (ClientProtos.MultiRequest) m;
2850
2851
2852 int actionsCount = 0;
2853 for (ClientProtos.RegionAction regionAction : r.getRegionActionList()) {
2854 actionsCount += regionAction.getActionCount();
2855 }
2856
2857
2858 ClientProtos.RegionAction actions = r.getRegionActionList().get(0);
2859 String row = actions.getActionCount() <= 0? "":
2860 getStringForByteString(actions.getAction(0).hasGet()?
2861 actions.getAction(0).getGet().getRow():
2862 actions.getAction(0).getMutation().getRow());
2863 return "region= " + getStringForByteString(actions.getRegion().getValue()) +
2864 ", for " + actionsCount + " action(s) and 1st row key=" + row;
2865 } else if (m instanceof ClientProtos.MutateRequest) {
2866 ClientProtos.MutateRequest r = (ClientProtos.MutateRequest) m;
2867 return "region= " + getStringForByteString(r.getRegion().getValue()) +
2868 ", row=" + getStringForByteString(r.getMutation().getRow());
2869 }
2870 return "TODO: " + m.getClass().toString();
2871 }
2872
2873 private static String getStringForByteString(ByteString bs) {
2874 return Bytes.toStringBinary(bs.toByteArray());
2875 }
2876
2877
2878
2879
2880
2881
2882 static String toShortString(final MutationProto proto) {
2883 return "row=" + Bytes.toString(proto.getRow().toByteArray()) +
2884 ", type=" + proto.getMutateType().toString();
2885 }
2886
2887 public static TableName toTableName(HBaseProtos.TableName tableNamePB) {
2888 return TableName.valueOf(tableNamePB.getNamespace().asReadOnlyByteBuffer(),
2889 tableNamePB.getQualifier().asReadOnlyByteBuffer());
2890 }
2891
2892 public static HBaseProtos.TableName toProtoTableName(TableName tableName) {
2893 return HBaseProtos.TableName.newBuilder()
2894 .setNamespace(ByteStringer.wrap(tableName.getNamespace()))
2895 .setQualifier(ByteStringer.wrap(tableName.getQualifier())).build();
2896 }
2897
2898 public static TableName[] getTableNameArray(List<HBaseProtos.TableName> tableNamesList) {
2899 if (tableNamesList == null) {
2900 return new TableName[0];
2901 }
2902 TableName[] tableNames = new TableName[tableNamesList.size()];
2903 for (int i = 0; i < tableNamesList.size(); i++) {
2904 tableNames[i] = toTableName(tableNamesList.get(i));
2905 }
2906 return tableNames;
2907 }
2908
2909
2910
2911
2912
2913
2914
2915 public static CellVisibility toCellVisibility(ClientProtos.CellVisibility proto) {
2916 if (proto == null) return null;
2917 return new CellVisibility(proto.getExpression());
2918 }
2919
2920
2921
2922
2923
2924
2925
2926
2927 public static CellVisibility toCellVisibility(byte[] protoBytes) throws DeserializationException {
2928 if (protoBytes == null) return null;
2929 ClientProtos.CellVisibility.Builder builder = ClientProtos.CellVisibility.newBuilder();
2930 ClientProtos.CellVisibility proto = null;
2931 try {
2932 ProtobufUtil.mergeFrom(builder, protoBytes);
2933 proto = builder.build();
2934 } catch (IOException e) {
2935 throw new DeserializationException(e);
2936 }
2937 return toCellVisibility(proto);
2938 }
2939
2940
2941
2942
2943
2944
2945
2946 public static ClientProtos.CellVisibility toCellVisibility(CellVisibility cellVisibility) {
2947 ClientProtos.CellVisibility.Builder builder = ClientProtos.CellVisibility.newBuilder();
2948 builder.setExpression(cellVisibility.getExpression());
2949 return builder.build();
2950 }
2951
2952
2953
2954
2955
2956
2957
2958 public static Authorizations toAuthorizations(ClientProtos.Authorizations proto) {
2959 if (proto == null) return null;
2960 return new Authorizations(proto.getLabelList());
2961 }
2962
2963
2964
2965
2966
2967
2968
2969
2970 public static Authorizations toAuthorizations(byte[] protoBytes) throws DeserializationException {
2971 if (protoBytes == null) return null;
2972 ClientProtos.Authorizations.Builder builder = ClientProtos.Authorizations.newBuilder();
2973 ClientProtos.Authorizations proto = null;
2974 try {
2975 ProtobufUtil.mergeFrom(builder, protoBytes);
2976 proto = builder.build();
2977 } catch (IOException e) {
2978 throw new DeserializationException(e);
2979 }
2980 return toAuthorizations(proto);
2981 }
2982
2983
2984
2985
2986
2987
2988
2989 public static ClientProtos.Authorizations toAuthorizations(Authorizations authorizations) {
2990 ClientProtos.Authorizations.Builder builder = ClientProtos.Authorizations.newBuilder();
2991 for (String label : authorizations.getLabels()) {
2992 builder.addLabel(label);
2993 }
2994 return builder.build();
2995 }
2996
2997 public static AccessControlProtos.UsersAndPermissions toUsersAndPermissions(String user,
2998 Permission perms) {
2999 return AccessControlProtos.UsersAndPermissions.newBuilder()
3000 .addUserPermissions(AccessControlProtos.UsersAndPermissions.UserPermissions.newBuilder()
3001 .setUser(ByteString.copyFromUtf8(user))
3002 .addPermissions(toPermission(perms))
3003 .build())
3004 .build();
3005 }
3006
3007 public static AccessControlProtos.UsersAndPermissions toUsersAndPermissions(
3008 ListMultimap<String, Permission> perms) {
3009 AccessControlProtos.UsersAndPermissions.Builder builder =
3010 AccessControlProtos.UsersAndPermissions.newBuilder();
3011 for (Map.Entry<String, Collection<Permission>> entry : perms.asMap().entrySet()) {
3012 AccessControlProtos.UsersAndPermissions.UserPermissions.Builder userPermBuilder =
3013 AccessControlProtos.UsersAndPermissions.UserPermissions.newBuilder();
3014 userPermBuilder.setUser(ByteString.copyFromUtf8(entry.getKey()));
3015 for (Permission perm: entry.getValue()) {
3016 userPermBuilder.addPermissions(toPermission(perm));
3017 }
3018 builder.addUserPermissions(userPermBuilder.build());
3019 }
3020 return builder.build();
3021 }
3022
3023 public static ListMultimap<String, Permission> toUsersAndPermissions(
3024 AccessControlProtos.UsersAndPermissions proto) {
3025 ListMultimap<String, Permission> result = ArrayListMultimap.create();
3026 for (AccessControlProtos.UsersAndPermissions.UserPermissions userPerms:
3027 proto.getUserPermissionsList()) {
3028 String user = userPerms.getUser().toStringUtf8();
3029 for (AccessControlProtos.Permission perm: userPerms.getPermissionsList()) {
3030 result.put(user, toPermission(perm));
3031 }
3032 }
3033 return result;
3034 }
3035
3036
3037
3038
3039
3040
3041 public static TimeUnit toTimeUnit(final HBaseProtos.TimeUnit proto) {
3042 switch (proto) {
3043 case NANOSECONDS:
3044 return TimeUnit.NANOSECONDS;
3045 case MICROSECONDS:
3046 return TimeUnit.MICROSECONDS;
3047 case MILLISECONDS:
3048 return TimeUnit.MILLISECONDS;
3049 case SECONDS:
3050 return TimeUnit.SECONDS;
3051 case MINUTES:
3052 return TimeUnit.MINUTES;
3053 case HOURS:
3054 return TimeUnit.HOURS;
3055 case DAYS:
3056 return TimeUnit.DAYS;
3057 default:
3058 throw new RuntimeException("Invalid TimeUnit " + proto);
3059 }
3060 }
3061
3062
3063
3064
3065
3066
3067 public static HBaseProtos.TimeUnit toProtoTimeUnit(final TimeUnit timeUnit) {
3068 switch (timeUnit) {
3069 case NANOSECONDS:
3070 return HBaseProtos.TimeUnit.NANOSECONDS;
3071 case MICROSECONDS:
3072 return HBaseProtos.TimeUnit.MICROSECONDS;
3073 case MILLISECONDS:
3074 return HBaseProtos.TimeUnit.MILLISECONDS;
3075 case SECONDS:
3076 return HBaseProtos.TimeUnit.SECONDS;
3077 case MINUTES:
3078 return HBaseProtos.TimeUnit.MINUTES;
3079 case HOURS:
3080 return HBaseProtos.TimeUnit.HOURS;
3081 case DAYS:
3082 return HBaseProtos.TimeUnit.DAYS;
3083 default:
3084 throw new RuntimeException("Invalid TimeUnit " + timeUnit);
3085 }
3086 }
3087
3088
3089
3090
3091
3092
3093 public static ThrottleType toThrottleType(final QuotaProtos.ThrottleType proto) {
3094 switch (proto) {
3095 case REQUEST_NUMBER:
3096 return ThrottleType.REQUEST_NUMBER;
3097 case REQUEST_SIZE:
3098 return ThrottleType.REQUEST_SIZE;
3099 case WRITE_NUMBER:
3100 return ThrottleType.WRITE_NUMBER;
3101 case WRITE_SIZE:
3102 return ThrottleType.WRITE_SIZE;
3103 case READ_NUMBER:
3104 return ThrottleType.READ_NUMBER;
3105 case READ_SIZE:
3106 return ThrottleType.READ_SIZE;
3107 default:
3108 throw new RuntimeException("Invalid ThrottleType " + proto);
3109 }
3110 }
3111
3112
3113
3114
3115
3116
3117 public static QuotaProtos.ThrottleType toProtoThrottleType(final ThrottleType type) {
3118 switch (type) {
3119 case REQUEST_NUMBER:
3120 return QuotaProtos.ThrottleType.REQUEST_NUMBER;
3121 case REQUEST_SIZE:
3122 return QuotaProtos.ThrottleType.REQUEST_SIZE;
3123 case WRITE_NUMBER:
3124 return QuotaProtos.ThrottleType.WRITE_NUMBER;
3125 case WRITE_SIZE:
3126 return QuotaProtos.ThrottleType.WRITE_SIZE;
3127 case READ_NUMBER:
3128 return QuotaProtos.ThrottleType.READ_NUMBER;
3129 case READ_SIZE:
3130 return QuotaProtos.ThrottleType.READ_SIZE;
3131 default:
3132 throw new RuntimeException("Invalid ThrottleType " + type);
3133 }
3134 }
3135
3136
3137
3138
3139
3140
3141 public static QuotaScope toQuotaScope(final QuotaProtos.QuotaScope proto) {
3142 switch (proto) {
3143 case CLUSTER:
3144 return QuotaScope.CLUSTER;
3145 case MACHINE:
3146 return QuotaScope.MACHINE;
3147 default:
3148 throw new RuntimeException("Invalid QuotaScope " + proto);
3149 }
3150 }
3151
3152
3153
3154
3155
3156
3157 public static QuotaProtos.QuotaScope toProtoQuotaScope(final QuotaScope scope) {
3158 switch (scope) {
3159 case CLUSTER:
3160 return QuotaProtos.QuotaScope.CLUSTER;
3161 case MACHINE:
3162 return QuotaProtos.QuotaScope.MACHINE;
3163 default:
3164 throw new RuntimeException("Invalid QuotaScope " + scope);
3165 }
3166 }
3167
3168
3169
3170
3171
3172
3173 public static QuotaType toQuotaScope(final QuotaProtos.QuotaType proto) {
3174 switch (proto) {
3175 case THROTTLE:
3176 return QuotaType.THROTTLE;
3177 default:
3178 throw new RuntimeException("Invalid QuotaType " + proto);
3179 }
3180 }
3181
3182
3183
3184
3185
3186
3187 public static QuotaProtos.QuotaType toProtoQuotaScope(final QuotaType type) {
3188 switch (type) {
3189 case THROTTLE:
3190 return QuotaProtos.QuotaType.THROTTLE;
3191 default:
3192 throw new RuntimeException("Invalid QuotaType " + type);
3193 }
3194 }
3195
3196
3197
3198
3199
3200
3201
3202
3203 public static QuotaProtos.TimedQuota toTimedQuota(final long limit, final TimeUnit timeUnit,
3204 final QuotaScope scope) {
3205 return QuotaProtos.TimedQuota.newBuilder().setSoftLimit(limit)
3206 .setTimeUnit(toProtoTimeUnit(timeUnit)).setScope(toProtoQuotaScope(scope)).build();
3207 }
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221 public static WALProtos.BulkLoadDescriptor toBulkLoadDescriptor(TableName tableName,
3222 ByteString encodedRegionName, Map<byte[], List<Path>> storeFiles,
3223 Map<String, Long> storeFilesSize, long bulkloadSeqId) {
3224 BulkLoadDescriptor.Builder desc =
3225 BulkLoadDescriptor.newBuilder()
3226 .setTableName(ProtobufUtil.toProtoTableName(tableName))
3227 .setEncodedRegionName(encodedRegionName).setBulkloadSeqNum(bulkloadSeqId);
3228
3229 for (Map.Entry<byte[], List<Path>> entry : storeFiles.entrySet()) {
3230 WALProtos.StoreDescriptor.Builder builder = StoreDescriptor.newBuilder()
3231 .setFamilyName(ByteStringer.wrap(entry.getKey()))
3232 .setStoreHomeDir(Bytes.toString(entry.getKey()));
3233 for (Path path : entry.getValue()) {
3234 String name = path.getName();
3235 builder.addStoreFile(name);
3236 Long size = storeFilesSize.get(name) == null ? (Long) 0L : storeFilesSize.get(name);
3237 builder.setStoreFileSizeBytes(size);
3238 }
3239 desc.addStores(builder);
3240 }
3241
3242 return desc.build();
3243 }
3244
3245
3246
3247
3248
3249
3250
3251
3252 public static void mergeDelimitedFrom(Message.Builder builder, InputStream in)
3253 throws IOException {
3254
3255
3256 final int firstByte = in.read();
3257 if (firstByte != -1) {
3258 final int size = CodedInputStream.readRawVarint32(firstByte, in);
3259 final InputStream limitedInput = new LimitInputStream(in, size);
3260 final CodedInputStream codedInput = CodedInputStream.newInstance(limitedInput);
3261 codedInput.setSizeLimit(size);
3262 builder.mergeFrom(codedInput);
3263 codedInput.checkLastTagWas(0);
3264 }
3265 }
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275 public static void mergeFrom(Message.Builder builder, InputStream in, int size)
3276 throws IOException {
3277 final CodedInputStream codedInput = CodedInputStream.newInstance(in);
3278 codedInput.setSizeLimit(size);
3279 builder.mergeFrom(codedInput);
3280 codedInput.checkLastTagWas(0);
3281 }
3282
3283
3284
3285
3286
3287
3288
3289
3290 public static void mergeFrom(Message.Builder builder, InputStream in)
3291 throws IOException {
3292 final CodedInputStream codedInput = CodedInputStream.newInstance(in);
3293 codedInput.setSizeLimit(Integer.MAX_VALUE);
3294 builder.mergeFrom(codedInput);
3295 codedInput.checkLastTagWas(0);
3296 }
3297
3298
3299
3300
3301
3302
3303
3304
3305 public static void mergeFrom(Message.Builder builder, ByteString bs) throws IOException {
3306 final CodedInputStream codedInput = bs.newCodedInput();
3307 codedInput.setSizeLimit(bs.size());
3308 builder.mergeFrom(codedInput);
3309 codedInput.checkLastTagWas(0);
3310 }
3311
3312
3313
3314
3315
3316
3317
3318
3319 public static void mergeFrom(Message.Builder builder, byte[] b) throws IOException {
3320 final CodedInputStream codedInput = CodedInputStream.newInstance(b);
3321 codedInput.setSizeLimit(b.length);
3322 builder.mergeFrom(codedInput);
3323 codedInput.checkLastTagWas(0);
3324 }
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335 public static void mergeFrom(Message.Builder builder, byte[] b, int offset, int length)
3336 throws IOException {
3337 final CodedInputStream codedInput = CodedInputStream.newInstance(b, offset, length);
3338 codedInput.setSizeLimit(length);
3339 builder.mergeFrom(codedInput);
3340 codedInput.checkLastTagWas(0);
3341 }
3342
3343 public static void mergeFrom(Message.Builder builder, CodedInputStream codedInput, int length)
3344 throws IOException {
3345 codedInput.resetSizeCounter();
3346 int prevLimit = codedInput.setSizeLimit(length);
3347
3348 int limit = codedInput.pushLimit(length);
3349 builder.mergeFrom(codedInput);
3350 codedInput.popLimit(limit);
3351
3352 codedInput.checkLastTagWas(0);
3353 codedInput.setSizeLimit(prevLimit);
3354 }
3355
3356 public static ReplicationLoadSink toReplicationLoadSink(
3357 ClusterStatusProtos.ReplicationLoadSink cls) {
3358 return new ReplicationLoadSink(cls.getAgeOfLastAppliedOp(), cls.getTimeStampsOfLastAppliedOp());
3359 }
3360
3361 public static ReplicationLoadSource toReplicationLoadSource(
3362 ClusterStatusProtos.ReplicationLoadSource cls) {
3363 return new ReplicationLoadSource(cls.getPeerID(), cls.getAgeOfLastShippedOp(),
3364 cls.getSizeOfLogQueue(), cls.getTimeStampOfLastShippedOp(), cls.getReplicationLag());
3365 }
3366
3367 public static List<ReplicationLoadSource> toReplicationLoadSourceList(
3368 List<ClusterStatusProtos.ReplicationLoadSource> clsList) {
3369 ArrayList<ReplicationLoadSource> rlsList = new ArrayList<ReplicationLoadSource>();
3370 for (ClusterStatusProtos.ReplicationLoadSource cls : clsList) {
3371 rlsList.add(toReplicationLoadSource(cls));
3372 }
3373 return rlsList;
3374 }
3375
3376
3377
3378
3379
3380
3381 public static HBaseProtos.VersionInfo getVersionInfo() {
3382 HBaseProtos.VersionInfo.Builder builder = HBaseProtos.VersionInfo.newBuilder();
3383 String version = VersionInfo.getVersion();
3384 builder.setVersion(version);
3385 String[] components = version.split("\\.");
3386 if (components != null && components.length > 2) {
3387 builder.setVersionMajor(Integer.parseInt(components[0]));
3388 builder.setVersionMinor(Integer.parseInt(components[1]));
3389 }
3390 builder.setUrl(VersionInfo.getUrl());
3391 builder.setRevision(VersionInfo.getRevision());
3392 builder.setUser(VersionInfo.getUser());
3393 builder.setDate(VersionInfo.getDate());
3394 builder.setSrcChecksum(VersionInfo.getSrcChecksum());
3395 return builder.build();
3396 }
3397
3398
3399
3400
3401
3402
3403 public static List<SecurityCapability> toSecurityCapabilityList(
3404 List<MasterProtos.SecurityCapabilitiesResponse.Capability> capabilities) {
3405 List<SecurityCapability> scList = new ArrayList<>(capabilities.size());
3406 for (MasterProtos.SecurityCapabilitiesResponse.Capability c: capabilities) {
3407 try {
3408 scList.add(SecurityCapability.valueOf(c.getNumber()));
3409 } catch (IllegalArgumentException e) {
3410
3411
3412 }
3413 }
3414 return scList;
3415 }
3416
3417 private static HBaseProtos.TimeRange.Builder timeRangeToProto(TimeRange timeRange) {
3418 HBaseProtos.TimeRange.Builder timeRangeBuilder =
3419 HBaseProtos.TimeRange.newBuilder();
3420 timeRangeBuilder.setFrom(timeRange.getMin());
3421 timeRangeBuilder.setTo(timeRange.getMax());
3422 return timeRangeBuilder;
3423 }
3424
3425 private static TimeRange protoToTimeRange(HBaseProtos.TimeRange timeRange) throws IOException {
3426 long minStamp = 0;
3427 long maxStamp = Long.MAX_VALUE;
3428 if (timeRange.hasFrom()) {
3429 minStamp = timeRange.getFrom();
3430 }
3431 if (timeRange.hasTo()) {
3432 maxStamp = timeRange.getTo();
3433 }
3434 return new TimeRange(minStamp, maxStamp);
3435 }
3436
3437 public static byte[] toCompactionEventTrackerBytes(Set<String> storeFiles) {
3438 HFileProtos.CompactionEventTracker.Builder builder =
3439 HFileProtos.CompactionEventTracker.newBuilder();
3440 for (String sf : storeFiles) {
3441 builder.addCompactedStoreFile(ByteString.copyFromUtf8(sf));
3442 }
3443 return ProtobufUtil.prependPBMagic(builder.build().toByteArray());
3444 }
3445
3446 public static Set<String> toCompactedStoreFiles(byte[] bytes) throws IOException {
3447 if (bytes != null && ProtobufUtil.isPBMagicPrefix(bytes)) {
3448 int pbLen = ProtobufUtil.lengthOfPBMagic();
3449 HFileProtos.CompactionEventTracker.Builder builder =
3450 HFileProtos.CompactionEventTracker.newBuilder();
3451 ProtobufUtil.mergeFrom(builder, bytes, pbLen, bytes.length - pbLen);
3452 HFileProtos.CompactionEventTracker compactionEventTracker = builder.build();
3453 List<ByteString> compactedStoreFiles = compactionEventTracker.getCompactedStoreFileList();
3454 if (compactedStoreFiles != null && compactedStoreFiles.size() != 0) {
3455 Set<String> compactedStoreFileSet = new HashSet<>();
3456 for (ByteString sf : compactedStoreFiles) {
3457 compactedStoreFileSet.add(sf.toStringUtf8());
3458 }
3459 return compactedStoreFileSet;
3460 }
3461 }
3462 return Collections.emptySet();
3463 }
3464 }