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