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