forked from apache/accumulo
-
Notifications
You must be signed in to change notification settings - Fork 2
/
TableOperationsImpl.java
1943 lines (1653 loc) · 71.7 KB
/
TableOperationsImpl.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.accumulo.core.client.impl;
import static com.google.common.base.Preconditions.checkArgument;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static java.util.stream.Collectors.toSet;
import static org.apache.accumulo.fate.util.UtilWaitThread.sleepUninterruptibly;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.apache.accumulo.core.Constants;
import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.client.IsolatedScanner;
import org.apache.accumulo.core.client.IteratorSetting;
import org.apache.accumulo.core.client.NamespaceExistsException;
import org.apache.accumulo.core.client.NamespaceNotFoundException;
import org.apache.accumulo.core.client.RowIterator;
import org.apache.accumulo.core.client.Scanner;
import org.apache.accumulo.core.client.TableDeletedException;
import org.apache.accumulo.core.client.TableExistsException;
import org.apache.accumulo.core.client.TableNotFoundException;
import org.apache.accumulo.core.client.TableOfflineException;
import org.apache.accumulo.core.client.admin.CompactionConfig;
import org.apache.accumulo.core.client.admin.DiskUsage;
import org.apache.accumulo.core.client.admin.FindMax;
import org.apache.accumulo.core.client.admin.Locations;
import org.apache.accumulo.core.client.admin.NewTableConfiguration;
import org.apache.accumulo.core.client.admin.SummaryRetriever;
import org.apache.accumulo.core.client.admin.TableOperations;
import org.apache.accumulo.core.client.admin.TimeType;
import org.apache.accumulo.core.client.impl.TabletLocator.TabletLocation;
import org.apache.accumulo.core.client.impl.thrift.ClientService.Client;
import org.apache.accumulo.core.client.impl.thrift.TDiskUsage;
import org.apache.accumulo.core.client.impl.thrift.ThriftNotActiveServiceException;
import org.apache.accumulo.core.client.impl.thrift.ThriftSecurityException;
import org.apache.accumulo.core.client.impl.thrift.ThriftTableOperationException;
import org.apache.accumulo.core.client.sample.SamplerConfiguration;
import org.apache.accumulo.core.client.summary.SummarizerConfiguration;
import org.apache.accumulo.core.client.summary.Summary;
import org.apache.accumulo.core.conf.AccumuloConfiguration;
import org.apache.accumulo.core.conf.ConfigurationCopy;
import org.apache.accumulo.core.conf.Property;
import org.apache.accumulo.core.constraints.Constraint;
import org.apache.accumulo.core.data.ByteSequence;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.data.TabletId;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.data.impl.KeyExtent;
import org.apache.accumulo.core.data.impl.TabletIdImpl;
import org.apache.accumulo.core.data.thrift.TRowRange;
import org.apache.accumulo.core.data.thrift.TSummaries;
import org.apache.accumulo.core.data.thrift.TSummarizerConfiguration;
import org.apache.accumulo.core.data.thrift.TSummaryRequest;
import org.apache.accumulo.core.iterators.IteratorUtil;
import org.apache.accumulo.core.iterators.IteratorUtil.IteratorScope;
import org.apache.accumulo.core.iterators.SortedKeyValueIterator;
import org.apache.accumulo.core.master.state.tables.TableState;
import org.apache.accumulo.core.master.thrift.FateOperation;
import org.apache.accumulo.core.master.thrift.MasterClientService;
import org.apache.accumulo.core.metadata.MetadataServicer;
import org.apache.accumulo.core.metadata.MetadataTable;
import org.apache.accumulo.core.metadata.RootTable;
import org.apache.accumulo.core.metadata.schema.MetadataSchema.TabletsSection;
import org.apache.accumulo.core.rpc.ThriftUtil;
import org.apache.accumulo.core.sample.impl.SamplerConfigurationImpl;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.accumulo.core.summary.SummarizerConfigurationUtil;
import org.apache.accumulo.core.summary.SummaryCollection;
import org.apache.accumulo.core.tabletserver.thrift.NotServingTabletException;
import org.apache.accumulo.core.tabletserver.thrift.TabletClientService;
import org.apache.accumulo.core.trace.Tracer;
import org.apache.accumulo.core.util.CachedConfiguration;
import org.apache.accumulo.core.util.HostAndPort;
import org.apache.accumulo.core.util.LocalityGroupUtil;
import org.apache.accumulo.core.util.MapCounter;
import org.apache.accumulo.core.util.NamingThreadFactory;
import org.apache.accumulo.core.util.OpTimer;
import org.apache.accumulo.core.util.Pair;
import org.apache.accumulo.core.util.TextUtil;
import org.apache.accumulo.core.volume.VolumeConfiguration;
import org.apache.accumulo.fate.util.Retry;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.thrift.TApplicationException;
import org.apache.thrift.TException;
import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
public class TableOperationsImpl extends TableOperationsHelper {
public static final String CLONE_EXCLUDE_PREFIX = "!";
private static final Logger log = LoggerFactory.getLogger(TableOperations.class);
private final ClientContext context;
public TableOperationsImpl(ClientContext context) {
checkArgument(context != null, "context is null");
this.context = context;
}
@Override
public SortedSet<String> list() {
OpTimer timer = null;
if (log.isTraceEnabled()) {
log.trace("tid={} Fetching list of tables...", Thread.currentThread().getId());
timer = new OpTimer().start();
}
TreeSet<String> tableNames = new TreeSet<>(Tables.getNameToIdMap(context).keySet());
if (timer != null) {
timer.stop();
log.trace("tid={} Fetched {} table names in {}", Thread.currentThread().getId(),
tableNames.size(), String.format("%.3f secs", timer.scale(TimeUnit.SECONDS)));
}
return tableNames;
}
@Override
public boolean exists(String tableName) {
checkArgument(tableName != null, "tableName is null");
if (tableName.equals(MetadataTable.NAME) || tableName.equals(RootTable.NAME))
return true;
OpTimer timer = null;
if (log.isTraceEnabled()) {
log.trace("tid={} Checking if table {} exists...", Thread.currentThread().getId(), tableName);
timer = new OpTimer().start();
}
boolean exists = Tables.getNameToIdMap(context).containsKey(tableName);
if (timer != null) {
timer.stop();
log.trace("tid={} Checked existance of {} in {}", Thread.currentThread().getId(), exists,
String.format("%.3f secs", timer.scale(TimeUnit.SECONDS)));
}
return exists;
}
@Override
public void create(String tableName)
throws AccumuloException, AccumuloSecurityException, TableExistsException {
create(tableName, new NewTableConfiguration());
}
@Override
@Deprecated
public void create(String tableName, boolean limitVersion)
throws AccumuloException, AccumuloSecurityException, TableExistsException {
create(tableName, limitVersion, TimeType.MILLIS);
}
@Override
@Deprecated
public void create(String tableName, boolean limitVersion, TimeType timeType)
throws AccumuloException, AccumuloSecurityException, TableExistsException {
checkArgument(tableName != null, "tableName is null");
checkArgument(timeType != null, "timeType is null");
NewTableConfiguration ntc = new NewTableConfiguration().setTimeType(timeType);
if (limitVersion)
create(tableName, ntc);
else
create(tableName, ntc.withoutDefaultIterators());
}
@Override
public void create(String tableName, NewTableConfiguration ntc)
throws AccumuloException, AccumuloSecurityException, TableExistsException {
checkArgument(tableName != null, "tableName is null");
checkArgument(ntc != null, "ntc is null");
List<ByteBuffer> args = Arrays.asList(ByteBuffer.wrap(tableName.getBytes(UTF_8)),
ByteBuffer.wrap(ntc.getTimeType().name().getBytes(UTF_8)),
ByteBuffer.wrap(Boolean.toString(ntc.isExactDeleteEnabled()).getBytes(UTF_8)));
Map<String,String> opts = ntc.getProperties();
try {
doTableFateOperation(tableName, AccumuloException.class, FateOperation.TABLE_CREATE, args,
opts);
} catch (TableNotFoundException e) {
// should not happen
throw new AssertionError(e);
}
}
private long beginFateOperation() throws ThriftSecurityException, TException {
while (true) {
MasterClientService.Iface client = null;
try {
client = MasterClient.getConnectionWithRetry(context);
return client.beginFateOperation(Tracer.traceInfo(), context.rpcCreds());
} catch (TTransportException tte) {
log.debug("Failed to call beginFateOperation(), retrying ... ", tte);
sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
} catch (ThriftNotActiveServiceException e) {
// Let it loop, fetching a new location
log.debug("Contacted a Master which is no longer active, retrying");
sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
} finally {
MasterClient.close(client);
}
}
}
// This method is for retrying in the case of network failures; anything else it passes to the
// caller to deal with
private void executeFateOperation(long opid, FateOperation op, List<ByteBuffer> args,
Map<String,String> opts, boolean autoCleanUp)
throws ThriftSecurityException, TException, ThriftTableOperationException {
while (true) {
MasterClientService.Iface client = null;
try {
client = MasterClient.getConnectionWithRetry(context);
client.executeFateOperation(Tracer.traceInfo(), context.rpcCreds(), opid, op, args, opts,
autoCleanUp);
return;
} catch (TTransportException tte) {
log.debug("Failed to call executeFateOperation(), retrying ... ", tte);
sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
} catch (ThriftNotActiveServiceException e) {
// Let it loop, fetching a new location
log.debug("Contacted a Master which is no longer active, retrying");
sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
} finally {
MasterClient.close(client);
}
}
}
private String waitForFateOperation(long opid)
throws ThriftSecurityException, TException, ThriftTableOperationException {
while (true) {
MasterClientService.Iface client = null;
try {
client = MasterClient.getConnectionWithRetry(context);
return client.waitForFateOperation(Tracer.traceInfo(), context.rpcCreds(), opid);
} catch (TTransportException tte) {
log.debug("Failed to call waitForFateOperation(), retrying ... ", tte);
sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
} catch (ThriftNotActiveServiceException e) {
// Let it loop, fetching a new location
log.debug("Contacted a Master which is no longer active, retrying");
sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
} finally {
MasterClient.close(client);
}
}
}
private void finishFateOperation(long opid) throws ThriftSecurityException, TException {
while (true) {
MasterClientService.Iface client = null;
try {
client = MasterClient.getConnectionWithRetry(context);
client.finishFateOperation(Tracer.traceInfo(), context.rpcCreds(), opid);
break;
} catch (TTransportException tte) {
log.debug("Failed to call finishFateOperation(), retrying ... ", tte);
sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
} catch (ThriftNotActiveServiceException e) {
// Let it loop, fetching a new location
log.debug("Contacted a Master which is no longer active, retrying");
sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
} finally {
MasterClient.close(client);
}
}
}
String doFateOperation(FateOperation op, List<ByteBuffer> args, Map<String,String> opts,
String tableOrNamespaceName)
throws AccumuloSecurityException, TableExistsException, TableNotFoundException,
AccumuloException, NamespaceExistsException, NamespaceNotFoundException {
return doFateOperation(op, args, opts, tableOrNamespaceName, true);
}
String doFateOperation(FateOperation op, List<ByteBuffer> args, Map<String,String> opts,
String tableOrNamespaceName, boolean wait)
throws AccumuloSecurityException, TableExistsException, TableNotFoundException,
AccumuloException, NamespaceExistsException, NamespaceNotFoundException {
Long opid = null;
try {
opid = beginFateOperation();
executeFateOperation(opid, op, args, opts, !wait);
if (!wait) {
opid = null;
return null;
}
return waitForFateOperation(opid);
} catch (ThriftSecurityException e) {
switch (e.getCode()) {
case TABLE_DOESNT_EXIST:
throw new TableNotFoundException(null, tableOrNamespaceName,
"Target table does not exist");
case NAMESPACE_DOESNT_EXIST:
throw new NamespaceNotFoundException(null, tableOrNamespaceName,
"Target namespace does not exist");
default:
String tableInfo = Tables.getPrintableTableInfoFromName(context, tableOrNamespaceName);
throw new AccumuloSecurityException(e.user, e.code, tableInfo, e);
}
} catch (ThriftTableOperationException e) {
switch (e.getType()) {
case EXISTS:
throw new TableExistsException(e);
case NOTFOUND:
throw new TableNotFoundException(e);
case NAMESPACE_EXISTS:
throw new NamespaceExistsException(e);
case NAMESPACE_NOTFOUND:
throw new NamespaceNotFoundException(e);
case OFFLINE:
throw new TableOfflineException(
Tables.getTableOfflineMsg(context, Tables.getTableId(context, tableOrNamespaceName)));
default:
throw new AccumuloException(e.description, e);
}
} catch (Exception e) {
throw new AccumuloException(e.getMessage(), e);
} finally {
Tables.clearCache(context);
// always finish table op, even when exception
if (opid != null)
try {
finishFateOperation(opid);
} catch (Exception e) {
log.warn("Exception thrown while finishing fate table operation", e);
}
}
}
private static class SplitEnv {
private String tableName;
private Table.ID tableId;
private ExecutorService executor;
private CountDownLatch latch;
private AtomicReference<Throwable> exception;
SplitEnv(String tableName, Table.ID tableId, ExecutorService executor, CountDownLatch latch,
AtomicReference<Throwable> exception) {
this.tableName = tableName;
this.tableId = tableId;
this.executor = executor;
this.latch = latch;
this.exception = exception;
}
}
private class SplitTask implements Runnable {
private List<Text> splits;
private SplitEnv env;
SplitTask(SplitEnv env, List<Text> splits) {
this.env = env;
this.splits = splits;
}
@Override
public void run() {
try {
if (env.exception.get() != null)
return;
if (splits.size() <= 2) {
addSplits(env.tableName, new TreeSet<>(splits), env.tableId);
for (int i = 0; i < splits.size(); i++)
env.latch.countDown();
return;
}
int mid = splits.size() / 2;
// split the middle split point to ensure that child task split different tablets and can
// therefore
// run in parallel
addSplits(env.tableName, new TreeSet<>(splits.subList(mid, mid + 1)), env.tableId);
env.latch.countDown();
env.executor.execute(new SplitTask(env, splits.subList(0, mid)));
env.executor.execute(new SplitTask(env, splits.subList(mid + 1, splits.size())));
} catch (Throwable t) {
env.exception.compareAndSet(null, t);
}
}
}
@Override
public void addSplits(String tableName, SortedSet<Text> partitionKeys)
throws TableNotFoundException, AccumuloException, AccumuloSecurityException {
Table.ID tableId = Tables.getTableId(context, tableName);
List<Text> splits = new ArrayList<>(partitionKeys);
// should be sorted because we copied from a sorted set, but that makes assumptions about
// how the copy was done so resort to be sure.
Collections.sort(splits);
CountDownLatch latch = new CountDownLatch(splits.size());
AtomicReference<Throwable> exception = new AtomicReference<>(null);
ExecutorService executor = Executors.newFixedThreadPool(16,
new NamingThreadFactory("addSplits"));
try {
executor.execute(
new SplitTask(new SplitEnv(tableName, tableId, executor, latch, exception), splits));
while (!latch.await(100, TimeUnit.MILLISECONDS)) {
if (exception.get() != null) {
executor.shutdownNow();
Throwable excep = exception.get();
// Below all exceptions are wrapped and rethrown. This is done so that the user knows what
// code path got them here. If the wrapping was not done, the
// user would only have the stack trace for the background thread.
if (excep instanceof TableNotFoundException) {
TableNotFoundException tnfe = (TableNotFoundException) excep;
throw new TableNotFoundException(tableId.canonicalID(), tableName,
"Table not found by background thread", tnfe);
} else if (excep instanceof TableOfflineException) {
log.debug("TableOfflineException occurred in background thread. Throwing new exception",
excep);
throw new TableOfflineException(Tables.getTableOfflineMsg(context, tableId));
} else if (excep instanceof AccumuloSecurityException) {
// base == background accumulo security exception
AccumuloSecurityException base = (AccumuloSecurityException) excep;
throw new AccumuloSecurityException(base.getUser(), base.asThriftException().getCode(),
base.getTableInfo(), excep);
} else if (excep instanceof AccumuloServerException) {
throw new AccumuloServerException((AccumuloServerException) excep);
} else if (excep instanceof Error) {
throw new Error(excep);
} else {
throw new AccumuloException(excep);
}
}
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
executor.shutdown();
}
}
private void addSplits(String tableName, SortedSet<Text> partitionKeys, Table.ID tableId)
throws AccumuloException, AccumuloSecurityException, TableNotFoundException,
AccumuloServerException {
TabletLocator tabLocator = TabletLocator.getLocator(context, tableId);
for (Text split : partitionKeys) {
boolean successful = false;
int attempt = 0;
long locationFailures = 0;
while (!successful) {
if (attempt > 0)
sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
attempt++;
TabletLocation tl = tabLocator.locateTablet(context, split, false, false);
if (tl == null) {
if (!Tables.exists(context, tableId))
throw new TableNotFoundException(tableId.canonicalID(), tableName, null);
else if (Tables.getTableState(context, tableId) == TableState.OFFLINE)
throw new TableOfflineException(Tables.getTableOfflineMsg(context, tableId));
continue;
}
HostAndPort address = HostAndPort.fromString(tl.tablet_location);
try {
TabletClientService.Client client = ThriftUtil.getTServerClient(address, context);
try {
OpTimer timer = null;
if (log.isTraceEnabled()) {
log.trace("tid={} Splitting tablet {} on {} at {}", Thread.currentThread().getId(),
tl.tablet_extent, address, split);
timer = new OpTimer().start();
}
client.splitTablet(Tracer.traceInfo(), context.rpcCreds(), tl.tablet_extent.toThrift(),
TextUtil.getByteBuffer(split));
// just split it, might as well invalidate it in the cache
tabLocator.invalidateCache(tl.tablet_extent);
if (timer != null) {
timer.stop();
log.trace("Split tablet in {}",
String.format("%.3f secs", timer.scale(TimeUnit.SECONDS)));
}
} finally {
ThriftUtil.returnClient(client);
}
} catch (TApplicationException tae) {
throw new AccumuloServerException(address.toString(), tae);
} catch (TTransportException e) {
tabLocator.invalidateCache(context, tl.tablet_location);
continue;
} catch (ThriftSecurityException e) {
Tables.clearCache(context);
if (!Tables.exists(context, tableId))
throw new TableNotFoundException(tableId.canonicalID(), tableName, null);
throw new AccumuloSecurityException(e.user, e.code, e);
} catch (NotServingTabletException e) {
// Do not silently spin when we repeatedly fail to get the location for a tablet
locationFailures++;
if (5 == locationFailures || 0 == locationFailures % 50) {
log.warn("Having difficulty locating hosting tabletserver for split {} on table {}."
+ " Seen {} failures.", split, tableName, locationFailures);
}
tabLocator.invalidateCache(tl.tablet_extent);
continue;
} catch (TException e) {
tabLocator.invalidateCache(context, tl.tablet_location);
continue;
}
successful = true;
}
}
}
@Override
public void merge(String tableName, Text start, Text end)
throws AccumuloException, AccumuloSecurityException, TableNotFoundException {
checkArgument(tableName != null, "tableName is null");
ByteBuffer EMPTY = ByteBuffer.allocate(0);
List<ByteBuffer> args = Arrays.asList(ByteBuffer.wrap(tableName.getBytes(UTF_8)),
start == null ? EMPTY : TextUtil.getByteBuffer(start),
end == null ? EMPTY : TextUtil.getByteBuffer(end));
Map<String,String> opts = new HashMap<>();
try {
doTableFateOperation(tableName, TableNotFoundException.class, FateOperation.TABLE_MERGE, args,
opts);
} catch (TableExistsException e) {
// should not happen
throw new AssertionError(e);
}
}
@Override
public void deleteRows(String tableName, Text start, Text end)
throws AccumuloException, AccumuloSecurityException, TableNotFoundException {
checkArgument(tableName != null, "tableName is null");
ByteBuffer EMPTY = ByteBuffer.allocate(0);
List<ByteBuffer> args = Arrays.asList(ByteBuffer.wrap(tableName.getBytes(UTF_8)),
start == null ? EMPTY : TextUtil.getByteBuffer(start),
end == null ? EMPTY : TextUtil.getByteBuffer(end));
Map<String,String> opts = new HashMap<>();
try {
doTableFateOperation(tableName, TableNotFoundException.class,
FateOperation.TABLE_DELETE_RANGE, args, opts);
} catch (TableExistsException e) {
// should not happen
throw new AssertionError(e);
}
}
@Override
public Collection<Text> listSplits(String tableName)
throws TableNotFoundException, AccumuloSecurityException {
checkArgument(tableName != null, "tableName is null");
Table.ID tableId = Tables.getTableId(context, tableName);
TreeMap<KeyExtent,String> tabletLocations = new TreeMap<>();
while (true) {
try {
tabletLocations.clear();
// the following method throws AccumuloException for some conditions that should be retried
MetadataServicer.forTableId(context, tableId).getTabletLocations(tabletLocations);
break;
} catch (AccumuloSecurityException ase) {
throw ase;
} catch (Exception e) {
if (!Tables.exists(context, tableId)) {
throw new TableNotFoundException(tableId.canonicalID(), tableName, null);
}
if (e instanceof RuntimeException && e.getCause() instanceof AccumuloSecurityException) {
throw (AccumuloSecurityException) e.getCause();
}
log.info("{} ... retrying ...", e.getMessage());
sleepUninterruptibly(3, TimeUnit.SECONDS);
}
}
ArrayList<Text> endRows = new ArrayList<>(tabletLocations.size());
for (KeyExtent ke : tabletLocations.keySet())
if (ke.getEndRow() != null)
endRows.add(ke.getEndRow());
return endRows;
}
@Deprecated
@Override
public Collection<Text> getSplits(String tableName) throws TableNotFoundException {
try {
return listSplits(tableName);
} catch (AccumuloSecurityException e) {
throw new RuntimeException(e);
}
}
@Override
public Collection<Text> listSplits(String tableName, int maxSplits)
throws TableNotFoundException, AccumuloSecurityException {
Collection<Text> endRows = listSplits(tableName);
if (endRows.size() <= maxSplits)
return endRows;
double r = (maxSplits + 1) / (double) (endRows.size());
double pos = 0;
ArrayList<Text> subset = new ArrayList<>(maxSplits);
int j = 0;
for (int i = 0; i < endRows.size() && j < maxSplits; i++) {
pos += r;
while (pos > 1) {
subset.add(((ArrayList<Text>) endRows).get(i));
j++;
pos -= 1;
}
}
return subset;
}
@Deprecated
@Override
public Collection<Text> getSplits(String tableName, int maxSplits) throws TableNotFoundException {
try {
return listSplits(tableName, maxSplits);
} catch (AccumuloSecurityException e) {
throw new RuntimeException(e);
}
}
@Override
public void delete(String tableName)
throws AccumuloException, AccumuloSecurityException, TableNotFoundException {
checkArgument(tableName != null, "tableName is null");
List<ByteBuffer> args = Arrays.asList(ByteBuffer.wrap(tableName.getBytes(UTF_8)));
Map<String,String> opts = new HashMap<>();
try {
doTableFateOperation(tableName, TableNotFoundException.class, FateOperation.TABLE_DELETE,
args, opts);
} catch (TableExistsException e) {
// should not happen
throw new AssertionError(e);
}
}
@Override
public void clone(String srcTableName, String newTableName, boolean flush,
Map<String,String> propertiesToSet, Set<String> propertiesToExclude)
throws AccumuloSecurityException, TableNotFoundException, AccumuloException,
TableExistsException {
checkArgument(srcTableName != null, "srcTableName is null");
checkArgument(newTableName != null, "newTableName is null");
Table.ID srcTableId = Tables.getTableId(context, srcTableName);
if (flush)
_flush(srcTableId, null, null, true);
if (propertiesToExclude == null)
propertiesToExclude = Collections.emptySet();
if (propertiesToSet == null)
propertiesToSet = Collections.emptyMap();
List<ByteBuffer> args = Arrays.asList(ByteBuffer.wrap(srcTableId.getUtf8()),
ByteBuffer.wrap(newTableName.getBytes(UTF_8)));
Map<String,String> opts = new HashMap<>();
for (Entry<String,String> entry : propertiesToSet.entrySet()) {
if (entry.getKey().startsWith(CLONE_EXCLUDE_PREFIX))
throw new IllegalArgumentException("Property can not start with " + CLONE_EXCLUDE_PREFIX);
opts.put(entry.getKey(), entry.getValue());
}
for (String prop : propertiesToExclude) {
opts.put(CLONE_EXCLUDE_PREFIX + prop, "");
}
doTableFateOperation(newTableName, AccumuloException.class, FateOperation.TABLE_CLONE, args,
opts);
}
@Override
public void rename(String oldTableName, String newTableName) throws AccumuloSecurityException,
TableNotFoundException, AccumuloException, TableExistsException {
List<ByteBuffer> args = Arrays.asList(ByteBuffer.wrap(oldTableName.getBytes(UTF_8)),
ByteBuffer.wrap(newTableName.getBytes(UTF_8)));
Map<String,String> opts = new HashMap<>();
doTableFateOperation(oldTableName, TableNotFoundException.class, FateOperation.TABLE_RENAME,
args, opts);
}
@Override
@Deprecated
public void flush(String tableName) throws AccumuloException, AccumuloSecurityException {
try {
flush(tableName, null, null, false);
} catch (TableNotFoundException e) {
throw new AccumuloException(e.getMessage(), e);
}
}
@Override
public void flush(String tableName, Text start, Text end, boolean wait)
throws AccumuloException, AccumuloSecurityException, TableNotFoundException {
checkArgument(tableName != null, "tableName is null");
Table.ID tableId = Tables.getTableId(context, tableName);
_flush(tableId, start, end, wait);
}
@Override
public void compact(String tableName, Text start, Text end, boolean flush, boolean wait)
throws AccumuloSecurityException, TableNotFoundException, AccumuloException {
compact(tableName, start, end, new ArrayList<>(), flush, wait);
}
@Override
public void compact(String tableName, Text start, Text end, List<IteratorSetting> iterators,
boolean flush, boolean wait)
throws AccumuloSecurityException, TableNotFoundException, AccumuloException {
compact(tableName, new CompactionConfig().setStartRow(start).setEndRow(end)
.setIterators(iterators).setFlush(flush).setWait(wait));
}
@Override
public void compact(String tableName, CompactionConfig config)
throws AccumuloSecurityException, TableNotFoundException, AccumuloException {
checkArgument(tableName != null, "tableName is null");
ByteBuffer EMPTY = ByteBuffer.allocate(0);
// Ensure compaction iterators exist on a tabletserver
final String skviName = SortedKeyValueIterator.class.getName();
for (IteratorSetting setting : config.getIterators()) {
String iteratorClass = setting.getIteratorClass();
if (!testClassLoad(tableName, iteratorClass, skviName)) {
throw new AccumuloException("TabletServer could not load iterator class " + iteratorClass);
}
}
// Make sure the specified compaction strategy exists on a tabletserver
final String compactionStrategyName = config.getCompactionStrategy().getClassName();
if (!CompactionStrategyConfigUtil.DEFAULT_STRATEGY.getClassName()
.equals(compactionStrategyName)) {
if (!testClassLoad(tableName, compactionStrategyName,
"org.apache.accumulo.tserver.compaction.CompactionStrategy")) {
throw new AccumuloException(
"TabletServer could not load CompactionStrategy class " + compactionStrategyName);
}
}
Table.ID tableId = Tables.getTableId(context, tableName);
Text start = config.getStartRow();
Text end = config.getEndRow();
if (config.getFlush())
_flush(tableId, start, end, true);
List<ByteBuffer> args = Arrays.asList(ByteBuffer.wrap(tableId.getUtf8()),
start == null ? EMPTY : TextUtil.getByteBuffer(start),
end == null ? EMPTY : TextUtil.getByteBuffer(end),
ByteBuffer.wrap(IteratorUtil.encodeIteratorSettings(config.getIterators())),
ByteBuffer.wrap(CompactionStrategyConfigUtil.encode(config.getCompactionStrategy())));
Map<String,String> opts = new HashMap<>();
try {
doFateOperation(FateOperation.TABLE_COMPACT, args, opts, tableName, config.getWait());
} catch (TableExistsException | NamespaceExistsException e) {
// should not happen
throw new AssertionError(e);
} catch (NamespaceNotFoundException e) {
throw new TableNotFoundException(null, tableName, "Namespace not found", e);
}
}
@Override
public void cancelCompaction(String tableName)
throws AccumuloSecurityException, TableNotFoundException, AccumuloException {
Table.ID tableId = Tables.getTableId(context, tableName);
List<ByteBuffer> args = Arrays.asList(ByteBuffer.wrap(tableId.getUtf8()));
Map<String,String> opts = new HashMap<>();
try {
doTableFateOperation(tableName, TableNotFoundException.class,
FateOperation.TABLE_CANCEL_COMPACT, args, opts);
} catch (TableExistsException e) {
// should not happen
throw new AssertionError(e);
}
}
private void _flush(Table.ID tableId, Text start, Text end, boolean wait)
throws AccumuloException, AccumuloSecurityException, TableNotFoundException {
try {
long flushID;
// used to pass the table name. but the tableid associated with a table name could change
// between calls.
// so pass the tableid to both calls
while (true) {
MasterClientService.Iface client = null;
try {
client = MasterClient.getConnectionWithRetry(context);
flushID = client.initiateFlush(Tracer.traceInfo(), context.rpcCreds(),
tableId.canonicalID());
break;
} catch (TTransportException tte) {
log.debug("Failed to call initiateFlush, retrying ... ", tte);
sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
} catch (ThriftNotActiveServiceException e) {
// Let it loop, fetching a new location
log.debug("Contacted a Master which is no longer active, retrying");
sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
} finally {
MasterClient.close(client);
}
}
while (true) {
MasterClientService.Iface client = null;
try {
client = MasterClient.getConnectionWithRetry(context);
client.waitForFlush(Tracer.traceInfo(), context.rpcCreds(), tableId.canonicalID(),
TextUtil.getByteBuffer(start), TextUtil.getByteBuffer(end), flushID,
wait ? Long.MAX_VALUE : 1);
break;
} catch (TTransportException tte) {
log.debug("Failed to call initiateFlush, retrying ... ", tte);
sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
} catch (ThriftNotActiveServiceException e) {
// Let it loop, fetching a new location
log.debug("Contacted a Master which is no longer active, retrying");
sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
} finally {
MasterClient.close(client);
}
}
} catch (ThriftSecurityException e) {
switch (e.getCode()) {
case TABLE_DOESNT_EXIST:
throw new TableNotFoundException(tableId.canonicalID(), null, e.getMessage(), e);
default:
log.debug("flush security exception on table id {}", tableId);
throw new AccumuloSecurityException(e.user, e.code, e);
}
} catch (ThriftTableOperationException e) {
switch (e.getType()) {
case NOTFOUND:
throw new TableNotFoundException(e);
default:
throw new AccumuloException(e.description, e);
}
} catch (Exception e) {
throw new AccumuloException(e);
}
}
@Override
public void setProperty(final String tableName, final String property, final String value)
throws AccumuloException, AccumuloSecurityException {
checkArgument(tableName != null, "tableName is null");
checkArgument(property != null, "property is null");
checkArgument(value != null, "value is null");
try {
MasterClient.executeTable(context, client -> client.setTableProperty(Tracer.traceInfo(),
context.rpcCreds(), tableName, property, value));
} catch (TableNotFoundException e) {
throw new AccumuloException(e);
}
}
@Override
public void removeProperty(final String tableName, final String property)
throws AccumuloException, AccumuloSecurityException {
checkArgument(tableName != null, "tableName is null");
checkArgument(property != null, "property is null");
try {
MasterClient.executeTable(context, client -> client.removeTableProperty(Tracer.traceInfo(),
context.rpcCreds(), tableName, property));
} catch (TableNotFoundException e) {
throw new AccumuloException(e);
}
}
@Override
public Iterable<Entry<String,String>> getProperties(final String tableName)
throws AccumuloException, TableNotFoundException {
checkArgument(tableName != null, "tableName is null");
try {
return ServerClient.executeRaw(context,
client -> client.getTableConfiguration(Tracer.traceInfo(), context.rpcCreds(), tableName))
.entrySet();
} catch (ThriftTableOperationException e) {
switch (e.getType()) {
case NOTFOUND:
throw new TableNotFoundException(e);
case NAMESPACE_NOTFOUND:
throw new TableNotFoundException(tableName, new NamespaceNotFoundException(e));