Do not allow recursive Namespace registration
[controller.git] / third-party / atomix / storage / src / main / java / io / atomix / utils / serializer / Namespace.java
1 /*
2  * Copyright 2014-present Open Networking Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package io.atomix.utils.serializer;
17
18 import com.esotericsoftware.kryo.Kryo;
19 import com.esotericsoftware.kryo.Registration;
20 import com.esotericsoftware.kryo.Serializer;
21 import com.esotericsoftware.kryo.io.ByteBufferInput;
22 import com.esotericsoftware.kryo.io.ByteBufferOutput;
23 import com.esotericsoftware.kryo.pool.KryoCallback;
24 import com.esotericsoftware.kryo.pool.KryoFactory;
25 import com.esotericsoftware.kryo.pool.KryoPool;
26 import com.esotericsoftware.kryo.serializers.CompatibleFieldSerializer;
27 import com.google.common.base.MoreObjects;
28 import com.google.common.collect.ImmutableList;
29 import org.apache.commons.lang3.tuple.Pair;
30 import org.objenesis.strategy.StdInstantiatorStrategy;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 import java.io.ByteArrayInputStream;
35 import java.io.InputStream;
36 import java.io.OutputStream;
37 import java.nio.ByteBuffer;
38 import java.util.ArrayList;
39 import java.util.Arrays;
40 import java.util.List;
41 import java.util.Objects;
42
43 import static java.util.Objects.requireNonNull;
44
45 /**
46  * Pool of Kryo instances, with classes pre-registered.
47  */
48 //@ThreadSafe
49 public final class Namespace implements KryoFactory, KryoPool {
50
51   /**
52    * Default buffer size used for serialization.
53    *
54    * @see #serialize(Object)
55    */
56   public static final int DEFAULT_BUFFER_SIZE = 4096;
57
58   /**
59    * Maximum allowed buffer size.
60    */
61   public static final int MAX_BUFFER_SIZE = 100 * 1000 * 1000;
62
63   /**
64    * ID to use if this KryoNamespace does not define registration id.
65    */
66   public static final int FLOATING_ID = -1;
67
68   /**
69    * Smallest ID free to use for user defined registrations.
70    */
71   public static final int INITIAL_ID = 16;
72
73   static final String NO_NAME = "(no name)";
74
75   private static final Logger LOGGER = LoggerFactory.getLogger(Namespace.class);
76
77   /**
78    * Default Kryo namespace.
79    */
80   public static final Namespace DEFAULT = builder().build();
81
82   private final KryoPool kryoPool = new KryoPool.Builder(this)
83       .softReferences()
84       .build();
85
86   private final KryoOutputPool kryoOutputPool = new KryoOutputPool();
87   private final KryoInputPool kryoInputPool = new KryoInputPool();
88
89   private final ImmutableList<RegistrationBlock> registeredBlocks;
90
91   private final ClassLoader classLoader;
92   private final boolean compatible;
93   private final boolean registrationRequired;
94   private final String friendlyName;
95
96   /**
97    * KryoNamespace builder.
98    */
99   //@NotThreadSafe
100   public static final class Builder {
101     private int blockHeadId = INITIAL_ID;
102     private List<Pair<Class<?>[], Serializer<?>>> types = new ArrayList<>();
103     private List<RegistrationBlock> blocks = new ArrayList<>();
104     private ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
105     private boolean registrationRequired = true;
106     private boolean compatible = false;
107
108     /**
109      * Builds a {@link Namespace} instance.
110      *
111      * @return KryoNamespace
112      */
113     public Namespace build() {
114       return build(NO_NAME);
115     }
116
117     /**
118      * Builds a {@link Namespace} instance.
119      *
120      * @param friendlyName friendly name for the namespace
121      * @return KryoNamespace
122      */
123     public Namespace build(String friendlyName) {
124       if (!types.isEmpty()) {
125         blocks.add(new RegistrationBlock(this.blockHeadId, types));
126       }
127       return new Namespace(blocks, classLoader, registrationRequired, compatible, friendlyName).populate(1);
128     }
129
130     /**
131      * Sets the next Kryo registration Id for following register entries.
132      *
133      * @param id Kryo registration Id
134      * @return this
135      * @see Kryo#register(Class, Serializer, int)
136      */
137     public Builder nextId(final int id) {
138       if (!types.isEmpty()) {
139         if (id != FLOATING_ID && id < blockHeadId + types.size()) {
140
141           if (LOGGER.isWarnEnabled()) {
142             LOGGER.warn("requested nextId {} could potentially overlap "
143                     + "with existing registrations {}+{} ",
144                 id, blockHeadId, types.size(), new RuntimeException());
145           }
146         }
147         blocks.add(new RegistrationBlock(this.blockHeadId, types));
148         types = new ArrayList<>();
149       }
150       this.blockHeadId = id;
151       return this;
152     }
153
154     /**
155      * Registers classes to be serialized using Kryo default serializer.
156      *
157      * @param expectedTypes list of classes
158      * @return this
159      */
160     public Builder register(final Class<?>... expectedTypes) {
161       for (Class<?> clazz : expectedTypes) {
162         types.add(Pair.of(new Class<?>[]{clazz}, null));
163       }
164       return this;
165     }
166
167     /**
168      * Registers serializer for the given set of classes.
169      * <p>
170      * When multiple classes are registered with an explicitly provided serializer, the namespace guarantees
171      * all instances will be serialized with the same type ID.
172      *
173      * @param classes    list of classes to register
174      * @param serializer serializer to use for the class
175      * @return this
176      */
177     public Builder register(Serializer<?> serializer, final Class<?>... classes) {
178       types.add(Pair.of(classes, requireNonNull(serializer)));
179       return this;
180     }
181
182     /**
183      * Sets the namespace class loader.
184      *
185      * @param classLoader the namespace class loader
186      * @return the namespace builder
187      */
188     public Builder setClassLoader(ClassLoader classLoader) {
189       this.classLoader = classLoader;
190       return this;
191     }
192
193     /**
194      * Sets whether backwards/forwards compatible versioned serialization is enabled.
195      * <p>
196      * When compatible serialization is enabled, the {@link CompatibleFieldSerializer} will be set as the
197      * default serializer for types that do not otherwise explicitly specify a serializer.
198      *
199      * @param compatible whether versioned serialization is enabled
200      * @return this
201      */
202     public Builder setCompatible(boolean compatible) {
203       this.compatible = compatible;
204       return this;
205     }
206
207     /**
208      * Sets the registrationRequired flag.
209      *
210      * @param registrationRequired Kryo's registrationRequired flag
211      * @return this
212      * @see Kryo#setRegistrationRequired(boolean)
213      */
214     public Builder setRegistrationRequired(boolean registrationRequired) {
215       this.registrationRequired = registrationRequired;
216       return this;
217     }
218   }
219
220   /**
221    * Creates a new {@link Namespace} builder.
222    *
223    * @return builder
224    */
225   public static Builder builder() {
226     return new Builder();
227   }
228
229   /**
230    * Creates a Kryo instance pool.
231    *
232    * @param registeredTypes      types to register
233    * @param registrationRequired whether registration is required
234    * @param compatible           whether compatible serialization is enabled
235    * @param friendlyName         friendly name for the namespace
236    */
237   private Namespace(
238       final List<RegistrationBlock> registeredTypes,
239       ClassLoader classLoader,
240       boolean registrationRequired,
241       boolean compatible,
242       String friendlyName) {
243     this.registeredBlocks = ImmutableList.copyOf(registeredTypes);
244     this.registrationRequired = registrationRequired;
245     this.classLoader = classLoader;
246     this.compatible = compatible;
247     this.friendlyName = requireNonNull(friendlyName);
248   }
249
250   /**
251    * Populates the Kryo pool.
252    *
253    * @param instances to add to the pool
254    * @return this
255    */
256   public Namespace populate(int instances) {
257
258     for (int i = 0; i < instances; ++i) {
259       release(create());
260     }
261     return this;
262   }
263
264   /**
265    * Serializes given object to byte array using Kryo instance in pool.
266    * <p>
267    * Note: Serialized bytes must be smaller than {@link #MAX_BUFFER_SIZE}.
268    *
269    * @param obj Object to serialize
270    * @return serialized bytes
271    */
272   public byte[] serialize(final Object obj) {
273     return serialize(obj, DEFAULT_BUFFER_SIZE);
274   }
275
276   /**
277    * Serializes given object to byte array using Kryo instance in pool.
278    *
279    * @param obj        Object to serialize
280    * @param bufferSize maximum size of serialized bytes
281    * @return serialized bytes
282    */
283   public byte[] serialize(final Object obj, final int bufferSize) {
284     return kryoOutputPool.run(output -> {
285       return kryoPool.run(kryo -> {
286         kryo.writeClassAndObject(output, obj);
287         output.flush();
288         return output.getByteArrayOutputStream().toByteArray();
289       });
290     }, bufferSize);
291   }
292
293   /**
294    * Serializes given object to byte buffer using Kryo instance in pool.
295    *
296    * @param obj    Object to serialize
297    * @param buffer to write to
298    */
299   public void serialize(final Object obj, final ByteBuffer buffer) {
300     ByteBufferOutput out = new ByteBufferOutput(buffer);
301     Kryo kryo = borrow();
302     try {
303       kryo.writeClassAndObject(out, obj);
304       out.flush();
305     } finally {
306       release(kryo);
307     }
308   }
309
310   /**
311    * Serializes given object to OutputStream using Kryo instance in pool.
312    *
313    * @param obj    Object to serialize
314    * @param stream to write to
315    */
316   public void serialize(final Object obj, final OutputStream stream) {
317     serialize(obj, stream, DEFAULT_BUFFER_SIZE);
318   }
319
320   /**
321    * Serializes given object to OutputStream using Kryo instance in pool.
322    *
323    * @param obj        Object to serialize
324    * @param stream     to write to
325    * @param bufferSize size of the buffer in front of the stream
326    */
327   public void serialize(final Object obj, final OutputStream stream, final int bufferSize) {
328     ByteBufferOutput out = new ByteBufferOutput(stream, bufferSize);
329     Kryo kryo = borrow();
330     try {
331       kryo.writeClassAndObject(out, obj);
332       out.flush();
333     } finally {
334       release(kryo);
335     }
336   }
337
338   /**
339    * Deserializes given byte array to Object using Kryo instance in pool.
340    *
341    * @param bytes serialized bytes
342    * @param <T>   deserialized Object type
343    * @return deserialized Object
344    */
345   public <T> T deserialize(final byte[] bytes) {
346     return kryoInputPool.run(input -> {
347       input.setInputStream(new ByteArrayInputStream(bytes));
348       return kryoPool.run(kryo -> {
349         @SuppressWarnings("unchecked")
350         T obj = (T) kryo.readClassAndObject(input);
351         return obj;
352       });
353     }, DEFAULT_BUFFER_SIZE);
354   }
355
356   /**
357    * Deserializes given byte buffer to Object using Kryo instance in pool.
358    *
359    * @param buffer input with serialized bytes
360    * @param <T>    deserialized Object type
361    * @return deserialized Object
362    */
363   public <T> T deserialize(final ByteBuffer buffer) {
364     ByteBufferInput in = new ByteBufferInput(buffer);
365     Kryo kryo = borrow();
366     try {
367       @SuppressWarnings("unchecked")
368       T obj = (T) kryo.readClassAndObject(in);
369       return obj;
370     } finally {
371       release(kryo);
372     }
373   }
374
375   /**
376    * Deserializes given InputStream to an Object using Kryo instance in pool.
377    *
378    * @param stream input stream
379    * @param <T>    deserialized Object type
380    * @return deserialized Object
381    */
382   public <T> T deserialize(final InputStream stream) {
383     return deserialize(stream, DEFAULT_BUFFER_SIZE);
384   }
385
386   /**
387    * Deserializes given InputStream to an Object using Kryo instance in pool.
388    *
389    * @param stream     input stream
390    * @param <T>        deserialized Object type
391    * @param bufferSize size of the buffer in front of the stream
392    * @return deserialized Object
393    */
394   public <T> T deserialize(final InputStream stream, final int bufferSize) {
395     ByteBufferInput in = new ByteBufferInput(stream, bufferSize);
396     Kryo kryo = borrow();
397     try {
398       @SuppressWarnings("unchecked")
399       T obj = (T) kryo.readClassAndObject(in);
400       return obj;
401     } finally {
402       release(kryo);
403     }
404   }
405
406   private String friendlyName() {
407     return friendlyName;
408   }
409
410   /**
411    * Gets the number of classes registered in this Kryo namespace.
412    *
413    * @return size of namespace
414    */
415   public int size() {
416     return (int) registeredBlocks.stream()
417         .flatMap(block -> block.types().stream())
418         .count();
419   }
420
421   /**
422    * Creates a Kryo instance.
423    *
424    * @return Kryo instance
425    */
426   @Override
427   public Kryo create() {
428     LOGGER.trace("Creating Kryo instance for {}", this);
429     Kryo kryo = new Kryo();
430     kryo.setClassLoader(classLoader);
431     kryo.setRegistrationRequired(registrationRequired);
432
433     // If compatible serialization is enabled, override the default serializer.
434     if (compatible) {
435       kryo.setDefaultSerializer(CompatibleFieldSerializer::new);
436     }
437
438     // TODO rethink whether we want to use StdInstantiatorStrategy
439     kryo.setInstantiatorStrategy(
440         new Kryo.DefaultInstantiatorStrategy(new StdInstantiatorStrategy()));
441
442     for (RegistrationBlock block : registeredBlocks) {
443       int id = block.begin();
444       if (id == FLOATING_ID) {
445         id = kryo.getNextRegistrationId();
446       }
447       for (Pair<Class<?>[], Serializer<?>> entry : block.types()) {
448         register(kryo, entry.getLeft(), entry.getRight(), id++);
449       }
450     }
451     return kryo;
452   }
453
454   /**
455    * Register {@code type} and {@code serializer} to {@code kryo} instance.
456    *
457    * @param kryo       Kryo instance
458    * @param types      types to register
459    * @param serializer Specific serializer to register or null to use default.
460    * @param id         type registration id to use
461    */
462   private void register(Kryo kryo, Class<?>[] types, Serializer<?> serializer, int id) {
463     Registration existing = kryo.getRegistration(id);
464     if (existing != null) {
465       boolean matches = false;
466       for (Class<?> type : types) {
467         if (existing.getType() == type) {
468           matches = true;
469           break;
470         }
471       }
472
473       if (!matches) {
474         LOGGER.error("{}: Failed to register {} as {}, {} was already registered.",
475             friendlyName(), types, id, existing.getType());
476
477         throw new IllegalStateException(String.format(
478             "Failed to register %s as %s, %s was already registered.",
479             Arrays.toString(types), id, existing.getType()));
480       }
481       // falling through to register call for now.
482       // Consider skipping, if there's reasonable
483       // way to compare serializer equivalence.
484     }
485
486     for (Class<?> type : types) {
487       Registration r = null;
488       if (serializer == null) {
489         r = kryo.register(type, id);
490       } else if (type.isInterface()) {
491         kryo.addDefaultSerializer(type, serializer);
492       } else {
493         r = kryo.register(type, serializer, id);
494       }
495       if (r != null) {
496         if (r.getId() != id) {
497           LOGGER.debug("{}: {} already registered as {}. Skipping {}.",
498               friendlyName(), r.getType(), r.getId(), id);
499         }
500         LOGGER.trace("{} registered as {}", r.getType(), r.getId());
501       }
502     }
503   }
504
505   @Override
506   public Kryo borrow() {
507     return kryoPool.borrow();
508   }
509
510   @Override
511   public void release(Kryo kryo) {
512     kryoPool.release(kryo);
513   }
514
515   @Override
516   public <T> T run(KryoCallback<T> callback) {
517     return kryoPool.run(callback);
518   }
519
520   @Override
521   public String toString() {
522     if (!NO_NAME.equals(friendlyName)) {
523       return MoreObjects.toStringHelper(getClass())
524           .omitNullValues()
525           .add("friendlyName", friendlyName)
526           // omit lengthy detail, when there's a name
527           .toString();
528     }
529     return MoreObjects.toStringHelper(getClass())
530         .add("registeredBlocks", registeredBlocks)
531         .toString();
532   }
533
534   static final class RegistrationBlock {
535     private final int begin;
536     private final ImmutableList<Pair<Class<?>[], Serializer<?>>> types;
537
538     RegistrationBlock(int begin, List<Pair<Class<?>[], Serializer<?>>> types) {
539       this.begin = begin;
540       this.types = ImmutableList.copyOf(types);
541     }
542
543     public int begin() {
544       return begin;
545     }
546
547     public ImmutableList<Pair<Class<?>[], Serializer<?>>> types() {
548       return types;
549     }
550
551     @Override
552     public String toString() {
553       return MoreObjects.toStringHelper(getClass())
554           .add("begin", begin)
555           .add("types", types)
556           .toString();
557     }
558
559     @Override
560     public int hashCode() {
561       return types.hashCode();
562     }
563
564     // Only the registered types are used for equality.
565     @Override
566     public boolean equals(Object obj) {
567       if (this == obj) {
568         return true;
569       }
570
571       if (obj instanceof RegistrationBlock) {
572         RegistrationBlock that = (RegistrationBlock) obj;
573         return Objects.equals(this.types, that.types);
574       }
575       return false;
576     }
577   }
578 }