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 org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.RegionSpecifier.RegionSpecifierType.REGION_NAME;
22
23 import java.io.ByteArrayOutputStream;
24 import java.io.IOException;
25 import java.lang.reflect.Constructor;
26 import java.lang.reflect.InvocationTargetException;
27 import java.lang.reflect.Method;
28 import java.lang.reflect.ParameterizedType;
29 import java.lang.reflect.Type;
30 import java.nio.ByteBuffer;
31 import java.util.ArrayList;
32 import java.util.Collection;
33 import java.util.HashMap;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.Map.Entry;
37 import java.util.NavigableSet;
38
39 import org.apache.hadoop.conf.Configuration;
40 import org.apache.hadoop.fs.Path;
41 import org.apache.hadoop.hbase.Cell;
42 import org.apache.hadoop.hbase.CellScanner;
43 import org.apache.hadoop.hbase.CellUtil;
44 import org.apache.hadoop.hbase.DoNotRetryIOException;
45 import org.apache.hadoop.hbase.HBaseConfiguration;
46 import org.apache.hadoop.hbase.HConstants;
47 import org.apache.hadoop.hbase.HRegionInfo;
48 import org.apache.hadoop.hbase.HTableDescriptor;
49 import org.apache.hadoop.hbase.KeyValue;
50 import org.apache.hadoop.hbase.KeyValueUtil;
51 import org.apache.hadoop.hbase.NamespaceDescriptor;
52 import org.apache.hadoop.hbase.ServerName;
53 import org.apache.hadoop.hbase.TableName;
54 import org.apache.hadoop.hbase.Tag;
55 import org.apache.hadoop.hbase.client.Append;
56 import org.apache.hadoop.hbase.client.Delete;
57 import org.apache.hadoop.hbase.client.Durability;
58 import org.apache.hadoop.hbase.client.Get;
59 import org.apache.hadoop.hbase.client.Increment;
60 import org.apache.hadoop.hbase.client.Mutation;
61 import org.apache.hadoop.hbase.client.Put;
62 import org.apache.hadoop.hbase.client.Result;
63 import org.apache.hadoop.hbase.client.Scan;
64 import org.apache.hadoop.hbase.client.metrics.ScanMetrics;
65 import org.apache.hadoop.hbase.exceptions.DeserializationException;
66 import org.apache.hadoop.hbase.filter.ByteArrayComparable;
67 import org.apache.hadoop.hbase.filter.Filter;
68 import org.apache.hadoop.hbase.io.TimeRange;
69 import org.apache.hadoop.hbase.ipc.PayloadCarryingRpcController;
70 import org.apache.hadoop.hbase.protobuf.generated.AccessControlProtos;
71 import org.apache.hadoop.hbase.protobuf.generated.AccessControlProtos.AccessControlService;
72 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.AdminService;
73 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.CloseRegionRequest;
74 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.CloseRegionResponse;
75 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetOnlineRegionRequest;
76 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetOnlineRegionResponse;
77 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetRegionInfoRequest;
78 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetRegionInfoResponse;
79 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetServerInfoRequest;
80 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetServerInfoResponse;
81 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetStoreFileRequest;
82 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetStoreFileResponse;
83 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.MergeRegionsRequest;
84 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.OpenRegionRequest;
85 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.ServerInfo;
86 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.SplitRegionRequest;
87 import org.apache.hadoop.hbase.protobuf.generated.AuthenticationProtos;
88 import org.apache.hadoop.hbase.protobuf.generated.CellProtos;
89 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos;
90 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.BulkLoadHFileRequest;
91 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.BulkLoadHFileResponse;
92 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ClientService;
93 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.Column;
94 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.CoprocessorServiceCall;
95 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.CoprocessorServiceRequest;
96 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.CoprocessorServiceResponse;
97 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.GetRequest;
98 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.GetResponse;
99 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutationProto;
100 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutationProto.ColumnValue;
101 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutationProto.ColumnValue.QualifierValue;
102 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutationProto.DeleteType;
103 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutationProto.MutationType;
104 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ScanRequest;
105 import org.apache.hadoop.hbase.protobuf.generated.ClusterStatusProtos.RegionLoad;
106 import org.apache.hadoop.hbase.protobuf.generated.ComparatorProtos;
107 import org.apache.hadoop.hbase.protobuf.generated.FilterProtos;
108 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos;
109 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.NameBytesPair;
110 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.RegionInfo;
111 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.RegionSpecifier;
112 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.RegionSpecifier.RegionSpecifierType;
113 import org.apache.hadoop.hbase.protobuf.generated.MapReduceProtos;
114 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.CreateTableRequest;
115 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetTableDescriptorsResponse;
116 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.MasterService;
117 import org.apache.hadoop.hbase.protobuf.generated.RegionServerStatusProtos.RegionServerReportRequest;
118 import org.apache.hadoop.hbase.protobuf.generated.RegionServerStatusProtos.RegionServerStartupRequest;
119 import org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor;
120 import org.apache.hadoop.hbase.security.access.Permission;
121 import org.apache.hadoop.hbase.security.access.TablePermission;
122 import org.apache.hadoop.hbase.security.access.UserPermission;
123 import org.apache.hadoop.hbase.security.token.AuthenticationTokenIdentifier;
124 import org.apache.hadoop.hbase.security.visibility.Authorizations;
125 import org.apache.hadoop.hbase.security.visibility.CellVisibility;
126 import org.apache.hadoop.hbase.util.ByteStringer;
127 import org.apache.hadoop.hbase.util.Bytes;
128 import org.apache.hadoop.hbase.util.DynamicClassLoader;
129 import org.apache.hadoop.hbase.util.ExceptionUtil;
130 import org.apache.hadoop.hbase.util.Methods;
131 import org.apache.hadoop.hbase.util.Pair;
132 import org.apache.hadoop.io.Text;
133 import org.apache.hadoop.ipc.RemoteException;
134 import org.apache.hadoop.security.token.Token;
135
136 import com.google.common.collect.ArrayListMultimap;
137 import com.google.common.collect.ListMultimap;
138 import com.google.common.collect.Lists;
139 import com.google.protobuf.ByteString;
140 import com.google.protobuf.InvalidProtocolBufferException;
141 import com.google.protobuf.Message;
142 import com.google.protobuf.Parser;
143 import com.google.protobuf.RpcChannel;
144 import com.google.protobuf.Service;
145 import com.google.protobuf.ServiceException;
146 import com.google.protobuf.TextFormat;
147
148
149
150
151 public final class ProtobufUtil {
152
153 private ProtobufUtil() {
154 }
155
156
157
158
159 private final static Map<String, Class<?>>
160 PRIMITIVES = new HashMap<String, Class<?>>();
161
162
163
164
165
166
167 private final static Cell[] EMPTY_CELL_ARRAY = new Cell[]{};
168 private final static Result EMPTY_RESULT = Result.create(EMPTY_CELL_ARRAY);
169 private final static Result EMPTY_RESULT_EXISTS_TRUE = Result.create(null, true);
170 private final static Result EMPTY_RESULT_EXISTS_FALSE = Result.create(null, false);
171
172 private final static ClientProtos.Result EMPTY_RESULT_PB;
173 private final static ClientProtos.Result EMPTY_RESULT_PB_EXISTS_TRUE;
174 private final static ClientProtos.Result EMPTY_RESULT_PB_EXISTS_FALSE;
175
176 static {
177 ClientProtos.Result.Builder builder = ClientProtos.Result.newBuilder();
178
179 builder.setExists(true);
180 builder.setAssociatedCellCount(0);
181 EMPTY_RESULT_PB_EXISTS_TRUE = builder.build();
182
183 builder.clear();
184
185 builder.setExists(false);
186 builder.setAssociatedCellCount(0);
187 EMPTY_RESULT_PB_EXISTS_FALSE = builder.build();
188
189 builder.clear();
190 builder.setAssociatedCellCount(0);
191 EMPTY_RESULT_PB = builder.build();
192 }
193
194
195
196
197 private final static ClassLoader CLASS_LOADER;
198
199 static {
200 ClassLoader parent = ProtobufUtil.class.getClassLoader();
201 Configuration conf = HBaseConfiguration.create();
202 CLASS_LOADER = new DynamicClassLoader(conf, parent);
203
204 PRIMITIVES.put(Boolean.TYPE.getName(), Boolean.TYPE);
205 PRIMITIVES.put(Byte.TYPE.getName(), Byte.TYPE);
206 PRIMITIVES.put(Character.TYPE.getName(), Character.TYPE);
207 PRIMITIVES.put(Short.TYPE.getName(), Short.TYPE);
208 PRIMITIVES.put(Integer.TYPE.getName(), Integer.TYPE);
209 PRIMITIVES.put(Long.TYPE.getName(), Long.TYPE);
210 PRIMITIVES.put(Float.TYPE.getName(), Float.TYPE);
211 PRIMITIVES.put(Double.TYPE.getName(), Double.TYPE);
212 PRIMITIVES.put(Void.TYPE.getName(), Void.TYPE);
213 }
214
215
216
217
218
219
220 public static final byte [] PB_MAGIC = new byte [] {'P', 'B', 'U', 'F'};
221 private static final String PB_MAGIC_STR = Bytes.toString(PB_MAGIC);
222
223
224
225
226
227
228
229
230 public static byte [] prependPBMagic(final byte [] bytes) {
231 return Bytes.add(PB_MAGIC, bytes);
232 }
233
234
235
236
237
238 public static boolean isPBMagicPrefix(final byte [] bytes) {
239 return isPBMagicPrefix(bytes, 0, bytes.length);
240 }
241
242
243
244
245
246 public static boolean isPBMagicPrefix(final byte [] bytes, int offset, int len) {
247 if (bytes == null || len < PB_MAGIC.length) return false;
248 return Bytes.compareTo(PB_MAGIC, 0, PB_MAGIC.length, bytes, offset, PB_MAGIC.length) == 0;
249 }
250
251
252
253
254
255 public static void expectPBMagicPrefix(final byte [] bytes) throws DeserializationException {
256 if (!isPBMagicPrefix(bytes)) {
257 throw new DeserializationException("Missing pb magic " + PB_MAGIC_STR + " prefix");
258 }
259 }
260
261
262
263
264 public static int lengthOfPBMagic() {
265 return PB_MAGIC.length;
266 }
267
268
269
270
271
272
273
274
275
276 public static IOException getRemoteException(ServiceException se) {
277 Throwable e = se.getCause();
278 if (e == null) {
279 return new IOException(se);
280 }
281 if (ExceptionUtil.isInterrupt(e)) {
282 return ExceptionUtil.asInterrupt(e);
283 }
284 if (e instanceof RemoteException) {
285 e = ((RemoteException) e).unwrapRemoteException();
286 }
287 return e instanceof IOException ? (IOException) e : new IOException(se);
288 }
289
290
291
292
293
294
295
296
297 public static HBaseProtos.ServerName
298 toServerName(final ServerName serverName) {
299 if (serverName == null) return null;
300 HBaseProtos.ServerName.Builder builder =
301 HBaseProtos.ServerName.newBuilder();
302 builder.setHostName(serverName.getHostname());
303 if (serverName.getPort() >= 0) {
304 builder.setPort(serverName.getPort());
305 }
306 if (serverName.getStartcode() >= 0) {
307 builder.setStartCode(serverName.getStartcode());
308 }
309 return builder.build();
310 }
311
312
313
314
315
316
317
318 public static ServerName toServerName(final HBaseProtos.ServerName proto) {
319 if (proto == null) return null;
320 String hostName = proto.getHostName();
321 long startCode = -1;
322 int port = -1;
323 if (proto.hasPort()) {
324 port = proto.getPort();
325 }
326 if (proto.hasStartCode()) {
327 startCode = proto.getStartCode();
328 }
329 return ServerName.valueOf(hostName, port, startCode);
330 }
331
332
333
334
335
336
337
338 public static HTableDescriptor[] getHTableDescriptorArray(GetTableDescriptorsResponse proto) {
339 if (proto == null) return null;
340
341 HTableDescriptor[] ret = new HTableDescriptor[proto.getTableSchemaCount()];
342 for (int i = 0; i < proto.getTableSchemaCount(); ++i) {
343 ret[i] = HTableDescriptor.convert(proto.getTableSchema(i));
344 }
345 return ret;
346 }
347
348
349
350
351
352
353
354 public static byte [][] getSplitKeysArray(final CreateTableRequest proto) {
355 byte [][] splitKeys = new byte[proto.getSplitKeysCount()][];
356 for (int i = 0; i < proto.getSplitKeysCount(); ++i) {
357 splitKeys[i] = proto.getSplitKeys(i).toByteArray();
358 }
359 return splitKeys;
360 }
361
362
363
364
365 public static Durability toDurability(
366 final ClientProtos.MutationProto.Durability proto) {
367 switch(proto) {
368 case USE_DEFAULT:
369 return Durability.USE_DEFAULT;
370 case SKIP_WAL:
371 return Durability.SKIP_WAL;
372 case ASYNC_WAL:
373 return Durability.ASYNC_WAL;
374 case SYNC_WAL:
375 return Durability.SYNC_WAL;
376 case FSYNC_WAL:
377 return Durability.FSYNC_WAL;
378 default:
379 return Durability.USE_DEFAULT;
380 }
381 }
382
383
384
385
386 public static ClientProtos.MutationProto.Durability toDurability(
387 final Durability d) {
388 switch(d) {
389 case USE_DEFAULT:
390 return ClientProtos.MutationProto.Durability.USE_DEFAULT;
391 case SKIP_WAL:
392 return ClientProtos.MutationProto.Durability.SKIP_WAL;
393 case ASYNC_WAL:
394 return ClientProtos.MutationProto.Durability.ASYNC_WAL;
395 case SYNC_WAL:
396 return ClientProtos.MutationProto.Durability.SYNC_WAL;
397 case FSYNC_WAL:
398 return ClientProtos.MutationProto.Durability.FSYNC_WAL;
399 default:
400 return ClientProtos.MutationProto.Durability.USE_DEFAULT;
401 }
402 }
403
404
405
406
407
408
409
410
411 public static Get toGet(
412 final ClientProtos.Get proto) throws IOException {
413 if (proto == null) return null;
414 byte[] row = proto.getRow().toByteArray();
415 Get get = new Get(row);
416 if (proto.hasCacheBlocks()) {
417 get.setCacheBlocks(proto.getCacheBlocks());
418 }
419 if (proto.hasMaxVersions()) {
420 get.setMaxVersions(proto.getMaxVersions());
421 }
422 if (proto.hasStoreLimit()) {
423 get.setMaxResultsPerColumnFamily(proto.getStoreLimit());
424 }
425 if (proto.hasStoreOffset()) {
426 get.setRowOffsetPerColumnFamily(proto.getStoreOffset());
427 }
428 if (proto.hasTimeRange()) {
429 HBaseProtos.TimeRange timeRange = proto.getTimeRange();
430 long minStamp = 0;
431 long maxStamp = Long.MAX_VALUE;
432 if (timeRange.hasFrom()) {
433 minStamp = timeRange.getFrom();
434 }
435 if (timeRange.hasTo()) {
436 maxStamp = timeRange.getTo();
437 }
438 get.setTimeRange(minStamp, maxStamp);
439 }
440 if (proto.hasFilter()) {
441 FilterProtos.Filter filter = proto.getFilter();
442 get.setFilter(ProtobufUtil.toFilter(filter));
443 }
444 for (NameBytesPair attribute: proto.getAttributeList()) {
445 get.setAttribute(attribute.getName(), attribute.getValue().toByteArray());
446 }
447 if (proto.getColumnCount() > 0) {
448 for (Column column: proto.getColumnList()) {
449 byte[] family = column.getFamily().toByteArray();
450 if (column.getQualifierCount() > 0) {
451 for (ByteString qualifier: column.getQualifierList()) {
452 get.addColumn(family, qualifier.toByteArray());
453 }
454 } else {
455 get.addFamily(family);
456 }
457 }
458 }
459 if (proto.hasExistenceOnly() && proto.getExistenceOnly()){
460 get.setCheckExistenceOnly(true);
461 }
462 if (proto.hasClosestRowBefore() && proto.getClosestRowBefore()){
463 get.setClosestRowBefore(true);
464 }
465 return get;
466 }
467
468
469
470
471
472
473
474
475 public static Put toPut(final MutationProto proto)
476 throws IOException {
477 return toPut(proto, null);
478 }
479
480
481
482
483
484
485
486
487
488 public static Put toPut(final MutationProto proto, final CellScanner cellScanner)
489 throws IOException {
490
491 MutationType type = proto.getMutateType();
492 assert type == MutationType.PUT: type.name();
493 long timestamp = proto.hasTimestamp()? proto.getTimestamp(): HConstants.LATEST_TIMESTAMP;
494 Put put = null;
495 int cellCount = proto.hasAssociatedCellCount()? proto.getAssociatedCellCount(): 0;
496 if (cellCount > 0) {
497
498 if (cellScanner == null) {
499 throw new DoNotRetryIOException("Cell count of " + cellCount + " but no cellScanner: " +
500 toShortString(proto));
501 }
502 for (int i = 0; i < cellCount; i++) {
503 if (!cellScanner.advance()) {
504 throw new DoNotRetryIOException("Cell count of " + cellCount + " but at index " + i +
505 " no cell returned: " + toShortString(proto));
506 }
507 Cell cell = cellScanner.current();
508 if (put == null) {
509 put = new Put(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength(), timestamp);
510 }
511 put.add(cell);
512 }
513 } else {
514 if (proto.hasRow()) {
515 put = new Put(proto.getRow().asReadOnlyByteBuffer(), timestamp);
516 } else {
517 throw new IllegalArgumentException("row cannot be null");
518 }
519
520 for (ColumnValue column: proto.getColumnValueList()) {
521 byte[] family = column.getFamily().toByteArray();
522 for (QualifierValue qv: column.getQualifierValueList()) {
523 if (!qv.hasValue()) {
524 throw new DoNotRetryIOException(
525 "Missing required field: qualifier value");
526 }
527 ByteBuffer qualifier =
528 qv.hasQualifier() ? qv.getQualifier().asReadOnlyByteBuffer() : null;
529 ByteBuffer value =
530 qv.hasValue() ? qv.getValue().asReadOnlyByteBuffer() : null;
531 long ts = timestamp;
532 if (qv.hasTimestamp()) {
533 ts = qv.getTimestamp();
534 }
535 byte[] tags;
536 if (qv.hasTags()) {
537 tags = qv.getTags().toByteArray();
538 Object[] array = Tag.asList(tags, 0, (short)tags.length).toArray();
539 Tag[] tagArray = new Tag[array.length];
540 for(int i = 0; i< array.length; i++) {
541 tagArray[i] = (Tag)array[i];
542 }
543 put.addImmutable(family, qualifier, ts, value, tagArray);
544 } else {
545 put.addImmutable(family, qualifier, ts, value);
546 }
547 }
548 }
549 }
550 put.setDurability(toDurability(proto.getDurability()));
551 for (NameBytesPair attribute: proto.getAttributeList()) {
552 put.setAttribute(attribute.getName(), attribute.getValue().toByteArray());
553 }
554 return put;
555 }
556
557
558
559
560
561
562
563
564 public static Delete toDelete(final MutationProto proto)
565 throws IOException {
566 return toDelete(proto, null);
567 }
568
569
570
571
572
573
574
575
576
577 public static Delete toDelete(final MutationProto proto, final CellScanner cellScanner)
578 throws IOException {
579 MutationType type = proto.getMutateType();
580 assert type == MutationType.DELETE : type.name();
581 byte [] row = proto.hasRow()? proto.getRow().toByteArray(): null;
582 long timestamp = HConstants.LATEST_TIMESTAMP;
583 if (proto.hasTimestamp()) {
584 timestamp = proto.getTimestamp();
585 }
586 Delete delete = null;
587 int cellCount = proto.hasAssociatedCellCount()? proto.getAssociatedCellCount(): 0;
588 if (cellCount > 0) {
589
590 if (cellScanner == null) {
591
592 throw new DoNotRetryIOException("Cell count of " + cellCount + " but no cellScanner: " +
593 TextFormat.shortDebugString(proto));
594 }
595 for (int i = 0; i < cellCount; i++) {
596 if (!cellScanner.advance()) {
597
598 throw new DoNotRetryIOException("Cell count of " + cellCount + " but at index " + i +
599 " no cell returned: " + TextFormat.shortDebugString(proto));
600 }
601 Cell cell = cellScanner.current();
602 if (delete == null) {
603 delete =
604 new Delete(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength(), timestamp);
605 }
606 delete.addDeleteMarker(KeyValueUtil.ensureKeyValue(cell));
607 }
608 } else {
609 delete = new Delete(row, timestamp);
610 for (ColumnValue column: proto.getColumnValueList()) {
611 byte[] family = column.getFamily().toByteArray();
612 for (QualifierValue qv: column.getQualifierValueList()) {
613 DeleteType deleteType = qv.getDeleteType();
614 byte[] qualifier = null;
615 if (qv.hasQualifier()) {
616 qualifier = qv.getQualifier().toByteArray();
617 }
618 long ts = HConstants.LATEST_TIMESTAMP;
619 if (qv.hasTimestamp()) {
620 ts = qv.getTimestamp();
621 }
622 if (deleteType == DeleteType.DELETE_ONE_VERSION) {
623 delete.deleteColumn(family, qualifier, ts);
624 } else if (deleteType == DeleteType.DELETE_MULTIPLE_VERSIONS) {
625 delete.deleteColumns(family, qualifier, ts);
626 } else if (deleteType == DeleteType.DELETE_FAMILY_VERSION) {
627 delete.deleteFamilyVersion(family, ts);
628 } else {
629 delete.deleteFamily(family, ts);
630 }
631 }
632 }
633 }
634 delete.setDurability(toDurability(proto.getDurability()));
635 for (NameBytesPair attribute: proto.getAttributeList()) {
636 delete.setAttribute(attribute.getName(), attribute.getValue().toByteArray());
637 }
638 return delete;
639 }
640
641
642
643
644
645
646
647
648 public static Append toAppend(final MutationProto proto, final CellScanner cellScanner)
649 throws IOException {
650 MutationType type = proto.getMutateType();
651 assert type == MutationType.APPEND : type.name();
652 byte [] row = proto.hasRow()? proto.getRow().toByteArray(): null;
653 Append append = null;
654 int cellCount = proto.hasAssociatedCellCount()? proto.getAssociatedCellCount(): 0;
655 if (cellCount > 0) {
656
657 if (cellScanner == null) {
658 throw new DoNotRetryIOException("Cell count of " + cellCount + " but no cellScanner: " +
659 toShortString(proto));
660 }
661 for (int i = 0; i < cellCount; i++) {
662 if (!cellScanner.advance()) {
663 throw new DoNotRetryIOException("Cell count of " + cellCount + " but at index " + i +
664 " no cell returned: " + toShortString(proto));
665 }
666 Cell cell = cellScanner.current();
667 if (append == null) {
668 append = new Append(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength());
669 }
670 append.add(KeyValueUtil.ensureKeyValue(cell));
671 }
672 } else {
673 append = new Append(row);
674 for (ColumnValue column: proto.getColumnValueList()) {
675 byte[] family = column.getFamily().toByteArray();
676 for (QualifierValue qv: column.getQualifierValueList()) {
677 byte[] qualifier = qv.getQualifier().toByteArray();
678 if (!qv.hasValue()) {
679 throw new DoNotRetryIOException(
680 "Missing required field: qualifer value");
681 }
682 byte[] value = qv.getValue().toByteArray();
683 byte[] tags = null;
684 if (qv.hasTags()) {
685 tags = qv.getTags().toByteArray();
686 }
687 append.add(CellUtil.createCell(row, family, qualifier, qv.getTimestamp(),
688 KeyValue.Type.Put, value, tags));
689 }
690 }
691 }
692 append.setDurability(toDurability(proto.getDurability()));
693 for (NameBytesPair attribute: proto.getAttributeList()) {
694 append.setAttribute(attribute.getName(), attribute.getValue().toByteArray());
695 }
696 return append;
697 }
698
699
700
701
702
703
704
705
706 public static Mutation toMutation(final MutationProto proto) throws IOException {
707 MutationType type = proto.getMutateType();
708 if (type == MutationType.APPEND) {
709 return toAppend(proto, null);
710 }
711 if (type == MutationType.DELETE) {
712 return toDelete(proto, null);
713 }
714 if (type == MutationType.PUT) {
715 return toPut(proto, null);
716 }
717 throw new IOException("Unknown mutation type " + type);
718 }
719
720
721
722
723
724
725
726
727 public static Increment toIncrement(final MutationProto proto, final CellScanner cellScanner)
728 throws IOException {
729 MutationType type = proto.getMutateType();
730 assert type == MutationType.INCREMENT : type.name();
731 byte [] row = proto.hasRow()? proto.getRow().toByteArray(): null;
732 Increment increment = null;
733 int cellCount = proto.hasAssociatedCellCount()? proto.getAssociatedCellCount(): 0;
734 if (cellCount > 0) {
735
736 if (cellScanner == null) {
737 throw new DoNotRetryIOException("Cell count of " + cellCount + " but no cellScanner: " +
738 TextFormat.shortDebugString(proto));
739 }
740 for (int i = 0; i < cellCount; i++) {
741 if (!cellScanner.advance()) {
742 throw new DoNotRetryIOException("Cell count of " + cellCount + " but at index " + i +
743 " no cell returned: " + TextFormat.shortDebugString(proto));
744 }
745 Cell cell = cellScanner.current();
746 if (increment == null) {
747 increment = new Increment(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength());
748 }
749 increment.add(KeyValueUtil.ensureKeyValue(cell));
750 }
751 } else {
752 increment = new Increment(row);
753 for (ColumnValue column: proto.getColumnValueList()) {
754 byte[] family = column.getFamily().toByteArray();
755 for (QualifierValue qv: column.getQualifierValueList()) {
756 byte[] qualifier = qv.getQualifier().toByteArray();
757 if (!qv.hasValue()) {
758 throw new DoNotRetryIOException("Missing required field: qualifer value");
759 }
760 byte[] value = qv.getValue().toByteArray();
761 byte[] tags = null;
762 if (qv.hasTags()) {
763 tags = qv.getTags().toByteArray();
764 }
765 increment.add(CellUtil.createCell(row, family, qualifier, qv.getTimestamp(),
766 KeyValue.Type.Put, value, tags));
767 }
768 }
769 }
770 if (proto.hasTimeRange()) {
771 HBaseProtos.TimeRange timeRange = proto.getTimeRange();
772 long minStamp = 0;
773 long maxStamp = Long.MAX_VALUE;
774 if (timeRange.hasFrom()) {
775 minStamp = timeRange.getFrom();
776 }
777 if (timeRange.hasTo()) {
778 maxStamp = timeRange.getTo();
779 }
780 increment.setTimeRange(minStamp, maxStamp);
781 }
782 increment.setDurability(toDurability(proto.getDurability()));
783 for (NameBytesPair attribute : proto.getAttributeList()) {
784 increment.setAttribute(attribute.getName(), attribute.getValue().toByteArray());
785 }
786 return increment;
787 }
788
789
790
791
792
793
794
795
796 public static ClientProtos.Scan toScan(
797 final Scan scan) throws IOException {
798 ClientProtos.Scan.Builder scanBuilder =
799 ClientProtos.Scan.newBuilder();
800 scanBuilder.setCacheBlocks(scan.getCacheBlocks());
801 if (scan.getBatch() > 0) {
802 scanBuilder.setBatchSize(scan.getBatch());
803 }
804 if (scan.getMaxResultSize() > 0) {
805 scanBuilder.setMaxResultSize(scan.getMaxResultSize());
806 }
807 if (scan.isSmall()) {
808 scanBuilder.setSmall(scan.isSmall());
809 }
810 Boolean loadColumnFamiliesOnDemand = scan.getLoadColumnFamiliesOnDemandValue();
811 if (loadColumnFamiliesOnDemand != null) {
812 scanBuilder.setLoadColumnFamiliesOnDemand(loadColumnFamiliesOnDemand.booleanValue());
813 }
814 scanBuilder.setMaxVersions(scan.getMaxVersions());
815 TimeRange timeRange = scan.getTimeRange();
816 if (!timeRange.isAllTime()) {
817 HBaseProtos.TimeRange.Builder timeRangeBuilder =
818 HBaseProtos.TimeRange.newBuilder();
819 timeRangeBuilder.setFrom(timeRange.getMin());
820 timeRangeBuilder.setTo(timeRange.getMax());
821 scanBuilder.setTimeRange(timeRangeBuilder.build());
822 }
823 Map<String, byte[]> attributes = scan.getAttributesMap();
824 if (!attributes.isEmpty()) {
825 NameBytesPair.Builder attributeBuilder = NameBytesPair.newBuilder();
826 for (Map.Entry<String, byte[]> attribute: attributes.entrySet()) {
827 attributeBuilder.setName(attribute.getKey());
828 attributeBuilder.setValue(ByteStringer.wrap(attribute.getValue()));
829 scanBuilder.addAttribute(attributeBuilder.build());
830 }
831 }
832 byte[] startRow = scan.getStartRow();
833 if (startRow != null && startRow.length > 0) {
834 scanBuilder.setStartRow(ByteStringer.wrap(startRow));
835 }
836 byte[] stopRow = scan.getStopRow();
837 if (stopRow != null && stopRow.length > 0) {
838 scanBuilder.setStopRow(ByteStringer.wrap(stopRow));
839 }
840 if (scan.hasFilter()) {
841 scanBuilder.setFilter(ProtobufUtil.toFilter(scan.getFilter()));
842 }
843 if (scan.hasFamilies()) {
844 Column.Builder columnBuilder = Column.newBuilder();
845 for (Map.Entry<byte[],NavigableSet<byte []>>
846 family: scan.getFamilyMap().entrySet()) {
847 columnBuilder.setFamily(ByteStringer.wrap(family.getKey()));
848 NavigableSet<byte []> qualifiers = family.getValue();
849 columnBuilder.clearQualifier();
850 if (qualifiers != null && qualifiers.size() > 0) {
851 for (byte [] qualifier: qualifiers) {
852 columnBuilder.addQualifier(ByteStringer.wrap(qualifier));
853 }
854 }
855 scanBuilder.addColumn(columnBuilder.build());
856 }
857 }
858 if (scan.getMaxResultsPerColumnFamily() >= 0) {
859 scanBuilder.setStoreLimit(scan.getMaxResultsPerColumnFamily());
860 }
861 if (scan.getRowOffsetPerColumnFamily() > 0) {
862 scanBuilder.setStoreOffset(scan.getRowOffsetPerColumnFamily());
863 }
864 if (scan.isReversed()) {
865 scanBuilder.setReversed(scan.isReversed());
866 }
867 return scanBuilder.build();
868 }
869
870
871
872
873
874
875
876
877 public static Scan toScan(
878 final ClientProtos.Scan proto) throws IOException {
879 byte [] startRow = HConstants.EMPTY_START_ROW;
880 byte [] stopRow = HConstants.EMPTY_END_ROW;
881 if (proto.hasStartRow()) {
882 startRow = proto.getStartRow().toByteArray();
883 }
884 if (proto.hasStopRow()) {
885 stopRow = proto.getStopRow().toByteArray();
886 }
887 Scan scan = new Scan(startRow, stopRow);
888 if (proto.hasCacheBlocks()) {
889 scan.setCacheBlocks(proto.getCacheBlocks());
890 }
891 if (proto.hasMaxVersions()) {
892 scan.setMaxVersions(proto.getMaxVersions());
893 }
894 if (proto.hasStoreLimit()) {
895 scan.setMaxResultsPerColumnFamily(proto.getStoreLimit());
896 }
897 if (proto.hasStoreOffset()) {
898 scan.setRowOffsetPerColumnFamily(proto.getStoreOffset());
899 }
900 if (proto.hasLoadColumnFamiliesOnDemand()) {
901 scan.setLoadColumnFamiliesOnDemand(proto.getLoadColumnFamiliesOnDemand());
902 }
903 if (proto.hasTimeRange()) {
904 HBaseProtos.TimeRange timeRange = proto.getTimeRange();
905 long minStamp = 0;
906 long maxStamp = Long.MAX_VALUE;
907 if (timeRange.hasFrom()) {
908 minStamp = timeRange.getFrom();
909 }
910 if (timeRange.hasTo()) {
911 maxStamp = timeRange.getTo();
912 }
913 scan.setTimeRange(minStamp, maxStamp);
914 }
915 if (proto.hasFilter()) {
916 FilterProtos.Filter filter = proto.getFilter();
917 scan.setFilter(ProtobufUtil.toFilter(filter));
918 }
919 if (proto.hasBatchSize()) {
920 scan.setBatch(proto.getBatchSize());
921 }
922 if (proto.hasMaxResultSize()) {
923 scan.setMaxResultSize(proto.getMaxResultSize());
924 }
925 if (proto.hasSmall()) {
926 scan.setSmall(proto.getSmall());
927 }
928 for (NameBytesPair attribute: proto.getAttributeList()) {
929 scan.setAttribute(attribute.getName(), attribute.getValue().toByteArray());
930 }
931 if (proto.getColumnCount() > 0) {
932 for (Column column: proto.getColumnList()) {
933 byte[] family = column.getFamily().toByteArray();
934 if (column.getQualifierCount() > 0) {
935 for (ByteString qualifier: column.getQualifierList()) {
936 scan.addColumn(family, qualifier.toByteArray());
937 }
938 } else {
939 scan.addFamily(family);
940 }
941 }
942 }
943 if (proto.hasReversed()) {
944 scan.setReversed(proto.getReversed());
945 }
946 return scan;
947 }
948
949
950
951
952
953
954
955
956 public static ClientProtos.Get toGet(
957 final Get get) throws IOException {
958 ClientProtos.Get.Builder builder =
959 ClientProtos.Get.newBuilder();
960 builder.setRow(ByteStringer.wrap(get.getRow()));
961 builder.setCacheBlocks(get.getCacheBlocks());
962 builder.setMaxVersions(get.getMaxVersions());
963 if (get.getFilter() != null) {
964 builder.setFilter(ProtobufUtil.toFilter(get.getFilter()));
965 }
966 TimeRange timeRange = get.getTimeRange();
967 if (!timeRange.isAllTime()) {
968 HBaseProtos.TimeRange.Builder timeRangeBuilder =
969 HBaseProtos.TimeRange.newBuilder();
970 timeRangeBuilder.setFrom(timeRange.getMin());
971 timeRangeBuilder.setTo(timeRange.getMax());
972 builder.setTimeRange(timeRangeBuilder.build());
973 }
974 Map<String, byte[]> attributes = get.getAttributesMap();
975 if (!attributes.isEmpty()) {
976 NameBytesPair.Builder attributeBuilder = NameBytesPair.newBuilder();
977 for (Map.Entry<String, byte[]> attribute: attributes.entrySet()) {
978 attributeBuilder.setName(attribute.getKey());
979 attributeBuilder.setValue(ByteStringer.wrap(attribute.getValue()));
980 builder.addAttribute(attributeBuilder.build());
981 }
982 }
983 if (get.hasFamilies()) {
984 Column.Builder columnBuilder = Column.newBuilder();
985 Map<byte[], NavigableSet<byte[]>> families = get.getFamilyMap();
986 for (Map.Entry<byte[], NavigableSet<byte[]>> family: families.entrySet()) {
987 NavigableSet<byte[]> qualifiers = family.getValue();
988 columnBuilder.setFamily(ByteStringer.wrap(family.getKey()));
989 columnBuilder.clearQualifier();
990 if (qualifiers != null && qualifiers.size() > 0) {
991 for (byte[] qualifier: qualifiers) {
992 columnBuilder.addQualifier(ByteStringer.wrap(qualifier));
993 }
994 }
995 builder.addColumn(columnBuilder.build());
996 }
997 }
998 if (get.getMaxResultsPerColumnFamily() >= 0) {
999 builder.setStoreLimit(get.getMaxResultsPerColumnFamily());
1000 }
1001 if (get.getRowOffsetPerColumnFamily() > 0) {
1002 builder.setStoreOffset(get.getRowOffsetPerColumnFamily());
1003 }
1004 if (get.isCheckExistenceOnly()){
1005 builder.setExistenceOnly(true);
1006 }
1007 if (get.isClosestRowBefore()){
1008 builder.setClosestRowBefore(true);
1009 }
1010 return builder.build();
1011 }
1012
1013
1014
1015
1016
1017
1018
1019 public static MutationProto toMutation(
1020 final Increment increment, final MutationProto.Builder builder, long nonce) {
1021 builder.setRow(ByteStringer.wrap(increment.getRow()));
1022 builder.setMutateType(MutationType.INCREMENT);
1023 builder.setDurability(toDurability(increment.getDurability()));
1024 if (nonce != HConstants.NO_NONCE) {
1025 builder.setNonce(nonce);
1026 }
1027 TimeRange timeRange = increment.getTimeRange();
1028 if (!timeRange.isAllTime()) {
1029 HBaseProtos.TimeRange.Builder timeRangeBuilder =
1030 HBaseProtos.TimeRange.newBuilder();
1031 timeRangeBuilder.setFrom(timeRange.getMin());
1032 timeRangeBuilder.setTo(timeRange.getMax());
1033 builder.setTimeRange(timeRangeBuilder.build());
1034 }
1035 ColumnValue.Builder columnBuilder = ColumnValue.newBuilder();
1036 QualifierValue.Builder valueBuilder = QualifierValue.newBuilder();
1037 for (Map.Entry<byte[], List<Cell>> family: increment.getFamilyCellMap().entrySet()) {
1038 columnBuilder.setFamily(ByteStringer.wrap(family.getKey()));
1039 columnBuilder.clearQualifierValue();
1040 List<Cell> values = family.getValue();
1041 if (values != null && values.size() > 0) {
1042 for (Cell cell: values) {
1043 KeyValue kv = KeyValueUtil.ensureKeyValue(cell);
1044 valueBuilder.setQualifier(ByteStringer.wrap(
1045 kv.getQualifierArray(), kv.getQualifierOffset(), kv.getQualifierLength()));
1046 valueBuilder.setValue(ByteStringer.wrap(
1047 kv.getValueArray(), kv.getValueOffset(), kv.getValueLength()));
1048 if (kv.getTagsLengthUnsigned() > 0) {
1049 valueBuilder.setTags(ByteStringer.wrap(kv.getTagsArray(),
1050 kv.getTagsOffset(), kv.getTagsLengthUnsigned()));
1051 }
1052 columnBuilder.addQualifierValue(valueBuilder.build());
1053 }
1054 }
1055 builder.addColumnValue(columnBuilder.build());
1056 }
1057 Map<String, byte[]> attributes = increment.getAttributesMap();
1058 if (!attributes.isEmpty()) {
1059 NameBytesPair.Builder attributeBuilder = NameBytesPair.newBuilder();
1060 for (Map.Entry<String, byte[]> attribute : attributes.entrySet()) {
1061 attributeBuilder.setName(attribute.getKey());
1062 attributeBuilder.setValue(ByteStringer.wrap(attribute.getValue()));
1063 builder.addAttribute(attributeBuilder.build());
1064 }
1065 }
1066 return builder.build();
1067 }
1068
1069 public static MutationProto toMutation(final MutationType type, final Mutation mutation)
1070 throws IOException {
1071 return toMutation(type, mutation, HConstants.NO_NONCE);
1072 }
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082 public static MutationProto toMutation(final MutationType type, final Mutation mutation,
1083 final long nonce) throws IOException {
1084 return toMutation(type, mutation, MutationProto.newBuilder(), nonce);
1085 }
1086
1087 public static MutationProto toMutation(final MutationType type, final Mutation mutation,
1088 MutationProto.Builder builder) throws IOException {
1089 return toMutation(type, mutation, builder, HConstants.NO_NONCE);
1090 }
1091
1092 public static MutationProto toMutation(final MutationType type, final Mutation mutation,
1093 MutationProto.Builder builder, long nonce)
1094 throws IOException {
1095 builder = getMutationBuilderAndSetCommonFields(type, mutation, builder);
1096 if (nonce != HConstants.NO_NONCE) {
1097 builder.setNonce(nonce);
1098 }
1099 ColumnValue.Builder columnBuilder = ColumnValue.newBuilder();
1100 QualifierValue.Builder valueBuilder = QualifierValue.newBuilder();
1101 for (Map.Entry<byte[],List<Cell>> family: mutation.getFamilyCellMap().entrySet()) {
1102 columnBuilder.clear();
1103 columnBuilder.setFamily(ByteStringer.wrap(family.getKey()));
1104 for (Cell cell: family.getValue()) {
1105 KeyValue kv = KeyValueUtil.ensureKeyValue(cell);
1106 valueBuilder.setQualifier(ByteStringer.wrap(
1107 kv.getQualifierArray(), kv.getQualifierOffset(), kv.getQualifierLength()));
1108 valueBuilder.setValue(ByteStringer.wrap(
1109 kv.getValueArray(), kv.getValueOffset(), kv.getValueLength()));
1110 valueBuilder.setTimestamp(kv.getTimestamp());
1111 if(cell.getTagsLengthUnsigned() > 0) {
1112 valueBuilder.setTags(ByteStringer.wrap(kv.getTagsArray(), kv.getTagsOffset(),
1113 kv.getTagsLengthUnsigned()));
1114 }
1115 if (type == MutationType.DELETE) {
1116 KeyValue.Type keyValueType = KeyValue.Type.codeToType(kv.getType());
1117 valueBuilder.setDeleteType(toDeleteType(keyValueType));
1118 }
1119 columnBuilder.addQualifierValue(valueBuilder.build());
1120 }
1121 builder.addColumnValue(columnBuilder.build());
1122 }
1123 return builder.build();
1124 }
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135 public static MutationProto toMutationNoData(final MutationType type, final Mutation mutation,
1136 final MutationProto.Builder builder) throws IOException {
1137 return toMutationNoData(type, mutation, builder, HConstants.NO_NONCE);
1138 }
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148 public static MutationProto toMutationNoData(final MutationType type, final Mutation mutation)
1149 throws IOException {
1150 MutationProto.Builder builder = MutationProto.newBuilder();
1151 return toMutationNoData(type, mutation, builder);
1152 }
1153
1154 public static MutationProto toMutationNoData(final MutationType type, final Mutation mutation,
1155 final MutationProto.Builder builder, long nonce) throws IOException {
1156 getMutationBuilderAndSetCommonFields(type, mutation, builder);
1157 builder.setAssociatedCellCount(mutation.size());
1158 if (nonce != HConstants.NO_NONCE) {
1159 builder.setNonce(nonce);
1160 }
1161 return builder.build();
1162 }
1163
1164
1165
1166
1167
1168
1169
1170
1171 private static MutationProto.Builder getMutationBuilderAndSetCommonFields(final MutationType type,
1172 final Mutation mutation, MutationProto.Builder builder) {
1173 builder.setRow(ByteStringer.wrap(mutation.getRow()));
1174 builder.setMutateType(type);
1175 builder.setDurability(toDurability(mutation.getDurability()));
1176 builder.setTimestamp(mutation.getTimeStamp());
1177 Map<String, byte[]> attributes = mutation.getAttributesMap();
1178 if (!attributes.isEmpty()) {
1179 NameBytesPair.Builder attributeBuilder = NameBytesPair.newBuilder();
1180 for (Map.Entry<String, byte[]> attribute: attributes.entrySet()) {
1181 attributeBuilder.setName(attribute.getKey());
1182 attributeBuilder.setValue(ByteStringer.wrap(attribute.getValue()));
1183 builder.addAttribute(attributeBuilder.build());
1184 }
1185 }
1186 return builder;
1187 }
1188
1189
1190
1191
1192
1193
1194
1195 public static ClientProtos.Result toResult(final Result result) {
1196 if (result.getExists() != null) {
1197 return toResult(result.getExists());
1198 }
1199
1200 Cell[] cells = result.rawCells();
1201 if (cells == null || cells.length == 0) {
1202 return EMPTY_RESULT_PB;
1203 }
1204
1205 ClientProtos.Result.Builder builder = ClientProtos.Result.newBuilder();
1206 for (Cell c : cells) {
1207 builder.addCell(toCell(c));
1208 }
1209
1210 return builder.build();
1211 }
1212
1213
1214
1215
1216
1217
1218
1219 public static ClientProtos.Result toResult(final boolean existence) {
1220 return existence ? EMPTY_RESULT_PB_EXISTS_TRUE : EMPTY_RESULT_PB_EXISTS_FALSE;
1221 }
1222
1223
1224
1225
1226
1227
1228
1229
1230 public static ClientProtos.Result toResultNoData(final Result result) {
1231 if (result.getExists() != null) return toResult(result.getExists());
1232 int size = result.size();
1233 if (size == 0) return EMPTY_RESULT_PB;
1234 ClientProtos.Result.Builder builder = ClientProtos.Result.newBuilder();
1235 builder.setAssociatedCellCount(size);
1236 return builder.build();
1237 }
1238
1239
1240
1241
1242
1243
1244
1245 public static Result toResult(final ClientProtos.Result proto) {
1246 if (proto.hasExists()) {
1247 return proto.getExists() ? EMPTY_RESULT_EXISTS_TRUE : EMPTY_RESULT_EXISTS_FALSE;
1248 }
1249
1250 List<CellProtos.Cell> values = proto.getCellList();
1251 if (values.isEmpty()){
1252 return EMPTY_RESULT;
1253 }
1254
1255 List<Cell> cells = new ArrayList<Cell>(values.size());
1256 for (CellProtos.Cell c : values) {
1257 cells.add(toCell(c));
1258 }
1259 return Result.create(cells, null);
1260 }
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270 public static Result toResult(final ClientProtos.Result proto, final CellScanner scanner)
1271 throws IOException {
1272 List<CellProtos.Cell> values = proto.getCellList();
1273
1274 if (proto.hasExists()) {
1275 if ((values != null && !values.isEmpty()) ||
1276 (proto.hasAssociatedCellCount() && proto.getAssociatedCellCount() > 0)) {
1277 throw new IllegalArgumentException("bad proto: exists with cells is no allowed " + proto);
1278 }
1279 return proto.getExists() ? EMPTY_RESULT_EXISTS_TRUE : EMPTY_RESULT_EXISTS_FALSE;
1280 }
1281
1282
1283 List<Cell> cells = null;
1284 if (proto.hasAssociatedCellCount()) {
1285 int count = proto.getAssociatedCellCount();
1286 cells = new ArrayList<Cell>(count + values.size());
1287 for (int i = 0; i < count; i++) {
1288 if (!scanner.advance()) throw new IOException("Failed get " + i + " of " + count);
1289 cells.add(scanner.current());
1290 }
1291 }
1292
1293 if (!values.isEmpty()){
1294 if (cells == null) cells = new ArrayList<Cell>(values.size());
1295 for (CellProtos.Cell c: values) {
1296 cells.add(toCell(c));
1297 }
1298 }
1299
1300 return (cells == null || cells.isEmpty()) ? EMPTY_RESULT : Result.create(cells, null);
1301 }
1302
1303
1304
1305
1306
1307
1308
1309
1310 public static ComparatorProtos.Comparator toComparator(ByteArrayComparable comparator) {
1311 ComparatorProtos.Comparator.Builder builder = ComparatorProtos.Comparator.newBuilder();
1312 builder.setName(comparator.getClass().getName());
1313 builder.setSerializedComparator(ByteStringer.wrap(comparator.toByteArray()));
1314 return builder.build();
1315 }
1316
1317
1318
1319
1320
1321
1322
1323 @SuppressWarnings("unchecked")
1324 public static ByteArrayComparable toComparator(ComparatorProtos.Comparator proto)
1325 throws IOException {
1326 String type = proto.getName();
1327 String funcName = "parseFrom";
1328 byte [] value = proto.getSerializedComparator().toByteArray();
1329 try {
1330 Class<? extends ByteArrayComparable> c =
1331 (Class<? extends ByteArrayComparable>)Class.forName(type, true, CLASS_LOADER);
1332 Method parseFrom = c.getMethod(funcName, byte[].class);
1333 if (parseFrom == null) {
1334 throw new IOException("Unable to locate function: " + funcName + " in type: " + type);
1335 }
1336 return (ByteArrayComparable)parseFrom.invoke(null, value);
1337 } catch (Exception e) {
1338 throw new IOException(e);
1339 }
1340 }
1341
1342
1343
1344
1345
1346
1347
1348 @SuppressWarnings("unchecked")
1349 public static Filter toFilter(FilterProtos.Filter proto) throws IOException {
1350 String type = proto.getName();
1351 final byte [] value = proto.getSerializedFilter().toByteArray();
1352 String funcName = "parseFrom";
1353 try {
1354 Class<? extends Filter> c =
1355 (Class<? extends Filter>)Class.forName(type, true, CLASS_LOADER);
1356 Method parseFrom = c.getMethod(funcName, byte[].class);
1357 if (parseFrom == null) {
1358 throw new IOException("Unable to locate function: " + funcName + " in type: " + type);
1359 }
1360 return (Filter)parseFrom.invoke(c, value);
1361 } catch (Exception e) {
1362 throw new IOException(e);
1363 }
1364 }
1365
1366
1367
1368
1369
1370
1371
1372 public static FilterProtos.Filter toFilter(Filter filter) throws IOException {
1373 FilterProtos.Filter.Builder builder = FilterProtos.Filter.newBuilder();
1374 builder.setName(filter.getClass().getName());
1375 builder.setSerializedFilter(ByteStringer.wrap(filter.toByteArray()));
1376 return builder.build();
1377 }
1378
1379
1380
1381
1382
1383
1384
1385
1386 public static DeleteType toDeleteType(
1387 KeyValue.Type type) throws IOException {
1388 switch (type) {
1389 case Delete:
1390 return DeleteType.DELETE_ONE_VERSION;
1391 case DeleteColumn:
1392 return DeleteType.DELETE_MULTIPLE_VERSIONS;
1393 case DeleteFamily:
1394 return DeleteType.DELETE_FAMILY;
1395 case DeleteFamilyVersion:
1396 return DeleteType.DELETE_FAMILY_VERSION;
1397 default:
1398 throw new IOException("Unknown delete type: " + type);
1399 }
1400 }
1401
1402
1403
1404
1405
1406
1407
1408
1409 @SuppressWarnings("unchecked")
1410 public static Throwable toException(final NameBytesPair parameter) throws IOException {
1411 if (parameter == null || !parameter.hasValue()) return null;
1412 String desc = parameter.getValue().toStringUtf8();
1413 String type = parameter.getName();
1414 try {
1415 Class<? extends Throwable> c =
1416 (Class<? extends Throwable>)Class.forName(type, true, CLASS_LOADER);
1417 Constructor<? extends Throwable> cn = null;
1418 try {
1419 cn = c.getDeclaredConstructor(String.class);
1420 return cn.newInstance(desc);
1421 } catch (NoSuchMethodException e) {
1422
1423 cn = c.getDeclaredConstructor(String.class, String.class);
1424 return cn.newInstance(type, desc);
1425 }
1426 } catch (Exception e) {
1427 throw new IOException(e);
1428 }
1429 }
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442 public static Result get(final ClientService.BlockingInterface client,
1443 final byte[] regionName, final Get get) throws IOException {
1444 return get(client, regionName, get, null);
1445 }
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457 public static Result get(final ClientService.BlockingInterface client, final byte[] regionName,
1458 final Get get, PayloadCarryingRpcController controller) throws IOException {
1459 GetRequest request =
1460 RequestConverter.buildGetRequest(regionName, get);
1461 try {
1462 GetResponse response = client.get(controller, request);
1463 if (response == null) return null;
1464 return toResult(response.getResult());
1465 } catch (ServiceException se) {
1466 throw getRemoteException(se);
1467 }
1468 }
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480 public static Result getRowOrBefore(final ClientService.BlockingInterface client,
1481 final byte[] regionName, final byte[] row, final byte[] family) throws IOException {
1482 return getRowOrBefore(client, regionName, row, family, null);
1483 }
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495 public static Result getRowOrBefore(final ClientService.BlockingInterface client,
1496 final byte[] regionName, final byte[] row, final byte[] family,
1497 PayloadCarryingRpcController payloadCarryingRpcController) throws IOException {
1498 GetRequest request =
1499 RequestConverter.buildGetRowOrBeforeRequest(
1500 regionName, row, family);
1501 try {
1502 GetResponse response = client.get(payloadCarryingRpcController, request);
1503 if (!response.hasResult()) return null;
1504 return toResult(response.getResult());
1505 } catch (ServiceException se) {
1506 throw getRemoteException(se);
1507 }
1508 }
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520 public static boolean bulkLoadHFile(final ClientService.BlockingInterface client,
1521 final List<Pair<byte[], String>> familyPaths,
1522 final byte[] regionName, boolean assignSeqNum) throws IOException {
1523 return bulkLoadHFile(client, familyPaths, regionName, assignSeqNum, null);
1524 }
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537 public static boolean bulkLoadHFile(final ClientService.BlockingInterface client,
1538 final List<Pair<byte[], String>> familyPaths, final byte[] regionName, boolean assignSeqNum,
1539 PayloadCarryingRpcController controller) throws IOException {
1540 BulkLoadHFileRequest request =
1541 RequestConverter.buildBulkLoadHFileRequest(familyPaths, regionName, assignSeqNum);
1542 try {
1543 BulkLoadHFileResponse response =
1544 client.bulkLoadHFile(controller, request);
1545 return response.getLoaded();
1546 } catch (ServiceException se) {
1547 throw getRemoteException(se);
1548 }
1549 }
1550
1551 public static CoprocessorServiceResponse execService(final ClientService.BlockingInterface client,
1552 final CoprocessorServiceCall call, final byte[] regionName) throws IOException {
1553 return execService(client, call, regionName, null);
1554 }
1555
1556 public static CoprocessorServiceResponse execService(
1557 final ClientService.BlockingInterface client, final CoprocessorServiceCall call,
1558 final byte[] regionName, PayloadCarryingRpcController controller) throws IOException {
1559 CoprocessorServiceRequest request = CoprocessorServiceRequest.newBuilder()
1560 .setCall(call).setRegion(
1561 RequestConverter.buildRegionSpecifier(REGION_NAME, regionName)).build();
1562 try {
1563 CoprocessorServiceResponse response =
1564 client.execService(controller, request);
1565 return response;
1566 } catch (ServiceException se) {
1567 throw getRemoteException(se);
1568 }
1569 }
1570
1571 public static CoprocessorServiceResponse execService(
1572 final MasterService.BlockingInterface client, final CoprocessorServiceCall call)
1573 throws IOException {
1574 CoprocessorServiceRequest request = CoprocessorServiceRequest.newBuilder()
1575 .setCall(call).setRegion(
1576 RequestConverter.buildRegionSpecifier(REGION_NAME, HConstants.EMPTY_BYTE_ARRAY)).build();
1577 try {
1578 CoprocessorServiceResponse response =
1579 client.execMasterService(null, request);
1580 return response;
1581 } catch (ServiceException se) {
1582 throw getRemoteException(se);
1583 }
1584 }
1585
1586 @SuppressWarnings("unchecked")
1587 public static <T extends Service> T newServiceStub(Class<T> service, RpcChannel channel)
1588 throws Exception {
1589 return (T)Methods.call(service, null, "newStub",
1590 new Class[]{ RpcChannel.class }, new Object[]{ channel });
1591 }
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605 public static HRegionInfo getRegionInfo(final AdminService.BlockingInterface admin,
1606 final byte[] regionName) throws IOException {
1607 try {
1608 GetRegionInfoRequest request =
1609 RequestConverter.buildGetRegionInfoRequest(regionName);
1610 GetRegionInfoResponse response =
1611 admin.getRegionInfo(null, request);
1612 return HRegionInfo.convert(response.getRegionInfo());
1613 } catch (ServiceException se) {
1614 throw getRemoteException(se);
1615 }
1616 }
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627 public static void closeRegion(final AdminService.BlockingInterface admin,
1628 final ServerName server, final byte[] regionName, final boolean transitionInZK) throws IOException {
1629 CloseRegionRequest closeRegionRequest =
1630 RequestConverter.buildCloseRegionRequest(server, regionName, transitionInZK);
1631 try {
1632 admin.closeRegion(null, closeRegionRequest);
1633 } catch (ServiceException se) {
1634 throw getRemoteException(se);
1635 }
1636 }
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648 public static boolean closeRegion(final AdminService.BlockingInterface admin,
1649 final ServerName server,
1650 final byte[] regionName,
1651 final int versionOfClosingNode, final ServerName destinationServer,
1652 final boolean transitionInZK) throws IOException {
1653 CloseRegionRequest closeRegionRequest =
1654 RequestConverter.buildCloseRegionRequest(server,
1655 regionName, versionOfClosingNode, destinationServer, transitionInZK);
1656 try {
1657 CloseRegionResponse response = admin.closeRegion(null, closeRegionRequest);
1658 return ResponseConverter.isClosed(response);
1659 } catch (ServiceException se) {
1660 throw getRemoteException(se);
1661 }
1662 }
1663
1664
1665
1666
1667
1668
1669
1670
1671 public static void openRegion(final AdminService.BlockingInterface admin,
1672 ServerName server, final HRegionInfo region) throws IOException {
1673 OpenRegionRequest request =
1674 RequestConverter.buildOpenRegionRequest(server, region, -1, null, null);
1675 try {
1676 admin.openRegion(null, request);
1677 } catch (ServiceException se) {
1678 throw ProtobufUtil.getRemoteException(se);
1679 }
1680 }
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690 public static List<HRegionInfo> getOnlineRegions(final AdminService.BlockingInterface admin)
1691 throws IOException {
1692 GetOnlineRegionRequest request = RequestConverter.buildGetOnlineRegionRequest();
1693 GetOnlineRegionResponse response = null;
1694 try {
1695 response = admin.getOnlineRegion(null, request);
1696 } catch (ServiceException se) {
1697 throw getRemoteException(se);
1698 }
1699 return getRegionInfos(response);
1700 }
1701
1702
1703
1704
1705
1706
1707
1708 static List<HRegionInfo> getRegionInfos(final GetOnlineRegionResponse proto) {
1709 if (proto == null) return null;
1710 List<HRegionInfo> regionInfos = new ArrayList<HRegionInfo>();
1711 for (RegionInfo regionInfo: proto.getRegionInfoList()) {
1712 regionInfos.add(HRegionInfo.convert(regionInfo));
1713 }
1714 return regionInfos;
1715 }
1716
1717
1718
1719
1720
1721
1722
1723
1724 public static ServerInfo getServerInfo(final AdminService.BlockingInterface admin)
1725 throws IOException {
1726 GetServerInfoRequest request = RequestConverter.buildGetServerInfoRequest();
1727 try {
1728 GetServerInfoResponse response = admin.getServerInfo(null, request);
1729 return response.getServerInfo();
1730 } catch (ServiceException se) {
1731 throw getRemoteException(se);
1732 }
1733 }
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745 public static List<String> getStoreFiles(final AdminService.BlockingInterface admin,
1746 final byte[] regionName, final byte[] family)
1747 throws IOException {
1748 GetStoreFileRequest request =
1749 RequestConverter.buildGetStoreFileRequest(regionName, family);
1750 try {
1751 GetStoreFileResponse response = admin.getStoreFile(null, request);
1752 return response.getStoreFileList();
1753 } catch (ServiceException se) {
1754 throw ProtobufUtil.getRemoteException(se);
1755 }
1756 }
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766 public static void split(final AdminService.BlockingInterface admin,
1767 final HRegionInfo hri, byte[] splitPoint) throws IOException {
1768 SplitRegionRequest request =
1769 RequestConverter.buildSplitRegionRequest(hri.getRegionName(), splitPoint);
1770 try {
1771 admin.splitRegion(null, request);
1772 } catch (ServiceException se) {
1773 throw ProtobufUtil.getRemoteException(se);
1774 }
1775 }
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787 public static void mergeRegions(final AdminService.BlockingInterface admin,
1788 final HRegionInfo region_a, final HRegionInfo region_b,
1789 final boolean forcible) throws IOException {
1790 MergeRegionsRequest request = RequestConverter.buildMergeRegionsRequest(
1791 region_a.getRegionName(), region_b.getRegionName(),forcible);
1792 try {
1793 admin.mergeRegions(null, request);
1794 } catch (ServiceException se) {
1795 throw ProtobufUtil.getRemoteException(se);
1796 }
1797 }
1798
1799
1800
1801
1802
1803
1804
1805
1806 public static long getTotalRequestsCount(RegionLoad rl) {
1807 if (rl == null) {
1808 return 0;
1809 }
1810
1811 return rl.getReadRequestsCount() + rl.getWriteRequestsCount();
1812 }
1813
1814
1815
1816
1817
1818 public static byte [] toDelimitedByteArray(final Message m) throws IOException {
1819
1820 ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
1821 baos.write(PB_MAGIC);
1822 m.writeDelimitedTo(baos);
1823 return baos.toByteArray();
1824 }
1825
1826
1827
1828
1829
1830
1831
1832 public static Permission toPermission(AccessControlProtos.Permission proto) {
1833 if (proto.getType() != AccessControlProtos.Permission.Type.Global) {
1834 return toTablePermission(proto);
1835 } else {
1836 List<Permission.Action> actions = toPermissionActions(proto.getGlobalPermission().getActionList());
1837 return new Permission(actions.toArray(new Permission.Action[actions.size()]));
1838 }
1839 }
1840
1841
1842
1843
1844
1845
1846
1847 public static TablePermission toTablePermission(AccessControlProtos.Permission proto) {
1848 if(proto.getType() == AccessControlProtos.Permission.Type.Global) {
1849 AccessControlProtos.GlobalPermission perm = proto.getGlobalPermission();
1850 List<Permission.Action> actions = toPermissionActions(perm.getActionList());
1851
1852 return new TablePermission(null, null, null,
1853 actions.toArray(new Permission.Action[actions.size()]));
1854 }
1855 if(proto.getType() == AccessControlProtos.Permission.Type.Namespace) {
1856 AccessControlProtos.NamespacePermission perm = proto.getNamespacePermission();
1857 List<Permission.Action> actions = toPermissionActions(perm.getActionList());
1858
1859 if(!proto.hasNamespacePermission()) {
1860 throw new IllegalStateException("Namespace must not be empty in NamespacePermission");
1861 }
1862 String namespace = perm.getNamespaceName().toStringUtf8();
1863 return new TablePermission(namespace, actions.toArray(new Permission.Action[actions.size()]));
1864 }
1865 if(proto.getType() == AccessControlProtos.Permission.Type.Table) {
1866 AccessControlProtos.TablePermission perm = proto.getTablePermission();
1867 List<Permission.Action> actions = toPermissionActions(perm.getActionList());
1868
1869 byte[] qualifier = null;
1870 byte[] family = null;
1871 TableName table = null;
1872
1873 if (!perm.hasTableName()) {
1874 throw new IllegalStateException("TableName cannot be empty");
1875 }
1876 table = ProtobufUtil.toTableName(perm.getTableName());
1877
1878 if (perm.hasFamily()) family = perm.getFamily().toByteArray();
1879 if (perm.hasQualifier()) qualifier = perm.getQualifier().toByteArray();
1880
1881 return new TablePermission(table, family, qualifier,
1882 actions.toArray(new Permission.Action[actions.size()]));
1883 }
1884 throw new IllegalStateException("Unrecognize Perm Type: "+proto.getType());
1885 }
1886
1887
1888
1889
1890
1891
1892
1893 public static AccessControlProtos.Permission toPermission(Permission perm) {
1894 AccessControlProtos.Permission.Builder ret = AccessControlProtos.Permission.newBuilder();
1895 if (perm instanceof TablePermission) {
1896 TablePermission tablePerm = (TablePermission)perm;
1897 if(tablePerm.hasNamespace()) {
1898 ret.setType(AccessControlProtos.Permission.Type.Namespace);
1899
1900 AccessControlProtos.NamespacePermission.Builder builder =
1901 AccessControlProtos.NamespacePermission.newBuilder();
1902 builder.setNamespaceName(ByteString.copyFromUtf8(tablePerm.getNamespace()));
1903 Permission.Action actions[] = perm.getActions();
1904 if (actions != null) {
1905 for (Permission.Action a : actions) {
1906 builder.addAction(toPermissionAction(a));
1907 }
1908 }
1909 ret.setNamespacePermission(builder);
1910 return ret.build();
1911 } else if (tablePerm.hasTable()) {
1912 ret.setType(AccessControlProtos.Permission.Type.Table);
1913
1914 AccessControlProtos.TablePermission.Builder builder =
1915 AccessControlProtos.TablePermission.newBuilder();
1916 builder.setTableName(ProtobufUtil.toProtoTableName(tablePerm.getTableName()));
1917 if (tablePerm.hasFamily()) {
1918 builder.setFamily(ByteStringer.wrap(tablePerm.getFamily()));
1919 }
1920 if (tablePerm.hasQualifier()) {
1921 builder.setQualifier(ByteStringer.wrap(tablePerm.getQualifier()));
1922 }
1923 Permission.Action actions[] = perm.getActions();
1924 if (actions != null) {
1925 for (Permission.Action a : actions) {
1926 builder.addAction(toPermissionAction(a));
1927 }
1928 }
1929 ret.setTablePermission(builder);
1930 return ret.build();
1931 }
1932 }
1933
1934 ret.setType(AccessControlProtos.Permission.Type.Global);
1935
1936 AccessControlProtos.GlobalPermission.Builder builder =
1937 AccessControlProtos.GlobalPermission.newBuilder();
1938 Permission.Action actions[] = perm.getActions();
1939 if (actions != null) {
1940 for (Permission.Action a: actions) {
1941 builder.addAction(toPermissionAction(a));
1942 }
1943 }
1944 ret.setGlobalPermission(builder);
1945 return ret.build();
1946 }
1947
1948
1949
1950
1951
1952
1953
1954 public static List<Permission.Action> toPermissionActions(
1955 List<AccessControlProtos.Permission.Action> protoActions) {
1956 List<Permission.Action> actions = new ArrayList<Permission.Action>(protoActions.size());
1957 for (AccessControlProtos.Permission.Action a : protoActions) {
1958 actions.add(toPermissionAction(a));
1959 }
1960 return actions;
1961 }
1962
1963
1964
1965
1966
1967
1968
1969 public static Permission.Action toPermissionAction(
1970 AccessControlProtos.Permission.Action action) {
1971 switch (action) {
1972 case READ:
1973 return Permission.Action.READ;
1974 case WRITE:
1975 return Permission.Action.WRITE;
1976 case EXEC:
1977 return Permission.Action.EXEC;
1978 case CREATE:
1979 return Permission.Action.CREATE;
1980 case ADMIN:
1981 return Permission.Action.ADMIN;
1982 }
1983 throw new IllegalArgumentException("Unknown action value "+action.name());
1984 }
1985
1986
1987
1988
1989
1990
1991
1992 public static AccessControlProtos.Permission.Action toPermissionAction(
1993 Permission.Action action) {
1994 switch (action) {
1995 case READ:
1996 return AccessControlProtos.Permission.Action.READ;
1997 case WRITE:
1998 return AccessControlProtos.Permission.Action.WRITE;
1999 case EXEC:
2000 return AccessControlProtos.Permission.Action.EXEC;
2001 case CREATE:
2002 return AccessControlProtos.Permission.Action.CREATE;
2003 case ADMIN:
2004 return AccessControlProtos.Permission.Action.ADMIN;
2005 }
2006 throw new IllegalArgumentException("Unknown action value "+action.name());
2007 }
2008
2009
2010
2011
2012
2013
2014
2015 public static AccessControlProtos.UserPermission toUserPermission(UserPermission perm) {
2016 return AccessControlProtos.UserPermission.newBuilder()
2017 .setUser(ByteStringer.wrap(perm.getUser()))
2018 .setPermission(toPermission(perm))
2019 .build();
2020 }
2021
2022
2023
2024
2025
2026
2027
2028 public static UserPermission toUserPermission(AccessControlProtos.UserPermission proto) {
2029 return new UserPermission(proto.getUser().toByteArray(),
2030 toTablePermission(proto.getPermission()));
2031 }
2032
2033
2034
2035
2036
2037
2038
2039
2040 public static AccessControlProtos.UsersAndPermissions toUserTablePermissions(
2041 ListMultimap<String, TablePermission> perm) {
2042 AccessControlProtos.UsersAndPermissions.Builder builder =
2043 AccessControlProtos.UsersAndPermissions.newBuilder();
2044 for (Map.Entry<String, Collection<TablePermission>> entry : perm.asMap().entrySet()) {
2045 AccessControlProtos.UsersAndPermissions.UserPermissions.Builder userPermBuilder =
2046 AccessControlProtos.UsersAndPermissions.UserPermissions.newBuilder();
2047 userPermBuilder.setUser(ByteString.copyFromUtf8(entry.getKey()));
2048 for (TablePermission tablePerm: entry.getValue()) {
2049 userPermBuilder.addPermissions(toPermission(tablePerm));
2050 }
2051 builder.addUserPermissions(userPermBuilder.build());
2052 }
2053 return builder.build();
2054 }
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066 public static void grant(AccessControlService.BlockingInterface protocol,
2067 String userShortName, Permission.Action... actions) throws ServiceException {
2068 List<AccessControlProtos.Permission.Action> permActions =
2069 Lists.newArrayListWithCapacity(actions.length);
2070 for (Permission.Action a : actions) {
2071 permActions.add(ProtobufUtil.toPermissionAction(a));
2072 }
2073 AccessControlProtos.GrantRequest request = RequestConverter.
2074 buildGrantRequest(userShortName, permActions.toArray(
2075 new AccessControlProtos.Permission.Action[actions.length]));
2076 protocol.grant(null, request);
2077 }
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093 public static void grant(AccessControlService.BlockingInterface protocol,
2094 String userShortName, TableName tableName, byte[] f, byte[] q,
2095 Permission.Action... actions) throws ServiceException {
2096 List<AccessControlProtos.Permission.Action> permActions =
2097 Lists.newArrayListWithCapacity(actions.length);
2098 for (Permission.Action a : actions) {
2099 permActions.add(ProtobufUtil.toPermissionAction(a));
2100 }
2101 AccessControlProtos.GrantRequest request = RequestConverter.
2102 buildGrantRequest(userShortName, tableName, f, q, permActions.toArray(
2103 new AccessControlProtos.Permission.Action[actions.length]));
2104 protocol.grant(null, request);
2105 }
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117 public static void grant(AccessControlService.BlockingInterface protocol,
2118 String userShortName, String namespace,
2119 Permission.Action... actions) throws ServiceException {
2120 List<AccessControlProtos.Permission.Action> permActions =
2121 Lists.newArrayListWithCapacity(actions.length);
2122 for (Permission.Action a : actions) {
2123 permActions.add(ProtobufUtil.toPermissionAction(a));
2124 }
2125 AccessControlProtos.GrantRequest request = RequestConverter.
2126 buildGrantRequest(userShortName, namespace, permActions.toArray(
2127 new AccessControlProtos.Permission.Action[actions.length]));
2128 protocol.grant(null, request);
2129 }
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141 public static void revoke(AccessControlService.BlockingInterface protocol,
2142 String userShortName, Permission.Action... actions) throws ServiceException {
2143 List<AccessControlProtos.Permission.Action> permActions =
2144 Lists.newArrayListWithCapacity(actions.length);
2145 for (Permission.Action a : actions) {
2146 permActions.add(ProtobufUtil.toPermissionAction(a));
2147 }
2148 AccessControlProtos.RevokeRequest request = RequestConverter.
2149 buildRevokeRequest(userShortName, permActions.toArray(
2150 new AccessControlProtos.Permission.Action[actions.length]));
2151 protocol.revoke(null, request);
2152 }
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168 public static void revoke(AccessControlService.BlockingInterface protocol,
2169 String userShortName, TableName tableName, byte[] f, byte[] q,
2170 Permission.Action... actions) throws ServiceException {
2171 List<AccessControlProtos.Permission.Action> permActions =
2172 Lists.newArrayListWithCapacity(actions.length);
2173 for (Permission.Action a : actions) {
2174 permActions.add(ProtobufUtil.toPermissionAction(a));
2175 }
2176 AccessControlProtos.RevokeRequest request = RequestConverter.
2177 buildRevokeRequest(userShortName, tableName, f, q, permActions.toArray(
2178 new AccessControlProtos.Permission.Action[actions.length]));
2179 protocol.revoke(null, request);
2180 }
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193 public static void revoke(AccessControlService.BlockingInterface protocol,
2194 String userShortName, String namespace,
2195 Permission.Action... actions) throws ServiceException {
2196 List<AccessControlProtos.Permission.Action> permActions =
2197 Lists.newArrayListWithCapacity(actions.length);
2198 for (Permission.Action a : actions) {
2199 permActions.add(ProtobufUtil.toPermissionAction(a));
2200 }
2201 AccessControlProtos.RevokeRequest request = RequestConverter.
2202 buildRevokeRequest(userShortName, namespace, permActions.toArray(
2203 new AccessControlProtos.Permission.Action[actions.length]));
2204 protocol.revoke(null, request);
2205 }
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215 public static List<UserPermission> getUserPermissions(
2216 AccessControlService.BlockingInterface protocol) throws ServiceException {
2217 AccessControlProtos.GetUserPermissionsRequest.Builder builder =
2218 AccessControlProtos.GetUserPermissionsRequest.newBuilder();
2219 builder.setType(AccessControlProtos.Permission.Type.Global);
2220 AccessControlProtos.GetUserPermissionsRequest request = builder.build();
2221 AccessControlProtos.GetUserPermissionsResponse response =
2222 protocol.getUserPermissions(null, request);
2223 List<UserPermission> perms = new ArrayList<UserPermission>();
2224 for (AccessControlProtos.UserPermission perm: response.getUserPermissionList()) {
2225 perms.add(ProtobufUtil.toUserPermission(perm));
2226 }
2227 return perms;
2228 }
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239 public static List<UserPermission> getUserPermissions(
2240 AccessControlService.BlockingInterface protocol,
2241 TableName t) throws ServiceException {
2242 AccessControlProtos.GetUserPermissionsRequest.Builder builder =
2243 AccessControlProtos.GetUserPermissionsRequest.newBuilder();
2244 if (t != null) {
2245 builder.setTableName(ProtobufUtil.toProtoTableName(t));
2246 }
2247 builder.setType(AccessControlProtos.Permission.Type.Table);
2248 AccessControlProtos.GetUserPermissionsRequest request = builder.build();
2249 AccessControlProtos.GetUserPermissionsResponse response =
2250 protocol.getUserPermissions(null, request);
2251 List<UserPermission> perms = new ArrayList<UserPermission>();
2252 for (AccessControlProtos.UserPermission perm: response.getUserPermissionList()) {
2253 perms.add(ProtobufUtil.toUserPermission(perm));
2254 }
2255 return perms;
2256 }
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267 public static List<UserPermission> getUserPermissions(
2268 AccessControlService.BlockingInterface protocol,
2269 byte[] namespace) throws ServiceException {
2270 AccessControlProtos.GetUserPermissionsRequest.Builder builder =
2271 AccessControlProtos.GetUserPermissionsRequest.newBuilder();
2272 if (namespace != null) {
2273 builder.setNamespaceName(ByteStringer.wrap(namespace));
2274 }
2275 builder.setType(AccessControlProtos.Permission.Type.Namespace);
2276 AccessControlProtos.GetUserPermissionsRequest request = builder.build();
2277 AccessControlProtos.GetUserPermissionsResponse response =
2278 protocol.getUserPermissions(null, request);
2279 List<UserPermission> perms = new ArrayList<UserPermission>();
2280 for (AccessControlProtos.UserPermission perm: response.getUserPermissionList()) {
2281 perms.add(ProtobufUtil.toUserPermission(perm));
2282 }
2283 return perms;
2284 }
2285
2286
2287
2288
2289
2290
2291
2292
2293 public static ListMultimap<String, TablePermission> toUserTablePermissions(
2294 AccessControlProtos.UsersAndPermissions proto) {
2295 ListMultimap<String, TablePermission> perms = ArrayListMultimap.create();
2296 AccessControlProtos.UsersAndPermissions.UserPermissions userPerm;
2297
2298 for (int i = 0; i < proto.getUserPermissionsCount(); i++) {
2299 userPerm = proto.getUserPermissions(i);
2300 for (int j = 0; j < userPerm.getPermissionsCount(); j++) {
2301 TablePermission tablePerm = toTablePermission(userPerm.getPermissions(j));
2302 perms.put(userPerm.getUser().toStringUtf8(), tablePerm);
2303 }
2304 }
2305
2306 return perms;
2307 }
2308
2309
2310
2311
2312
2313
2314
2315 public static AuthenticationProtos.Token toToken(Token<AuthenticationTokenIdentifier> token) {
2316 AuthenticationProtos.Token.Builder builder = AuthenticationProtos.Token.newBuilder();
2317 builder.setIdentifier(ByteStringer.wrap(token.getIdentifier()));
2318 builder.setPassword(ByteStringer.wrap(token.getPassword()));
2319 if (token.getService() != null) {
2320 builder.setService(ByteString.copyFromUtf8(token.getService().toString()));
2321 }
2322 return builder.build();
2323 }
2324
2325
2326
2327
2328
2329
2330
2331 public static Token<AuthenticationTokenIdentifier> toToken(AuthenticationProtos.Token proto) {
2332 return new Token<AuthenticationTokenIdentifier>(
2333 proto.hasIdentifier() ? proto.getIdentifier().toByteArray() : null,
2334 proto.hasPassword() ? proto.getPassword().toByteArray() : null,
2335 AuthenticationTokenIdentifier.AUTH_TOKEN_TYPE,
2336 proto.hasService() ? new Text(proto.getService().toStringUtf8()) : null);
2337 }
2338
2339
2340
2341
2342
2343
2344
2345
2346 public static String getRegionEncodedName(
2347 final RegionSpecifier regionSpecifier) throws DoNotRetryIOException {
2348 byte[] value = regionSpecifier.getValue().toByteArray();
2349 RegionSpecifierType type = regionSpecifier.getType();
2350 switch (type) {
2351 case REGION_NAME:
2352 return HRegionInfo.encodeRegionName(value);
2353 case ENCODED_REGION_NAME:
2354 return Bytes.toString(value);
2355 default:
2356 throw new DoNotRetryIOException(
2357 "Unsupported region specifier type: " + type);
2358 }
2359 }
2360
2361 public static ScanMetrics toScanMetrics(final byte[] bytes) {
2362 Parser<MapReduceProtos.ScanMetrics> parser = MapReduceProtos.ScanMetrics.PARSER;
2363 MapReduceProtos.ScanMetrics pScanMetrics = null;
2364 try {
2365 pScanMetrics = parser.parseFrom(bytes);
2366 } catch (InvalidProtocolBufferException e) {
2367
2368 }
2369 ScanMetrics scanMetrics = new ScanMetrics();
2370 if (pScanMetrics != null) {
2371 for (HBaseProtos.NameInt64Pair pair : pScanMetrics.getMetricsList()) {
2372 if (pair.hasName() && pair.hasValue()) {
2373 scanMetrics.setCounter(pair.getName(), pair.getValue());
2374 }
2375 }
2376 }
2377 return scanMetrics;
2378 }
2379
2380 public static MapReduceProtos.ScanMetrics toScanMetrics(ScanMetrics scanMetrics) {
2381 MapReduceProtos.ScanMetrics.Builder builder = MapReduceProtos.ScanMetrics.newBuilder();
2382 Map<String, Long> metrics = scanMetrics.getMetricsMap();
2383 for (Entry<String, Long> e : metrics.entrySet()) {
2384 HBaseProtos.NameInt64Pair nameInt64Pair =
2385 HBaseProtos.NameInt64Pair.newBuilder()
2386 .setName(e.getKey())
2387 .setValue(e.getValue())
2388 .build();
2389 builder.addMetrics(nameInt64Pair);
2390 }
2391 return builder.build();
2392 }
2393
2394
2395
2396
2397
2398
2399 public static void toIOException(ServiceException se) throws IOException {
2400 if (se == null) {
2401 throw new NullPointerException("Null service exception passed!");
2402 }
2403
2404 Throwable cause = se.getCause();
2405 if (cause != null && cause instanceof IOException) {
2406 throw (IOException)cause;
2407 }
2408 throw new IOException(se);
2409 }
2410
2411 public static CellProtos.Cell toCell(final Cell kv) {
2412
2413
2414 CellProtos.Cell.Builder kvbuilder = CellProtos.Cell.newBuilder();
2415 kvbuilder.setRow(ByteStringer.wrap(kv.getRowArray(), kv.getRowOffset(),
2416 kv.getRowLength()));
2417 kvbuilder.setFamily(ByteStringer.wrap(kv.getFamilyArray(),
2418 kv.getFamilyOffset(), kv.getFamilyLength()));
2419 kvbuilder.setQualifier(ByteStringer.wrap(kv.getQualifierArray(),
2420 kv.getQualifierOffset(), kv.getQualifierLength()));
2421 kvbuilder.setCellType(CellProtos.CellType.valueOf(kv.getTypeByte()));
2422 kvbuilder.setTimestamp(kv.getTimestamp());
2423 kvbuilder.setValue(ByteStringer.wrap(kv.getValueArray(), kv.getValueOffset(),
2424 kv.getValueLength()));
2425 return kvbuilder.build();
2426 }
2427
2428 public static Cell toCell(final CellProtos.Cell cell) {
2429
2430
2431 return CellUtil.createCell(cell.getRow().toByteArray(),
2432 cell.getFamily().toByteArray(),
2433 cell.getQualifier().toByteArray(),
2434 cell.getTimestamp(),
2435 (byte)cell.getCellType().getNumber(),
2436 cell.getValue().toByteArray());
2437 }
2438
2439 public static HBaseProtos.NamespaceDescriptor toProtoNamespaceDescriptor(NamespaceDescriptor ns) {
2440 HBaseProtos.NamespaceDescriptor.Builder b =
2441 HBaseProtos.NamespaceDescriptor.newBuilder()
2442 .setName(ByteString.copyFromUtf8(ns.getName()));
2443 for(Map.Entry<String, String> entry: ns.getConfiguration().entrySet()) {
2444 b.addConfiguration(HBaseProtos.NameStringPair.newBuilder()
2445 .setName(entry.getKey())
2446 .setValue(entry.getValue()));
2447 }
2448 return b.build();
2449 }
2450
2451 public static NamespaceDescriptor toNamespaceDescriptor(
2452 HBaseProtos.NamespaceDescriptor desc) throws IOException {
2453 NamespaceDescriptor.Builder b =
2454 NamespaceDescriptor.create(desc.getName().toStringUtf8());
2455 for(HBaseProtos.NameStringPair prop : desc.getConfigurationList()) {
2456 b.addConfiguration(prop.getName(), prop.getValue());
2457 }
2458 return b.build();
2459 }
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471 @SuppressWarnings("unchecked")
2472 public static <T extends Message>
2473 T getParsedGenericInstance(Class<?> runtimeClass, int position, ByteString b)
2474 throws IOException {
2475 Type type = runtimeClass.getGenericSuperclass();
2476 Type argType = ((ParameterizedType)type).getActualTypeArguments()[position];
2477 Class<T> classType = (Class<T>)argType;
2478 T inst;
2479 try {
2480 Method m = classType.getMethod("parseFrom", ByteString.class);
2481 inst = (T)m.invoke(null, b);
2482 return inst;
2483 } catch (SecurityException e) {
2484 throw new IOException(e);
2485 } catch (NoSuchMethodException e) {
2486 throw new IOException(e);
2487 } catch (IllegalArgumentException e) {
2488 throw new IOException(e);
2489 } catch (InvocationTargetException e) {
2490 throw new IOException(e);
2491 } catch (IllegalAccessException e) {
2492 throw new IOException(e);
2493 }
2494 }
2495
2496 public static CompactionDescriptor toCompactionDescriptor(HRegionInfo info, byte[] family,
2497 List<Path> inputPaths, List<Path> outputPaths, Path storeDir) {
2498
2499
2500
2501 CompactionDescriptor.Builder builder = CompactionDescriptor.newBuilder()
2502 .setTableName(ByteStringer.wrap(info.getTableName()))
2503 .setEncodedRegionName(ByteStringer.wrap(info.getEncodedNameAsBytes()))
2504 .setFamilyName(ByteStringer.wrap(family))
2505 .setStoreHomeDir(storeDir.getName());
2506 for (Path inputPath : inputPaths) {
2507 builder.addCompactionInput(inputPath.getName());
2508 }
2509 for (Path outputPath : outputPaths) {
2510 builder.addCompactionOutput(outputPath.getName());
2511 }
2512 builder.setRegionName(ByteStringer.wrap(info.getRegionName()));
2513 return builder.build();
2514 }
2515
2516
2517
2518
2519
2520
2521
2522
2523 public static String getShortTextFormat(Message m) {
2524 if (m == null) return "null";
2525 if (m instanceof ScanRequest) {
2526
2527 return TextFormat.shortDebugString(m);
2528 } else if (m instanceof RegionServerReportRequest) {
2529
2530 RegionServerReportRequest r = (RegionServerReportRequest)m;
2531 return "server " + TextFormat.shortDebugString(r.getServer()) +
2532 " load { numberOfRequests: " + r.getLoad().getNumberOfRequests() + " }";
2533 } else if (m instanceof RegionServerStartupRequest) {
2534
2535 return TextFormat.shortDebugString(m);
2536 } else if (m instanceof MutationProto) {
2537 return toShortString((MutationProto)m);
2538 } else if (m instanceof GetRequest) {
2539 GetRequest r = (GetRequest) m;
2540 return "region= " + getStringForByteString(r.getRegion().getValue()) +
2541 ", row=" + getStringForByteString(r.getGet().getRow());
2542 } else if (m instanceof ClientProtos.MultiRequest) {
2543 ClientProtos.MultiRequest r = (ClientProtos.MultiRequest) m;
2544
2545 ClientProtos.RegionAction actions = r.getRegionActionList().get(0);
2546 String row = actions.getActionCount() <= 0? "":
2547 getStringForByteString(actions.getAction(0).hasGet()?
2548 actions.getAction(0).getGet().getRow():
2549 actions.getAction(0).getMutation().getRow());
2550 return "region= " + getStringForByteString(actions.getRegion().getValue()) +
2551 ", for " + r.getRegionActionCount() +
2552 " actions and 1st row key=" + row;
2553 } else if (m instanceof ClientProtos.MutateRequest) {
2554 ClientProtos.MutateRequest r = (ClientProtos.MutateRequest) m;
2555 return "region= " + getStringForByteString(r.getRegion().getValue()) +
2556 ", row=" + getStringForByteString(r.getMutation().getRow());
2557 }
2558 return "TODO: " + m.getClass().toString();
2559 }
2560
2561 private static String getStringForByteString(ByteString bs) {
2562 return Bytes.toStringBinary(bs.toByteArray());
2563 }
2564
2565
2566
2567
2568
2569
2570 static String toShortString(final MutationProto proto) {
2571 return "row=" + Bytes.toString(proto.getRow().toByteArray()) +
2572 ", type=" + proto.getMutateType().toString();
2573 }
2574
2575 public static TableName toTableName(HBaseProtos.TableName tableNamePB) {
2576 return TableName.valueOf(tableNamePB.getNamespace().asReadOnlyByteBuffer(),
2577 tableNamePB.getQualifier().asReadOnlyByteBuffer());
2578 }
2579
2580 public static HBaseProtos.TableName toProtoTableName(TableName tableName) {
2581 return HBaseProtos.TableName.newBuilder()
2582 .setNamespace(ByteStringer.wrap(tableName.getNamespace()))
2583 .setQualifier(ByteStringer.wrap(tableName.getQualifier())).build();
2584 }
2585
2586 public static TableName[] getTableNameArray(List<HBaseProtos.TableName> tableNamesList) {
2587 if (tableNamesList == null) {
2588 return new TableName[0];
2589 }
2590 TableName[] tableNames = new TableName[tableNamesList.size()];
2591 for (int i = 0; i < tableNamesList.size(); i++) {
2592 tableNames[i] = toTableName(tableNamesList.get(i));
2593 }
2594 return tableNames;
2595 }
2596
2597
2598
2599
2600
2601
2602
2603 public static CellVisibility toCellVisibility(ClientProtos.CellVisibility proto) {
2604 if (proto == null) return null;
2605 return new CellVisibility(proto.getExpression());
2606 }
2607
2608
2609
2610
2611
2612
2613
2614
2615 public static CellVisibility toCellVisibility(byte[] protoBytes) throws DeserializationException {
2616 if (protoBytes == null) return null;
2617 ClientProtos.CellVisibility.Builder builder = ClientProtos.CellVisibility.newBuilder();
2618 ClientProtos.CellVisibility proto = null;
2619 try {
2620 proto = builder.mergeFrom(protoBytes).build();
2621 } catch (InvalidProtocolBufferException e) {
2622 throw new DeserializationException(e);
2623 }
2624 return toCellVisibility(proto);
2625 }
2626
2627
2628
2629
2630
2631
2632
2633 public static ClientProtos.CellVisibility toCellVisibility(CellVisibility cellVisibility) {
2634 ClientProtos.CellVisibility.Builder builder = ClientProtos.CellVisibility.newBuilder();
2635 builder.setExpression(cellVisibility.getExpression());
2636 return builder.build();
2637 }
2638
2639
2640
2641
2642
2643
2644
2645 public static Authorizations toAuthorizations(ClientProtos.Authorizations proto) {
2646 if (proto == null) return null;
2647 return new Authorizations(proto.getLabelList());
2648 }
2649
2650
2651
2652
2653
2654
2655
2656
2657 public static Authorizations toAuthorizations(byte[] protoBytes) throws DeserializationException {
2658 if (protoBytes == null) return null;
2659 ClientProtos.Authorizations.Builder builder = ClientProtos.Authorizations.newBuilder();
2660 ClientProtos.Authorizations proto = null;
2661 try {
2662 proto = builder.mergeFrom(protoBytes).build();
2663 } catch (InvalidProtocolBufferException e) {
2664 throw new DeserializationException(e);
2665 }
2666 return toAuthorizations(proto);
2667 }
2668
2669
2670
2671
2672
2673
2674
2675 public static ClientProtos.Authorizations toAuthorizations(Authorizations authorizations) {
2676 ClientProtos.Authorizations.Builder builder = ClientProtos.Authorizations.newBuilder();
2677 for (String label : authorizations.getLabels()) {
2678 builder.addLabel(label);
2679 }
2680 return builder.build();
2681 }
2682
2683 public static AccessControlProtos.UsersAndPermissions toUsersAndPermissions(String user,
2684 Permission perms) {
2685 return AccessControlProtos.UsersAndPermissions.newBuilder()
2686 .addUserPermissions(AccessControlProtos.UsersAndPermissions.UserPermissions.newBuilder()
2687 .setUser(ByteString.copyFromUtf8(user))
2688 .addPermissions(toPermission(perms))
2689 .build())
2690 .build();
2691 }
2692
2693 public static AccessControlProtos.UsersAndPermissions toUsersAndPermissions(
2694 ListMultimap<String, Permission> perms) {
2695 AccessControlProtos.UsersAndPermissions.Builder builder =
2696 AccessControlProtos.UsersAndPermissions.newBuilder();
2697 for (Map.Entry<String, Collection<Permission>> entry : perms.asMap().entrySet()) {
2698 AccessControlProtos.UsersAndPermissions.UserPermissions.Builder userPermBuilder =
2699 AccessControlProtos.UsersAndPermissions.UserPermissions.newBuilder();
2700 userPermBuilder.setUser(ByteString.copyFromUtf8(entry.getKey()));
2701 for (Permission perm: entry.getValue()) {
2702 userPermBuilder.addPermissions(toPermission(perm));
2703 }
2704 builder.addUserPermissions(userPermBuilder.build());
2705 }
2706 return builder.build();
2707 }
2708
2709 public static ListMultimap<String, Permission> toUsersAndPermissions(
2710 AccessControlProtos.UsersAndPermissions proto) {
2711 ListMultimap<String, Permission> result = ArrayListMultimap.create();
2712 for (AccessControlProtos.UsersAndPermissions.UserPermissions userPerms:
2713 proto.getUserPermissionsList()) {
2714 String user = userPerms.getUser().toStringUtf8();
2715 for (AccessControlProtos.Permission perm: userPerms.getPermissionsList()) {
2716 result.put(user, toPermission(perm));
2717 }
2718 }
2719 return result;
2720 }
2721 }