Fixup javadoc
[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.google.common.base.MoreObjects;
27 import com.google.common.collect.ImmutableList;
28 import org.objenesis.strategy.StdInstantiatorStrategy;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 import java.io.ByteArrayInputStream;
33 import java.io.InputStream;
34 import java.io.OutputStream;
35 import java.nio.ByteBuffer;
36 import java.util.ArrayList;
37 import java.util.Arrays;
38 import java.util.List;
39 import java.util.Map;
40 import java.util.Map.Entry;
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    * ID to use if this KryoNamespace does not define registration id.
60    */
61   private static final int FLOATING_ID = -1;
62
63   /**
64    * Smallest ID free to use for user defined registrations.
65    */
66   private static final int INITIAL_ID = 16;
67
68   static final String NO_NAME = "(no name)";
69
70   private static final Logger LOGGER = LoggerFactory.getLogger(Namespace.class);
71
72   private final KryoPool kryoPool = new KryoPool.Builder(this).softReferences().build();
73
74   private final KryoOutputPool kryoOutputPool = new KryoOutputPool();
75   private final KryoInputPool kryoInputPool = new KryoInputPool();
76
77   private final ImmutableList<RegistrationBlock> registeredBlocks;
78
79   private final ClassLoader classLoader;
80   private final String friendlyName;
81
82   /**
83    * KryoNamespace builder.
84    */
85   //@NotThreadSafe
86   public static final class Builder {
87     private int blockHeadId = INITIAL_ID;
88     private List<Entry<Class<?>[], Serializer<?>>> types = new ArrayList<>();
89     private List<RegistrationBlock> blocks = new ArrayList<>();
90     private ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
91
92     /**
93      * Builds a {@link Namespace} instance.
94      *
95      * @return KryoNamespace
96      */
97     public Namespace build() {
98       return build(NO_NAME);
99     }
100
101     /**
102      * Builds a {@link Namespace} instance.
103      *
104      * @param friendlyName friendly name for the namespace
105      * @return KryoNamespace
106      */
107     public Namespace build(String friendlyName) {
108       if (!types.isEmpty()) {
109         blocks.add(new RegistrationBlock(this.blockHeadId, types));
110       }
111       return new Namespace(blocks, classLoader, friendlyName);
112     }
113
114     /**
115      * Registers serializer for the given set of classes.
116      * <p>
117      * When multiple classes are registered with an explicitly provided serializer, the namespace guarantees
118      * all instances will be serialized with the same type ID.
119      *
120      * @param classes    list of classes to register
121      * @param serializer serializer to use for the class
122      * @return this
123      */
124     public Builder register(Serializer<?> serializer, final Class<?>... classes) {
125       types.add(Map.entry(classes, serializer));
126       return this;
127     }
128
129     /**
130      * Sets the namespace class loader.
131      *
132      * @param classLoader the namespace class loader
133      * @return the namespace builder
134      */
135     public Builder setClassLoader(ClassLoader classLoader) {
136       this.classLoader = classLoader;
137       return this;
138     }
139   }
140
141   /**
142    * Creates a new {@link Namespace} builder.
143    *
144    * @return builder
145    */
146   public static Builder builder() {
147     return new Builder();
148   }
149
150   /**
151    * Creates a Kryo instance pool.
152    *
153    * @param registeredTypes      types to register
154    * @param registrationRequired whether registration is required
155    * @param friendlyName         friendly name for the namespace
156    */
157   private Namespace(
158       final List<RegistrationBlock> registeredTypes,
159       ClassLoader classLoader,
160       String friendlyName) {
161     this.registeredBlocks = ImmutableList.copyOf(registeredTypes);
162     this.classLoader = classLoader;
163     this.friendlyName = requireNonNull(friendlyName);
164
165     // Pre-populate with a single instance
166     release(create());
167   }
168
169   /**
170    * Serializes given object to byte array using Kryo instance in pool.
171    *
172    * @param obj Object to serialize
173    * @return serialized bytes
174    */
175   public byte[] serialize(final Object obj) {
176     return serialize(obj, DEFAULT_BUFFER_SIZE);
177   }
178
179   /**
180    * Serializes given object to byte array using Kryo instance in pool.
181    *
182    * @param obj        Object to serialize
183    * @param bufferSize maximum size of serialized bytes
184    * @return serialized bytes
185    */
186   public byte[] serialize(final Object obj, final int bufferSize) {
187     return kryoOutputPool.run(output -> {
188       return kryoPool.run(kryo -> {
189         kryo.writeClassAndObject(output, obj);
190         output.flush();
191         return output.getByteArrayOutputStream().toByteArray();
192       });
193     }, bufferSize);
194   }
195
196   /**
197    * Serializes given object to byte buffer using Kryo instance in pool.
198    *
199    * @param obj    Object to serialize
200    * @param buffer to write to
201    */
202   public void serialize(final Object obj, final ByteBuffer buffer) {
203     ByteBufferOutput out = new ByteBufferOutput(buffer);
204     Kryo kryo = borrow();
205     try {
206       kryo.writeClassAndObject(out, obj);
207       out.flush();
208     } finally {
209       release(kryo);
210     }
211   }
212
213   /**
214    * Serializes given object to OutputStream using Kryo instance in pool.
215    *
216    * @param obj    Object to serialize
217    * @param stream to write to
218    */
219   public void serialize(final Object obj, final OutputStream stream) {
220     serialize(obj, stream, DEFAULT_BUFFER_SIZE);
221   }
222
223   /**
224    * Serializes given object to OutputStream using Kryo instance in pool.
225    *
226    * @param obj        Object to serialize
227    * @param stream     to write to
228    * @param bufferSize size of the buffer in front of the stream
229    */
230   public void serialize(final Object obj, final OutputStream stream, final int bufferSize) {
231     ByteBufferOutput out = new ByteBufferOutput(stream, bufferSize);
232     Kryo kryo = borrow();
233     try {
234       kryo.writeClassAndObject(out, obj);
235       out.flush();
236     } finally {
237       release(kryo);
238     }
239   }
240
241   /**
242    * Deserializes given byte array to Object using Kryo instance in pool.
243    *
244    * @param bytes serialized bytes
245    * @param <T>   deserialized Object type
246    * @return deserialized Object
247    */
248   public <T> T deserialize(final byte[] bytes) {
249     return kryoInputPool.run(input -> {
250       input.setInputStream(new ByteArrayInputStream(bytes));
251       return kryoPool.run(kryo -> {
252         @SuppressWarnings("unchecked")
253         T obj = (T) kryo.readClassAndObject(input);
254         return obj;
255       });
256     }, DEFAULT_BUFFER_SIZE);
257   }
258
259   /**
260    * Deserializes given byte buffer to Object using Kryo instance in pool.
261    *
262    * @param buffer input with serialized bytes
263    * @param <T>    deserialized Object type
264    * @return deserialized Object
265    */
266   public <T> T deserialize(final ByteBuffer buffer) {
267     ByteBufferInput in = new ByteBufferInput(buffer);
268     Kryo kryo = borrow();
269     try {
270       @SuppressWarnings("unchecked")
271       T obj = (T) kryo.readClassAndObject(in);
272       return obj;
273     } finally {
274       release(kryo);
275     }
276   }
277
278   /**
279    * Deserializes given InputStream to an Object using Kryo instance in pool.
280    *
281    * @param stream input stream
282    * @param <T>    deserialized Object type
283    * @return deserialized Object
284    */
285   public <T> T deserialize(final InputStream stream) {
286     return deserialize(stream, DEFAULT_BUFFER_SIZE);
287   }
288
289   /**
290    * Deserializes given InputStream to an Object using Kryo instance in pool.
291    *
292    * @param stream     input stream
293    * @param <T>        deserialized Object type
294    * @param bufferSize size of the buffer in front of the stream
295    * @return deserialized Object
296    */
297   public <T> T deserialize(final InputStream stream, final int bufferSize) {
298     ByteBufferInput in = new ByteBufferInput(stream, bufferSize);
299     Kryo kryo = borrow();
300     try {
301       @SuppressWarnings("unchecked")
302       T obj = (T) kryo.readClassAndObject(in);
303       return obj;
304     } finally {
305       release(kryo);
306     }
307   }
308
309   /**
310    * Creates a Kryo instance.
311    *
312    * @return Kryo instance
313    */
314   @Override
315   public Kryo create() {
316     LOGGER.trace("Creating Kryo instance for {}", this);
317     Kryo kryo = new Kryo();
318     kryo.setClassLoader(classLoader);
319     kryo.setRegistrationRequired(true);
320
321     // TODO rethink whether we want to use StdInstantiatorStrategy
322     kryo.setInstantiatorStrategy(
323         new Kryo.DefaultInstantiatorStrategy(new StdInstantiatorStrategy()));
324
325     for (RegistrationBlock block : registeredBlocks) {
326       int id = block.begin();
327       if (id == FLOATING_ID) {
328         id = kryo.getNextRegistrationId();
329       }
330       for (Entry<Class<?>[], Serializer<?>> entry : block.types()) {
331         register(kryo, entry.getKey(), entry.getValue(), id++);
332       }
333     }
334     return kryo;
335   }
336
337   /**
338    * Register {@code type} and {@code serializer} to {@code kryo} instance.
339    *
340    * @param kryo       Kryo instance
341    * @param types      types to register
342    * @param serializer Specific serializer to register or null to use default.
343    * @param id         type registration id to use
344    */
345   private void register(Kryo kryo, Class<?>[] types, Serializer<?> serializer, int id) {
346     Registration existing = kryo.getRegistration(id);
347     if (existing != null) {
348       boolean matches = false;
349       for (Class<?> type : types) {
350         if (existing.getType() == type) {
351           matches = true;
352           break;
353         }
354       }
355
356       if (!matches) {
357         LOGGER.error("{}: Failed to register {} as {}, {} was already registered.",
358             friendlyName, types, id, existing.getType());
359
360         throw new IllegalStateException(String.format(
361             "Failed to register %s as %s, %s was already registered.",
362             Arrays.toString(types), id, existing.getType()));
363       }
364       // falling through to register call for now.
365       // Consider skipping, if there's reasonable
366       // way to compare serializer equivalence.
367     }
368
369     for (Class<?> type : types) {
370       Registration r = null;
371       if (serializer == null) {
372         r = kryo.register(type, id);
373       } else if (type.isInterface()) {
374         kryo.addDefaultSerializer(type, serializer);
375       } else {
376         r = kryo.register(type, serializer, id);
377       }
378       if (r != null) {
379         if (r.getId() != id) {
380           LOGGER.debug("{}: {} already registered as {}. Skipping {}.",
381               friendlyName, r.getType(), r.getId(), id);
382         }
383         LOGGER.trace("{} registered as {}", r.getType(), r.getId());
384       }
385     }
386   }
387
388   @Override
389   public Kryo borrow() {
390     return kryoPool.borrow();
391   }
392
393   @Override
394   public void release(Kryo kryo) {
395     kryoPool.release(kryo);
396   }
397
398   @Override
399   public <T> T run(KryoCallback<T> callback) {
400     return kryoPool.run(callback);
401   }
402
403   @Override
404   public String toString() {
405     if (!NO_NAME.equals(friendlyName)) {
406       return MoreObjects.toStringHelper(getClass())
407           .omitNullValues()
408           .add("friendlyName", friendlyName)
409           // omit lengthy detail, when there's a name
410           .toString();
411     }
412     return MoreObjects.toStringHelper(getClass())
413         .add("registeredBlocks", registeredBlocks)
414         .toString();
415   }
416
417   static final class RegistrationBlock {
418     private final int begin;
419     private final ImmutableList<Entry<Class<?>[], Serializer<?>>> types;
420
421     RegistrationBlock(int begin, List<Entry<Class<?>[], Serializer<?>>> types) {
422       this.begin = begin;
423       this.types = ImmutableList.copyOf(types);
424     }
425
426     public int begin() {
427       return begin;
428     }
429
430     public ImmutableList<Entry<Class<?>[], Serializer<?>>> types() {
431       return types;
432     }
433
434     @Override
435     public String toString() {
436       return MoreObjects.toStringHelper(getClass())
437           .add("begin", begin)
438           .add("types", types)
439           .toString();
440     }
441
442     @Override
443     public int hashCode() {
444       return types.hashCode();
445     }
446
447     // Only the registered types are used for equality.
448     @Override
449     public boolean equals(Object obj) {
450       if (this == obj) {
451         return true;
452       }
453
454       if (obj instanceof RegistrationBlock) {
455         RegistrationBlock that = (RegistrationBlock) obj;
456         return Objects.equals(this.types, that.types);
457       }
458       return false;
459     }
460   }
461 }