1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.hadoop.hbase.security.visibility;
19
20 import static org.apache.hadoop.hbase.TagType.VISIBILITY_TAG_TYPE;
21 import static org.apache.hadoop.hbase.security.visibility.VisibilityConstants.LABELS_TABLE_FAMILY;
22 import static org.apache.hadoop.hbase.security.visibility.VisibilityConstants.LABELS_TABLE_NAME;
23 import static org.apache.hadoop.hbase.security.visibility.VisibilityConstants.LABEL_QUALIFIER;
24 import static org.apache.hadoop.hbase.security.visibility.VisibilityConstants.SORTED_ORDINAL_SERIALIZATION_FORMAT;
25 import static org.apache.hadoop.hbase.security.visibility.VisibilityUtils.SYSTEM_LABEL;
26
27 import java.io.ByteArrayOutputStream;
28 import java.io.DataOutputStream;
29 import java.io.IOException;
30 import java.util.ArrayList;
31 import java.util.BitSet;
32 import java.util.Collections;
33 import java.util.HashMap;
34 import java.util.HashSet;
35 import java.util.Iterator;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.Set;
39 import java.util.concurrent.atomic.AtomicInteger;
40 import java.util.regex.Pattern;
41
42 import org.apache.commons.logging.Log;
43 import org.apache.commons.logging.LogFactory;
44 import org.apache.hadoop.conf.Configuration;
45 import org.apache.hadoop.hbase.Cell;
46 import org.apache.hadoop.hbase.CellUtil;
47 import org.apache.hadoop.hbase.HConstants;
48 import org.apache.hadoop.hbase.HConstants.OperationStatusCode;
49 import org.apache.hadoop.hbase.Tag;
50 import org.apache.hadoop.hbase.TagType;
51 import org.apache.hadoop.hbase.classification.InterfaceAudience;
52 import org.apache.hadoop.hbase.client.Delete;
53 import org.apache.hadoop.hbase.client.Mutation;
54 import org.apache.hadoop.hbase.client.Put;
55 import org.apache.hadoop.hbase.client.Scan;
56 import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
57 import org.apache.hadoop.hbase.filter.Filter;
58 import org.apache.hadoop.hbase.io.util.StreamUtils;
59 import org.apache.hadoop.hbase.regionserver.OperationStatus;
60 import org.apache.hadoop.hbase.regionserver.Region;
61 import org.apache.hadoop.hbase.regionserver.RegionScanner;
62 import org.apache.hadoop.hbase.security.User;
63 import org.apache.hadoop.hbase.security.access.AccessControlLists;
64 import org.apache.hadoop.hbase.util.Bytes;
65 import org.apache.hadoop.hbase.util.Pair;
66 import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
67
68 @InterfaceAudience.Private
69 public class DefaultVisibilityLabelServiceImpl implements VisibilityLabelService {
70
71 private static final Log LOG = LogFactory.getLog(DefaultVisibilityLabelServiceImpl.class);
72
73
74 private static final int SYSTEM_LABEL_ORDINAL = 1;
75 private static final Tag[] LABELS_TABLE_TAGS = new Tag[1];
76 private static final byte[] DUMMY_VALUE = new byte[0];
77
78 private AtomicInteger ordinalCounter = new AtomicInteger(-1);
79 private Configuration conf;
80 private Region labelsRegion;
81 private VisibilityLabelsCache labelsCache;
82 private List<ScanLabelGenerator> scanLabelGenerators;
83 private List<String> superUsers;
84 private List<String> superGroups;
85
86 static {
87 ByteArrayOutputStream baos = new ByteArrayOutputStream();
88 DataOutputStream dos = new DataOutputStream(baos);
89 try {
90 StreamUtils.writeRawVInt32(dos, SYSTEM_LABEL_ORDINAL);
91 } catch (IOException e) {
92
93 }
94 LABELS_TABLE_TAGS[0] = new Tag(VISIBILITY_TAG_TYPE, baos.toByteArray());
95 }
96
97 public DefaultVisibilityLabelServiceImpl() {
98
99 }
100
101 @Override
102 public void setConf(Configuration conf) {
103 this.conf = conf;
104 }
105
106 @Override
107 public Configuration getConf() {
108 return this.conf;
109 }
110
111 @Override
112 public void init(RegionCoprocessorEnvironment e) throws IOException {
113 ZooKeeperWatcher zk = e.getRegionServerServices().getZooKeeper();
114 try {
115 labelsCache = VisibilityLabelsCache.createAndGet(zk, this.conf);
116 } catch (IOException ioe) {
117 LOG.error("Error creating VisibilityLabelsCache", ioe);
118 throw ioe;
119 }
120 this.scanLabelGenerators = VisibilityUtils.getScanLabelGenerators(this.conf);
121 Pair<List<String>, List<String>> superUsersAndGroups =
122 VisibilityUtils.getSystemAndSuperUsers(this.conf);
123 this.superUsers = superUsersAndGroups.getFirst();
124 this.superGroups = superUsersAndGroups.getSecond();
125 if (e.getRegion().getRegionInfo().getTable().equals(LABELS_TABLE_NAME)) {
126 this.labelsRegion = e.getRegion();
127 Pair<Map<String, Integer>, Map<String, List<Integer>>> labelsAndUserAuths =
128 extractLabelsAndAuths(getExistingLabelsWithAuths());
129 Map<String, Integer> labels = labelsAndUserAuths.getFirst();
130 Map<String, List<Integer>> userAuths = labelsAndUserAuths.getSecond();
131
132 addSystemLabel(this.labelsRegion, labels, userAuths);
133 int ordinal = SYSTEM_LABEL_ORDINAL;
134 for (Integer i : labels.values()) {
135 if (i > ordinal) {
136 ordinal = i;
137 }
138 }
139 this.ordinalCounter.set(ordinal + 1);
140 if (labels.size() > 0) {
141
142 byte[] serialized = VisibilityUtils.getDataToWriteToZooKeeper(labels);
143 this.labelsCache.writeToZookeeper(serialized, true);
144 this.labelsCache.refreshLabelsCache(serialized);
145 }
146 if (userAuths.size() > 0) {
147 byte[] serialized = VisibilityUtils.getUserAuthsDataToWriteToZooKeeper(userAuths);
148 this.labelsCache.writeToZookeeper(serialized, false);
149 this.labelsCache.refreshUserAuthsCache(serialized);
150 }
151 }
152 }
153
154 protected List<List<Cell>> getExistingLabelsWithAuths() throws IOException {
155 Scan scan = new Scan();
156 RegionScanner scanner = labelsRegion.getScanner(scan);
157 List<List<Cell>> existingLabels = new ArrayList<List<Cell>>();
158 try {
159 while (true) {
160 List<Cell> cells = new ArrayList<Cell>();
161 scanner.next(cells);
162 if (cells.isEmpty()) {
163 break;
164 }
165 existingLabels.add(cells);
166 }
167 } finally {
168 scanner.close();
169 }
170 return existingLabels;
171 }
172
173 protected Pair<Map<String, Integer>, Map<String, List<Integer>>> extractLabelsAndAuths(
174 List<List<Cell>> labelDetails) {
175 Map<String, Integer> labels = new HashMap<String, Integer>();
176 Map<String, List<Integer>> userAuths = new HashMap<String, List<Integer>>();
177 for (List<Cell> cells : labelDetails) {
178 for (Cell cell : cells) {
179 if (Bytes.equals(cell.getQualifierArray(), cell.getQualifierOffset(),
180 cell.getQualifierLength(), LABEL_QUALIFIER, 0, LABEL_QUALIFIER.length)) {
181 labels.put(
182 Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()),
183 Bytes.toInt(cell.getRowArray(), cell.getRowOffset()));
184 } else {
185
186 String user = Bytes.toString(cell.getQualifierArray(), cell.getQualifierOffset(),
187 cell.getQualifierLength());
188 List<Integer> auths = userAuths.get(user);
189 if (auths == null) {
190 auths = new ArrayList<Integer>();
191 userAuths.put(user, auths);
192 }
193 auths.add(Bytes.toInt(cell.getRowArray(), cell.getRowOffset()));
194 }
195 }
196 }
197 return new Pair<Map<String, Integer>, Map<String, List<Integer>>>(labels, userAuths);
198 }
199
200 protected void addSystemLabel(Region region, Map<String, Integer> labels,
201 Map<String, List<Integer>> userAuths) throws IOException {
202 if (!labels.containsKey(SYSTEM_LABEL)) {
203 Put p = new Put(Bytes.toBytes(SYSTEM_LABEL_ORDINAL));
204 p.addImmutable(LABELS_TABLE_FAMILY, LABEL_QUALIFIER, Bytes.toBytes(SYSTEM_LABEL));
205 region.put(p);
206 labels.put(SYSTEM_LABEL, SYSTEM_LABEL_ORDINAL);
207 }
208 }
209
210 @Override
211 public OperationStatus[] addLabels(List<byte[]> labels) throws IOException {
212 assert labelsRegion != null;
213 OperationStatus[] finalOpStatus = new OperationStatus[labels.size()];
214 List<Mutation> puts = new ArrayList<Mutation>(labels.size());
215 int i = 0;
216 for (byte[] label : labels) {
217 String labelStr = Bytes.toString(label);
218 if (this.labelsCache.getLabelOrdinal(labelStr) > 0) {
219 finalOpStatus[i] = new OperationStatus(OperationStatusCode.FAILURE,
220 new LabelAlreadyExistsException("Label '" + labelStr + "' already exists"));
221 } else {
222 Put p = new Put(Bytes.toBytes(ordinalCounter.get()));
223 p.addImmutable(LABELS_TABLE_FAMILY, LABEL_QUALIFIER, label, LABELS_TABLE_TAGS);
224 if (LOG.isDebugEnabled()) {
225 LOG.debug("Adding the label " + labelStr);
226 }
227 puts.add(p);
228 ordinalCounter.incrementAndGet();
229 }
230 i++;
231 }
232 if (mutateLabelsRegion(puts, finalOpStatus)) {
233 updateZk(true);
234 }
235 return finalOpStatus;
236 }
237
238 @Override
239 public OperationStatus[] setAuths(byte[] user, List<byte[]> authLabels) throws IOException {
240 assert labelsRegion != null;
241 OperationStatus[] finalOpStatus = new OperationStatus[authLabels.size()];
242 List<Mutation> puts = new ArrayList<Mutation>(authLabels.size());
243 int i = 0;
244 for (byte[] auth : authLabels) {
245 String authStr = Bytes.toString(auth);
246 int labelOrdinal = this.labelsCache.getLabelOrdinal(authStr);
247 if (labelOrdinal == 0) {
248
249 finalOpStatus[i] = new OperationStatus(OperationStatusCode.FAILURE,
250 new InvalidLabelException("Label '" + authStr + "' doesn't exists"));
251 } else {
252 Put p = new Put(Bytes.toBytes(labelOrdinal));
253 p.addImmutable(LABELS_TABLE_FAMILY, user, DUMMY_VALUE, LABELS_TABLE_TAGS);
254 puts.add(p);
255 }
256 i++;
257 }
258 if (mutateLabelsRegion(puts, finalOpStatus)) {
259 updateZk(false);
260 }
261 return finalOpStatus;
262 }
263
264 @Override
265 public OperationStatus[] clearAuths(byte[] user, List<byte[]> authLabels) throws IOException {
266 assert labelsRegion != null;
267 OperationStatus[] finalOpStatus = new OperationStatus[authLabels.size()];
268 List<String> currentAuths;
269 if (AccessControlLists.isGroupPrincipal(Bytes.toString(user))) {
270 String group = AccessControlLists.getGroupName(Bytes.toString(user));
271 currentAuths = this.getGroupAuths(new String[]{group}, true);
272 }
273 else {
274 currentAuths = this.getUserAuths(user, true);
275 }
276 List<Mutation> deletes = new ArrayList<Mutation>(authLabels.size());
277 int i = 0;
278 for (byte[] authLabel : authLabels) {
279 String authLabelStr = Bytes.toString(authLabel);
280 if (currentAuths.contains(authLabelStr)) {
281 int labelOrdinal = this.labelsCache.getLabelOrdinal(authLabelStr);
282 assert labelOrdinal > 0;
283 Delete d = new Delete(Bytes.toBytes(labelOrdinal));
284 d.deleteColumns(LABELS_TABLE_FAMILY, user);
285 deletes.add(d);
286 } else {
287
288 finalOpStatus[i] = new OperationStatus(OperationStatusCode.FAILURE,
289 new InvalidLabelException("Label '" + authLabelStr + "' is not set for the user "
290 + Bytes.toString(user)));
291 }
292 i++;
293 }
294 if (mutateLabelsRegion(deletes, finalOpStatus)) {
295 updateZk(false);
296 }
297 return finalOpStatus;
298 }
299
300
301
302
303
304
305
306
307
308 private boolean mutateLabelsRegion(List<Mutation> mutations, OperationStatus[] finalOpStatus)
309 throws IOException {
310 OperationStatus[] opStatus = this.labelsRegion.batchMutate(mutations
311 .toArray(new Mutation[mutations.size()]), HConstants.NO_NONCE, HConstants.NO_NONCE);
312 int i = 0;
313 boolean updateZk = false;
314 for (OperationStatus status : opStatus) {
315
316 updateZk = updateZk || (status.getOperationStatusCode() == OperationStatusCode.SUCCESS);
317 for (; i < finalOpStatus.length; i++) {
318 if (finalOpStatus[i] == null) {
319 finalOpStatus[i] = status;
320 break;
321 }
322 }
323 }
324 return updateZk;
325 }
326
327 @Override
328 @Deprecated
329 public List<String> getAuths(byte[] user, boolean systemCall)
330 throws IOException {
331 return getUserAuths(user, systemCall);
332 }
333
334 @Override
335 public List<String> getUserAuths(byte[] user, boolean systemCall)
336 throws IOException {
337 assert (labelsRegion != null || systemCall);
338 if (systemCall || labelsRegion == null) {
339 return this.labelsCache.getUserAuths(Bytes.toString(user));
340 }
341 Scan s = new Scan();
342 if (user != null && user.length > 0) {
343 s.addColumn(LABELS_TABLE_FAMILY, user);
344 }
345 Filter filter = VisibilityUtils.createVisibilityLabelFilter(this.labelsRegion,
346 new Authorizations(SYSTEM_LABEL));
347 s.setFilter(filter);
348 ArrayList<String> auths = new ArrayList<String>();
349 RegionScanner scanner = this.labelsRegion.getScanner(s);
350 try {
351 List<Cell> results = new ArrayList<Cell>(1);
352 while (true) {
353 scanner.next(results);
354 if (results.isEmpty()) break;
355 Cell cell = results.get(0);
356 int ordinal = Bytes.toInt(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength());
357 String label = this.labelsCache.getLabel(ordinal);
358 if (label != null) {
359 auths.add(label);
360 }
361 results.clear();
362 }
363 } finally {
364 scanner.close();
365 }
366 return auths;
367 }
368
369 @Override
370 public List<String> getGroupAuths(String[] groups, boolean systemCall)
371 throws IOException {
372 assert (labelsRegion != null || systemCall);
373 if (systemCall || labelsRegion == null) {
374 return this.labelsCache.getGroupAuths(groups);
375 }
376 Scan s = new Scan();
377 if (groups != null && groups.length > 0) {
378 for (String group : groups) {
379 s.addColumn(LABELS_TABLE_FAMILY, Bytes.toBytes(AccessControlLists.toGroupEntry(group)));
380 }
381 }
382 Filter filter = VisibilityUtils.createVisibilityLabelFilter(this.labelsRegion,
383 new Authorizations(SYSTEM_LABEL));
384 s.setFilter(filter);
385 Set<String> auths = new HashSet<String>();
386 RegionScanner scanner = this.labelsRegion.getScanner(s);
387 try {
388 List<Cell> results = new ArrayList<Cell>(1);
389 while (true) {
390 scanner.next(results);
391 if (results.isEmpty()) break;
392 Cell cell = results.get(0);
393 int ordinal = Bytes.toInt(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength());
394 String label = this.labelsCache.getLabel(ordinal);
395 if (label != null) {
396 auths.add(label);
397 }
398 results.clear();
399 }
400 } finally {
401 scanner.close();
402 }
403 return new ArrayList<String>(auths);
404 }
405
406 @Override
407 public List<String> listLabels(String regex) throws IOException {
408 assert (labelsRegion != null);
409 Pair<Map<String, Integer>, Map<String, List<Integer>>> labelsAndUserAuths =
410 extractLabelsAndAuths(getExistingLabelsWithAuths());
411 Map<String, Integer> labels = labelsAndUserAuths.getFirst();
412 labels.remove(SYSTEM_LABEL);
413 if (regex != null) {
414 Pattern pattern = Pattern.compile(regex);
415 ArrayList<String> matchedLabels = new ArrayList<String>();
416 for (String label : labels.keySet()) {
417 if (pattern.matcher(label).matches()) {
418 matchedLabels.add(label);
419 }
420 }
421 return matchedLabels;
422 }
423 return new ArrayList<String>(labels.keySet());
424 }
425
426 @Override
427 public List<Tag> createVisibilityExpTags(String visExpression, boolean withSerializationFormat,
428 boolean checkAuths) throws IOException {
429 Set<Integer> auths = new HashSet<Integer>();
430 if (checkAuths) {
431 User user = VisibilityUtils.getActiveUser();
432 auths.addAll(this.labelsCache.getUserAuthsAsOrdinals(user.getShortName()));
433 auths.addAll(this.labelsCache.getGroupAuthsAsOrdinals(user.getGroupNames()));
434 }
435 return VisibilityUtils.createVisibilityExpTags(visExpression, withSerializationFormat,
436 checkAuths, auths, labelsCache);
437 }
438
439 protected void updateZk(boolean labelAddition) throws IOException {
440
441
442
443
444 Pair<Map<String, Integer>, Map<String, List<Integer>>> labelsAndUserAuths =
445 extractLabelsAndAuths(getExistingLabelsWithAuths());
446 Map<String, Integer> existingLabels = labelsAndUserAuths.getFirst();
447 Map<String, List<Integer>> userAuths = labelsAndUserAuths.getSecond();
448 if (labelAddition) {
449 byte[] serialized = VisibilityUtils.getDataToWriteToZooKeeper(existingLabels);
450 this.labelsCache.writeToZookeeper(serialized, true);
451 } else {
452 byte[] serialized = VisibilityUtils.getUserAuthsDataToWriteToZooKeeper(userAuths);
453 this.labelsCache.writeToZookeeper(serialized, false);
454 }
455 }
456
457 @Override
458 public VisibilityExpEvaluator getVisibilityExpEvaluator(Authorizations authorizations)
459 throws IOException {
460
461
462 if (isReadFromSystemAuthUser()) {
463 return new VisibilityExpEvaluator() {
464 @Override
465 public boolean evaluate(Cell cell) throws IOException {
466 return true;
467 }
468 };
469 }
470 List<String> authLabels = null;
471 for (ScanLabelGenerator scanLabelGenerator : scanLabelGenerators) {
472 try {
473
474 authLabels = scanLabelGenerator.getLabels(VisibilityUtils.getActiveUser(), authorizations);
475 authLabels = (authLabels == null) ? new ArrayList<String>() : authLabels;
476 authorizations = new Authorizations(authLabels);
477 } catch (Throwable t) {
478 LOG.error(t);
479 throw new IOException(t);
480 }
481 }
482 int labelsCount = this.labelsCache.getLabelsCount();
483 final BitSet bs = new BitSet(labelsCount + 1);
484 if (authLabels != null) {
485 for (String authLabel : authLabels) {
486 int labelOrdinal = this.labelsCache.getLabelOrdinal(authLabel);
487 if (labelOrdinal != 0) {
488 bs.set(labelOrdinal);
489 }
490 }
491 }
492
493 return new VisibilityExpEvaluator() {
494 @Override
495 public boolean evaluate(Cell cell) throws IOException {
496 boolean visibilityTagPresent = false;
497
498 if (cell.getTagsLength() > 0) {
499 Iterator<Tag> tagsItr = CellUtil.tagsIterator(cell.getTagsArray(), cell.getTagsOffset(),
500 cell.getTagsLength());
501 while (tagsItr.hasNext()) {
502 boolean includeKV = true;
503 Tag tag = tagsItr.next();
504 if (tag.getType() == VISIBILITY_TAG_TYPE) {
505 visibilityTagPresent = true;
506 int offset = tag.getTagOffset();
507 int endOffset = offset + tag.getTagLength();
508 while (offset < endOffset) {
509 Pair<Integer, Integer> result = StreamUtils
510 .readRawVarint32(tag.getBuffer(), offset);
511 int currLabelOrdinal = result.getFirst();
512 if (currLabelOrdinal < 0) {
513
514
515 int temp = -currLabelOrdinal;
516 if (bs.get(temp)) {
517 includeKV = false;
518 break;
519 }
520 } else {
521 if (!bs.get(currLabelOrdinal)) {
522 includeKV = false;
523 break;
524 }
525 }
526 offset += result.getSecond();
527 }
528 if (includeKV) {
529
530
531 return true;
532 }
533 }
534 }
535 }
536 return !(visibilityTagPresent);
537 }
538 };
539 }
540
541 protected boolean isReadFromSystemAuthUser() throws IOException {
542 User user = VisibilityUtils.getActiveUser();
543 return havingSystemAuth(user);
544 }
545
546 @Override
547 @Deprecated
548 public boolean havingSystemAuth(byte[] user) throws IOException {
549
550 if (this.superUsers.contains(Bytes.toString(user))) {
551 return true;
552 }
553 List<String> auths = this.getUserAuths(user, true);
554 if (LOG.isTraceEnabled()) {
555 LOG.trace("The auths for user " + Bytes.toString(user) + " are " + auths);
556 }
557 return auths.contains(SYSTEM_LABEL);
558 }
559
560 @Override
561 public boolean havingSystemAuth(User user) throws IOException {
562
563 if (isSystemOrSuperUser(user)) {
564 return true;
565 }
566
567 List<String> auths = this.getUserAuths(Bytes.toBytes(user.getShortName()), true);
568 if (LOG.isTraceEnabled()) {
569 LOG.trace("The auths for user " + user.getShortName() + " are " + auths);
570 }
571 if (auths.contains(SYSTEM_LABEL)) {
572 return true;
573 }
574 auths = this.getGroupAuths(user.getGroupNames(), true);
575 if (LOG.isTraceEnabled()) {
576 LOG.trace("The auths for groups of user " + user.getShortName() + " are " + auths);
577 }
578 return auths.contains(SYSTEM_LABEL);
579 }
580
581 private boolean isSystemOrSuperUser(User user) throws IOException {
582 if (this.superUsers.contains(user.getShortName())) {
583 return true;
584 }
585 String[] groups = user.getGroupNames();
586 if (groups != null && groups.length > 0) {
587 for (String group : groups) {
588 if (this.superGroups.contains(group)) {
589 return true;
590 }
591 }
592 }
593 return false;
594 }
595
596 @Override
597 public boolean matchVisibility(List<Tag> putVisTags, Byte putTagsFormat, List<Tag> deleteVisTags,
598 Byte deleteTagsFormat) throws IOException {
599 if ((deleteTagsFormat != null && deleteTagsFormat == SORTED_ORDINAL_SERIALIZATION_FORMAT)
600 && (putTagsFormat == null || putTagsFormat == SORTED_ORDINAL_SERIALIZATION_FORMAT)) {
601 if (putVisTags.size() == 0) {
602
603 return false;
604 }
605 if (putTagsFormat == null) {
606 return matchUnSortedVisibilityTags(putVisTags, deleteVisTags);
607 } else {
608 return matchOrdinalSortedVisibilityTags(putVisTags, deleteVisTags);
609 }
610 }
611 throw new IOException("Unexpected tag format passed for comparison, deleteTagsFormat : "
612 + deleteTagsFormat + ", putTagsFormat : " + putTagsFormat);
613 }
614
615
616
617
618
619
620
621 private static boolean matchUnSortedVisibilityTags(List<Tag> putVisTags,
622 List<Tag> deleteVisTags) throws IOException {
623 return compareTagsOrdinals(sortTagsBasedOnOrdinal(putVisTags),
624 sortTagsBasedOnOrdinal(deleteVisTags));
625 }
626
627
628
629
630
631
632
633 private static boolean matchOrdinalSortedVisibilityTags(List<Tag> putVisTags,
634 List<Tag> deleteVisTags) {
635 boolean matchFound = false;
636
637 if ((deleteVisTags.size()) == putVisTags.size()) {
638 for (Tag tag : deleteVisTags) {
639 matchFound = false;
640 for (Tag givenTag : putVisTags) {
641 if (Bytes.equals(tag.getBuffer(), tag.getTagOffset(), tag.getTagLength(),
642 givenTag.getBuffer(), givenTag.getTagOffset(), givenTag.getTagLength())) {
643 matchFound = true;
644 break;
645 }
646 }
647 if (!matchFound) break;
648 }
649 }
650 return matchFound;
651 }
652
653 private static List<List<Integer>> sortTagsBasedOnOrdinal(List<Tag> tags) throws IOException {
654 List<List<Integer>> fullTagsList = new ArrayList<List<Integer>>();
655 for (Tag tag : tags) {
656 if (tag.getType() == VISIBILITY_TAG_TYPE) {
657 getSortedTagOrdinals(fullTagsList, tag);
658 }
659 }
660 return fullTagsList;
661 }
662
663 private static void getSortedTagOrdinals(List<List<Integer>> fullTagsList, Tag tag)
664 throws IOException {
665 List<Integer> tagsOrdinalInSortedOrder = new ArrayList<Integer>();
666 int offset = tag.getTagOffset();
667 int endOffset = offset + tag.getTagLength();
668 while (offset < endOffset) {
669 Pair<Integer, Integer> result = StreamUtils.readRawVarint32(tag.getBuffer(), offset);
670 tagsOrdinalInSortedOrder.add(result.getFirst());
671 offset += result.getSecond();
672 }
673 Collections.sort(tagsOrdinalInSortedOrder);
674 fullTagsList.add(tagsOrdinalInSortedOrder);
675 }
676
677
678
679
680 private static boolean compareTagsOrdinals(List<List<Integer>> putVisTags,
681 List<List<Integer>> deleteVisTags) {
682 boolean matchFound = false;
683 if (deleteVisTags.size() == putVisTags.size()) {
684 for (List<Integer> deleteTagOrdinals : deleteVisTags) {
685 matchFound = false;
686 for (List<Integer> tagOrdinals : putVisTags) {
687 if (deleteTagOrdinals.equals(tagOrdinals)) {
688 matchFound = true;
689 break;
690 }
691 }
692 if (!matchFound) break;
693 }
694 }
695 return matchFound;
696 }
697
698 @Override
699 public byte[] encodeVisibilityForReplication(final List<Tag> tags, final Byte serializationFormat)
700 throws IOException {
701 if (tags.size() > 0
702 && (serializationFormat == null ||
703 serializationFormat == SORTED_ORDINAL_SERIALIZATION_FORMAT)) {
704 return createModifiedVisExpression(tags);
705 }
706 return null;
707 }
708
709
710
711
712
713
714 private byte[] createModifiedVisExpression(final List<Tag> tags)
715 throws IOException {
716 StringBuilder visibilityString = new StringBuilder();
717 for (Tag tag : tags) {
718 if (tag.getType() == TagType.VISIBILITY_TAG_TYPE) {
719 if (visibilityString.length() != 0) {
720 visibilityString.append(VisibilityConstants.CLOSED_PARAN).append(
721 VisibilityConstants.OR_OPERATOR);
722 }
723 int offset = tag.getTagOffset();
724 int endOffset = offset + tag.getTagLength();
725 boolean expressionStart = true;
726 while (offset < endOffset) {
727 Pair<Integer, Integer> result = StreamUtils.readRawVarint32(tag.getBuffer(), offset);
728 int currLabelOrdinal = result.getFirst();
729 if (currLabelOrdinal < 0) {
730 int temp = -currLabelOrdinal;
731 String label = this.labelsCache.getLabel(temp);
732 if (expressionStart) {
733
734 visibilityString.append(VisibilityConstants.OPEN_PARAN)
735 .append(VisibilityConstants.NOT_OPERATOR).append(CellVisibility.quote(label));
736 } else {
737 visibilityString.append(VisibilityConstants.AND_OPERATOR)
738 .append(VisibilityConstants.NOT_OPERATOR).append(CellVisibility.quote(label));
739 }
740 } else {
741 String label = this.labelsCache.getLabel(currLabelOrdinal);
742 if (expressionStart) {
743 visibilityString.append(VisibilityConstants.OPEN_PARAN).append(
744 CellVisibility.quote(label));
745 } else {
746 visibilityString.append(VisibilityConstants.AND_OPERATOR).append(
747 CellVisibility.quote(label));
748 }
749 }
750 expressionStart = false;
751 offset += result.getSecond();
752 }
753 }
754 }
755 if (visibilityString.length() != 0) {
756 visibilityString.append(VisibilityConstants.CLOSED_PARAN);
757
758 return Bytes.toBytes(visibilityString.toString());
759 }
760 return null;
761 }
762 }