Debian Codegraph @

lang/java/src/com/sleepycat/persist/impl/PersistCatalog.java

raw
1 /*-
2 * See the file LICENSE for redistribution information.
3 *
4 * Copyright (c) 2002, 2013 Oracle and/or its affiliates. All rights reserved.
5 *
6 */
7
8 package com.sleepycat.persist.impl;
9
10 import java.io.ByteArrayInputStream;
11 import java.io.ByteArrayOutputStream;
12 import java.io.IOException;
13 import java.io.ObjectInputStream;
14 import java.io.ObjectOutputStream;
15 import java.io.Serializable;
16 import java.lang.reflect.Modifier;
17 import java.util.ArrayList;
18 import java.util.Collection;
19 import java.util.Collections;
20 import java.util.HashMap;
21 import java.util.HashSet;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.Set;
25
26 import com.sleepycat.bind.tuple.IntegerBinding;
27 import com.sleepycat.compat.DbCompat;
28 import com.sleepycat.db.Database;
29 import com.sleepycat.db.DatabaseConfig;
30 import com.sleepycat.db.DatabaseEntry;
31 import com.sleepycat.db.DatabaseException;
32 import com.sleepycat.db.DeadlockException;
33 import com.sleepycat.db.Environment;
34 import com.sleepycat.db.OperationStatus;
35 import com.sleepycat.db.Transaction;
36 import java.util.IdentityHashMap;
37 import com.sleepycat.persist.DatabaseNamer;
38 import com.sleepycat.persist.StoreExistsException;
39 import com.sleepycat.persist.StoreNotFoundException;
40 import com.sleepycat.persist.evolve.Converter;
41 import com.sleepycat.persist.evolve.IncompatibleClassException;
42 import com.sleepycat.persist.evolve.Mutations;
43 import com.sleepycat.persist.evolve.Renamer;
44 import com.sleepycat.persist.model.AnnotationModel;
45 import com.sleepycat.persist.model.ClassMetadata;
46 import com.sleepycat.persist.model.EntityMetadata;
47 import com.sleepycat.persist.model.EntityModel;
48 import com.sleepycat.persist.model.ModelInternal;
49 import com.sleepycat.persist.raw.RawObject;
50 import com.sleepycat.persist.raw.RawType;
51 import com.sleepycat.util.RuntimeExceptionWrapper;
52
53 /**
54 * The catalog of class formats for a store, along with its associated model
55 * and mutations.
56 *
57 * @author Mark Hayes
58 */
59 public class PersistCatalog implements Catalog {
60
61 private static final int MAX_TXN_RETRIES = 10;
62
63 /**
64 * Key to Data record in the catalog database. In the JE 3.0.12 beta
65 * version the formatList record is stored under this key and is converted
66 * to a Data object when it is read.
67 */
68 private static final byte[] DATA_KEY = getIntBytes(-1);
69
70 /**
71 * Key to a JE 3.0.12 beta version mutations record in the catalog
72 * database. This record is no longer used because mutations are stored in
73 * the Data record and is deleted when the beta version is detected.
74 */
75 private static final byte[] BETA_MUTATIONS_KEY = getIntBytes(-2);
76
77 private static byte[] getIntBytes(int val) {
78 DatabaseEntry entry = new DatabaseEntry();
79 IntegerBinding.intToEntry(val, entry);
80 assert entry.getSize() == 4 && entry.getData().length == 4;
81 return entry.getData();
82 }
83
84 /**
85 * Used by unit tests.
86 */
87 public static boolean expectNoClassChanges;
88 public static boolean unevolvedFormatsEncountered;
89
90 /**
91 * The object stored under DATA_KEY in the catalog database.
92 */
93 private static class Data implements Serializable {
94
95 static final long serialVersionUID = 7515058069137413261L;
96
97 List<Format> formatList;
98 Mutations mutations;
99 int version;
100 }
101
102 /**
103 * A list of all formats indexed by formatId. Element zero is unused and
104 * null, since IDs start at one; this avoids adjusting the ID to index the
105 * list. Some elements are null to account for predefined IDs that are not
106 * used.
107 *
108 * <p>This field, like formatMap, is volatile because it is reassigned
109 * when dynamically adding new formats. See {@link addNewFormat}.</p>
110 */
111 private volatile List<Format> formatList;
112
113 /**
114 * A map of the current/live formats in formatList, indexed by class name.
115 *
116 * <p>This field, like formatList, is volatile because it is reassigned
117 * when dynamically adding new formats. See {@link addNewFormat}.</p>
118 */
119 private volatile Map<String, Format> formatMap;
120
121 /**
122 * A map of the latest formats (includes deleted formats) in formatList,
123 * indexed by class name.
124 *
125 * <p>This field, like formatMap, is volatile because it is reassigned
126 * when dynamically adding new formats. See {@link addNewFormat}.</p>
127 */
128 private volatile Map<String, Format> latestFormatMap;
129
130 /**
131 * A temporary map of proxied class name to proxy class name. Used during
132 * catalog creation, and then set to null. This map is used to force proxy
133 * formats to be created prior to proxied formats. [#14665]
134 */
135 private Map<String, String> proxyClassMap;
136
137 private final Environment env;
138 private final boolean rawAccess;
139 private EntityModel model;
140 private StoredModel storedModel;
141 private Mutations mutations;
142 private final Database db;
143 private int openCount;
144 private boolean readOnly;
145 private final boolean transactional;
146
147 /**
148 * If a Replica is upgraded, local in-memory evolution may take place prior
149 * to the Master being upgraded. In that case, the size of the formatList
150 * will be greater than nStoredFormats. In this case, the readOnly
151 * state field will be set to true. We must be sure not to write the
152 * metadata in this state. [#16655]
153 */
154 private volatile int nStoredFormats;
155
156 /**
157 * The Store is normally present but may be null in unit tests (for
158 * example, BindingTest).
159 */
160 private final Store store;
161
162 /**
163 * The Evolver and catalog Data are non-null during catalog initialization,
164 * and null otherwise.
165 */
166 private Evolver initEvolver;
167 private Data initData;
168
169 /**
170 * Creates a new catalog, opening the database and reading it from a given
171 * catalog database if it already exists. All predefined formats and
172 * formats for the given model are added. For modified classes, old
173 * formats are defined based on the rules for compatible class changes and
174 * the given mutations. If any format is changed or added, and the
175 * database is not read-only, write the initialized catalog to the
176 * database.
177 */
178 public PersistCatalog(final Environment env,
179 final String storePrefix,
180 final String dbName,
181 final DatabaseConfig dbConfig,
182 final EntityModel modelParam,
183 final Mutations mutationsParam,
184 final boolean rawAccess,
185 final Store store)
186 throws StoreExistsException,
187 StoreNotFoundException,
188 IncompatibleClassException,
189 DatabaseException {
190
191 this.env = env;
192 this.rawAccess = rawAccess;
193 this.store = store;
194 this.transactional = dbConfig.getTransactional();
195
196 /* store may be null for testing. */
197 String[] fileAndDbNames = (store != null) ?
198 store.parseDbName(dbName) :
199 Store.parseDbName(dbName, DatabaseNamer.DEFAULT);
200
201 /*
202 * Use a null (auto-commit) transaction for opening the database, so
203 * that the database is opened even if a ReplicaWriteException occurs
204 * when attempting to evolve the metadata. We will close the database
205 * if another exception occurs in the finally statement below.
206 */
207 db = DbCompat.openDatabase(env, null /*txn*/, fileAndDbNames[0],
208 fileAndDbNames[1], dbConfig);
209 if (db == null) {
210 String dbNameMsg = store.getDbNameMessage(fileAndDbNames);
211 if (dbConfig.getExclusiveCreate()) {
212 throw new StoreExistsException
213 ("Catalog DB already exists and ExclusiveCreate=true, " +
214 dbNameMsg);
215 } else {
216 assert !dbConfig.getAllowCreate();
217 throw new StoreNotFoundException
218 ("Catalog DB does not exist and AllowCreate=false, " +
219 dbNameMsg);
220 }
221 }
222 openCount = 1;
223 boolean success = false;
224 try {
225 initAndRetry(storePrefix, modelParam, mutationsParam);
226 success = true;
227 } finally {
228 if (!success) {
229 close();
230 }
231 }
232 }
233
234 /**
235 * Creates a new catalog when a Replica refresh occurs. Uses some
236 * information from the old catalog directly in the new catalog, but all
237 * formats are created from scratch and class evolution is attempted.
238 */
239 PersistCatalog(final PersistCatalog oldCatalog, final String storePrefix)
240 throws DatabaseException {
241
242 db = oldCatalog.db;
243 store = oldCatalog.store;
244 env = oldCatalog.env;
245 rawAccess = oldCatalog.rawAccess;
246 openCount = oldCatalog.openCount;
247 transactional = oldCatalog.transactional;
248
249 initAndRetry(storePrefix, oldCatalog.model, oldCatalog.mutations);
250 }
251
252 private void initAndRetry(final String storePrefix,
253 final EntityModel modelParam,
254 final Mutations mutationsParam)
255 throws DatabaseException {
256
257 for (int i = 0;; i += 1) {
258 Transaction txn = null;
259 if (transactional && DbCompat.getThreadTransaction(env) == null) {
260 txn =
261 env.beginTransaction(null, store.getAutoCommitTxnConfig());
262 }
263 boolean success = false;
264 try {
265 init(txn, storePrefix, modelParam, mutationsParam);
266 success = true;
267 return;
268 } catch (DeadlockException e) {
269
270 /*
271 * It is very unlikely that two threads opening the same
272 * EntityStore will cause a lock conflict. However, because we
273 * read-modify-update the catalog record,
274 * LockPreemptedException must be handled in a replicated JE
275 * environment. Since LockPreemptedException is a
276 * LockConfictException, it is simplest to retry when any
277 * LockConfictException occurs.
278 */
279 if (i >= MAX_TXN_RETRIES) {
280 throw e;
281 }
282 continue;
283 } finally {
284
285 /*
286 * If the catalog is read-only we abort rather than commit,
287 * because a ReplicaWriteException may have occurred.
288 * ReplicaWriteException invalidates the transaction, and there
289 * are no writes to commit anyway. [#16655]
290 */
291 if (txn != null) {
292 if (success && !isReadOnly()) {
293 txn.commit();
294 } else {
295 txn.abort();
296 }
297 }
298 }
299 }
300 }
301
302 private void init(final Transaction txn,
303 final String storePrefix,
304 final EntityModel modelParam,
305 final Mutations mutationsParam)
306 throws DatabaseException {
307
308 try {
309 initData = readData(txn);
310 mutations = initData.mutations;
311 if (mutations == null) {
312 mutations = new Mutations();
313 }
314
315 /*
316 * When the beta version is detected, force a re-write of the
317 * catalog and disallow class changes. This brings the catalog up
318 * to date so that evolution can proceed correctly from then on.
319 */
320 boolean betaVersion = (initData.version == BETA_VERSION);
321 boolean needWrite = betaVersion;
322 boolean disallowClassChanges = betaVersion;
323
324 /*
325 * Store the given mutations if they are different from the stored
326 * mutations, and force evolution to apply the new mutations.
327 */
328 boolean forceEvolution = false;
329 if (mutationsParam != null &&
330 !mutations.equals(mutationsParam)) {
331 mutations = mutationsParam;
332 needWrite = true;
333 forceEvolution = true;
334 }
335
336 final ClassLoader envClassLoader = DbCompat.getClassLoader(env);
337
338 /* Get the existing format list, or copy it from SimpleCatalog. */
339 formatList = initData.formatList;
340 if (formatList == null) {
341 formatList = SimpleCatalog.getAllSimpleFormats(envClassLoader);
342
343 /*
344 * Special cases: Object and Number are predefined but are not
345 * simple types.
346 */
347 Format format = new NonPersistentFormat(this, Object.class);
348 format.setId(Format.ID_OBJECT);
349 formatList.set(Format.ID_OBJECT, format);
350 format = new NonPersistentFormat(this, Number.class);
351 format.setId(Format.ID_NUMBER);
352 formatList.set(Format.ID_NUMBER, format);
353 } else {
354 /* Pick up any new predefined simple types. */
355 if (SimpleCatalog.addMissingSimpleFormats(envClassLoader,
356 formatList)) {
357 needWrite = true;
358 }
359 nStoredFormats = formatList.size();
360 }
361
362 /* Initialize transient catalog field before further use. */
363 for (Format format : formatList) {
364 if (format != null) {
365 format.initCatalog(this);
366 }
367 }
368
369 /* Special handling for JE 3.0.12 beta formats. */
370 if (betaVersion) {
371 Map<String, Format> formatMap = new HashMap<String, Format>();
372 for (Format format : formatList) {
373 if (format != null) {
374 formatMap.put(format.getClassName(), format);
375 }
376 }
377 for (Format format : formatList) {
378 if (format != null) {
379 format.migrateFromBeta(formatMap);
380 }
381 }
382 }
383
384 /*
385 * If we should not use the current model, initialize the stored
386 * model and return.
387 */
388 formatMap = new HashMap<String, Format>(formatList.size());
389 latestFormatMap = new HashMap<String, Format>(formatList.size());
390 if (rawAccess) {
391 for (Format format : formatList) {
392 if (format != null) {
393 String name = format.getClassName();
394 if (format.isCurrentVersion()) {
395 formatMap.put(name, format);
396 }
397 if (format == format.getLatestVersion()) {
398 latestFormatMap.put(name, format);
399 }
400 }
401 }
402 if (modelParam != null) {
403 model = modelParam;
404 storedModel = (StoredModel) modelParam;
405 } else {
406 storedModel = new StoredModel(this);
407 model = storedModel;
408 }
409 ModelInternal.setClassLoader(model, envClassLoader);
410 for (Format format : formatList) {
411 if (format != null) {
412 format.initializeIfNeeded(this, model);
413 }
414 }
415 initModelAndMutations();
416 return;
417 }
418
419 /*
420 * We are opening a store that uses the current model. Default to
421 * the AnnotationModel if no model is specified.
422 */
423 if (modelParam != null) {
424 model = modelParam;
425 } else {
426 model = new AnnotationModel();
427 }
428 ModelInternal.setClassLoader(model, envClassLoader);
429 storedModel = null;
430
431 /*
432 * Add all predefined (simple) formats to the format map. The
433 * current version of other formats will be added below.
434 */
435 for (int i = 0; i <= Format.ID_PREDEFINED; i += 1) {
436 Format simpleFormat = formatList.get(i);
437 if (simpleFormat != null) {
438 formatMap.put(simpleFormat.getClassName(), simpleFormat);
439 }
440 }
441
442 /*
443 * Known classes are those explicitly registered by the user via
444 * the model, plus the predefined proxy classes.
445 */
446 List<String> knownClasses =
447 new ArrayList<String>(model.getKnownClasses());
448 /* Also adds the special classes, i.e., enum or array. [#19377] */
449 knownClasses.addAll(model.getKnownSpecialClasses());
450 addPredefinedProxies(knownClasses);
451
452 /*
453 * Create a temporary map of proxied class name to proxy class
454 * name, using all known formats and classes. This map is used to
455 * force proxy formats to be created prior to proxied formats.
456 * [#14665]
457 */
458 proxyClassMap = new HashMap<String, String>();
459 for (Format oldFormat : formatList) {
460 if (oldFormat == null || Format.isPredefined(oldFormat)) {
461 continue;
462 }
463 String oldName = oldFormat.getClassName();
464 Renamer renamer = mutations.getRenamer
465 (oldName, oldFormat.getVersion(), null);
466 String newName =
467 (renamer != null) ? renamer.getNewName() : oldName;
468 addProxiedClass(newName, false /*isKnownClass*/);
469 }
470 for (String className : knownClasses) {
471 addProxiedClass(className, true /*isKnownClass*/);
472 }
473
474 /*
475 * Add known formats from the model and the predefined proxies.
476 * In general, classes will not be present in an AnnotationModel
477 * until an instance is stored, in which case an old format exists.
478 * However, registered proxy classes are an exception and must be
479 * added in advance. And the user may choose to register new
480 * classes in advance. The more formats we define in advance, the
481 * less times we have to write to the catalog database.
482 */
483 Map<String, Format> newFormats = new HashMap<String, Format>();
484 for (String className : knownClasses) {
485 createFormat(className, newFormats);
486 }
487
488 /*
489 * Perform class evolution for all old formats, and throw an
490 * exception that contains the messages for all of the errors in
491 * mutations or in the definition of new classes.
492 */
493 initEvolver = new Evolver
494 (this, storePrefix, mutations, newFormats, forceEvolution,
495 disallowClassChanges);
496 for (Format oldFormat : formatList) {
497 if (oldFormat == null || Format.isPredefined(oldFormat)) {
498 continue;
499 }
500 if (oldFormat.isEntity()) {
501 initEvolver.evolveFormat(oldFormat);
502 } else {
503 initEvolver.addNonEntityFormat(oldFormat);
504 }
505 }
506 initEvolver.finishEvolution();
507 String errors = initEvolver.getErrors();
508 if (errors != null) {
509 throw new IncompatibleClassException(errors);
510 }
511
512 /*
513 * Add the new formats remaining. New formats that are equal to
514 * old formats were removed from the newFormats map above.
515 */
516 for (Format newFormat : newFormats.values()) {
517 addFormat(newFormat);
518 }
519
520 /* Initialize all formats. */
521 for (Format format : formatList) {
522 if (format != null) {
523 format.initializeIfNeeded(this, model);
524 if (format == format.getLatestVersion()) {
525 latestFormatMap.put(format.getClassName(), format);
526 }
527 }
528 }
529
530 final boolean formatsChanged =
531 newFormats.size() > 0 ||
532 initEvolver.areFormatsChanged();
533 needWrite |= formatsChanged;
534
535 /* For unit testing. */
536 if (expectNoClassChanges && formatsChanged) {
537 throw new IllegalStateException
538 ("Unexpected changes " +
539 " newFormats.size=" + newFormats.size() +
540 " areFormatsChanged=" + initEvolver.areFormatsChanged());
541 }
542
543 readOnly = db.getConfig().getReadOnly();
544
545 /* Write the catalog if anything changed. */
546 if (needWrite && !readOnly) {
547
548
549 /*
550 * Only rename/remove databases if we are going to update
551 * the catalog to reflect those class changes.
552 */
553 initEvolver.renameAndRemoveDatabases(store, txn);
554
555 /*
556 * Note that we use the Data object that was read above,
557 * and the beta version determines whether to delete the
558 * old mutations record.
559 */
560 initData.formatList = formatList;
561 initData.mutations = mutations;
562 writeData(txn, initData);
563 }
564 initModelAndMutations();
565 } finally {
566
567 /*
568 * Fields needed only for the duration of this ctor and which
569 * should be null afterwards.
570 */
571 proxyClassMap = null;
572 initData = null;
573 initEvolver = null;
574 }
575 }
576
577 private void initModelAndMutations() {
578
579 /*
580 * Give the model a reference to the catalog to fully initialize
581 * the model. Only then may we initialize the Converter mutations,
582 * which themselves may call model methods and expect the model to
583 * be fully initialized.
584 */
585 ModelInternal.setCatalog(model, this);
586 for (Converter converter : mutations.getConverters()) {
587 converter.getConversion().initialize(model);
588 }
589 }
590
591 public void getEntityFormats(Collection<Format> entityFormats) {
592 for (Format format : formatMap.values()) {
593 if (format.isEntity()) {
594 entityFormats.add(format);
595 }
596 }
597 }
598
599 private void addProxiedClass(String className, boolean isKnownClass) {
600 ClassMetadata metadata = model.getClassMetadata(className);
601 if (metadata != null) {
602 String proxiedClassName = metadata.getProxiedClassName();
603 if (proxiedClassName != null) {
604
605 /*
606 * If the class is a registered known class, need to check if
607 * registering proxy class is allowed or not. Currently, only
608 * SimpleType is not allowed to register a proxy class.
609 */
610 if (isKnownClass) {
611 try {
612 Class type = resolveClass(proxiedClassName);
613
614 /*
615 * Check if the proxied class is allowed to register a
616 * proxy class. If not, IllegalArgumentException will
617 * be thrown.
618 */
619 if(!SimpleCatalog.allowRegisterProxy(type)) {
620 throw new IllegalArgumentException
621 ("Registering proxy is not allowed for " +
622 proxiedClassName +
623 ", which is a built-in simple type.");
624 }
625 } catch (ClassNotFoundException e) {
626 throw DbCompat.unexpectedState
627 ("Class does not exist: " + proxiedClassName);
628 }
629 }
630 proxyClassMap.put(proxiedClassName, className);
631 }
632 }
633 }
634
635 private void addPredefinedProxies(List<String> knownClasses) {
636 knownClasses.add(CollectionProxy.ArrayListProxy.class.getName());
637 knownClasses.add(CollectionProxy.LinkedListProxy.class.getName());
638 knownClasses.add(CollectionProxy.HashSetProxy.class.getName());
639 knownClasses.add(CollectionProxy.TreeSetProxy.class.getName());
640 knownClasses.add(MapProxy.HashMapProxy.class.getName());
641 knownClasses.add(MapProxy.TreeMapProxy.class.getName());
642 knownClasses.add(MapProxy.LinkedHashMapProxy.class.getName());
643 }
644
645 /**
646 * Returns a map from format to a set of its superclass formats. The
647 * format for simple types, enums and class Object are not included. Only
648 * complex types have superclass formats as defined by
649 * Format.getSuperFormat.
650 */
651 Map<Format, Set<Format>> getSubclassMap() {
652 Map<Format, Set<Format>> subclassMap =
653 new HashMap<Format, Set<Format>>();
654 for (Format format : formatList) {
655 if (format == null || Format.isPredefined(format)) {
656 continue;
657 }
658 Format superFormat = format.getSuperFormat();
659 if (superFormat != null) {
660 Set<Format> subclass = subclassMap.get(superFormat);
661 if (subclass == null) {
662 subclass = new HashSet<Format>();
663 subclassMap.put(superFormat, subclass);
664 }
665 subclass.add(format);
666 }
667 }
668 return subclassMap;
669 }
670
671 /**
672 * Returns the model parameter, default model or stored model.
673 */
674 public EntityModel getResolvedModel() {
675 return model;
676 }
677
678 /**
679 * Increments the reference count for a catalog that is already open.
680 */
681 public void openExisting() {
682 openCount += 1;
683 }
684
685 /**
686 * Returns true if the user opened the store read-only, or we're running in
687 * Replica upgrade mode.
688 */
689 public boolean isReadOnly() {
690 return readOnly;
691 }
692
693 /**
694 * Decrements the reference count and closes the catalog DB when it reaches
695 * zero. Returns true if the database was closed or false if the reference
696 * count is still non-zero and the database was left open.
697 */
698 public boolean close()
699 throws DatabaseException {
700
701 if (openCount == 0) {
702 throw DbCompat.unexpectedState("Catalog is not open");
703 } else {
704 openCount -= 1;
705 if (openCount == 0) {
706 db.close();
707 return true;
708 } else {
709 return false;
710 }
711 }
712 }
713
714 /**
715 * Returns the current merged mutations.
716 */
717 public Mutations getMutations() {
718 return mutations;
719 }
720
721 /**
722 * Convenience method that gets the class for the given class name and
723 * calls createFormat with the class object.
724 */
725 public Format createFormat(String clsName,
726 Map<String, Format> newFormats) {
727 Class type;
728 try {
729 type = resolveClass(clsName);
730 } catch (ClassNotFoundException e) {
731 throw DbCompat.unexpectedState
732 ("Class does not exist: " + clsName);
733 }
734 return createFormat(type, newFormats);
735 }
736
737 /**
738 * If the given class format is not already present in the given map and
739 * a format for this class name does not already exist, creates an
740 * uninitialized format, adds it to the map, and also collects related
741 * formats in the map.
742 */
743 public Format createFormat(Class type, Map<String, Format> newFormats) {
744 /* Return a new or existing format for this class. */
745 String className = type.getName();
746 Format format = getFormatFromMap(type, newFormats);
747 if (format != null) {
748 return format;
749 }
750 format = getFormatFromMap(type, formatMap);
751 if (format != null) {
752 return format;
753 }
754 /* Simple types are predefined. */
755 assert !SimpleCatalog.isSimpleType(type) : className;
756
757 /*
758 * Although metadata is only needed for a complex type, call
759 * getClassMetadata for all types to support checks for illegal
760 * metadata on other types.
761 */
762 ClassMetadata metadata = model.getClassMetadata(className);
763 /* Create format of the appropriate type. */
764 String proxyClassName = null;
765 if (proxyClassMap != null) {
766 proxyClassName = proxyClassMap.get(className);
767 }
768 if (proxyClassName != null) {
769 format = new ProxiedFormat(this, type, proxyClassName);
770 } else if (type.isArray()) {
771 format = type.getComponentType().isPrimitive() ?
772 (new PrimitiveArrayFormat(this, type)) :
773 (new ObjectArrayFormat(this, type));
774 } else if (type.isEnum()) {
775 format = new EnumFormat(this, type);
776 } else if (type.getEnclosingClass() != null &&
777 type.getEnclosingClass().isEnum()) {
778
779 /*
780 * If the type is an anonymous class of an enum class, the format
781 * which represents the enum class will be created. [#18357]
782 */
783 format = new EnumFormat(this, type.getEnclosingClass());
784 } else if (type == Object.class || type.isInterface()) {
785 format = new NonPersistentFormat(this, type);
786 } else {
787 if (metadata == null) {
788 throw new IllegalArgumentException
789 ("Class could not be loaded or is not persistent: " +
790 className);
791 }
792 if (metadata.getCompositeKeyFields() != null &&
793 (metadata.getPrimaryKey() != null ||
794 metadata.getSecondaryKeys() != null)) {
795 throw new IllegalArgumentException
796 ("A composite key class may not have primary or" +
797 " secondary key fields: " + type.getName());
798 }
799
800 /*
801 * Check for inner class before default constructor, to give a
802 * specific error message for each.
803 */
804 if (type.getEnclosingClass() != null &&
805 !Modifier.isStatic(type.getModifiers())) {
806 throw new IllegalArgumentException
807 ("Inner classes not allowed: " + type.getName());
808 }
809 try {
810 type.getDeclaredConstructor();
811 } catch (NoSuchMethodException e) {
812 throw new IllegalArgumentException
813 ("No default constructor: " + type.getName(), e);
814 }
815 if (metadata.getCompositeKeyFields() != null) {
816 format = new CompositeKeyFormat
817 (this, type, metadata,
818 metadata.getCompositeKeyFields());
819 } else {
820 EntityMetadata entityMetadata =
821 model.getEntityMetadata(className);
822 format =
823 new ComplexFormat(this, type, metadata, entityMetadata);
824 }
825 }
826 /* Collect new format along with any related new formats. */
827 newFormats.put(className, format);
828 format.collectRelatedFormats(this, newFormats);
829
830 return format;
831 }
832
833 private Format getFormatFromMap(Class type,
834 Map<String, Format> formats) {
835 Format format = formats.get(type.getName());
836 if (format != null) {
837 return format;
838 } else if (type.getEnclosingClass() != null &&
839 type.getEnclosingClass().isEnum()) {
840
841 /*
842 * If the type is an anonymous class of this enum class, the format
843 * which represents the enum class will be returned. [#18357]
844 */
845 format = formats.get(type.getEnclosingClass().getName());
846 if (format != null) {
847 return format;
848 }
849 }
850 return null;
851 }
852
853 /**
854 * Adds a format and makes it the current format for the class.
855 */
856 private void addFormat(Format format) {
857 addFormat(format, formatList, formatMap);
858 }
859
860 /**
861 * Adds a format to the given the format collections, for use when
862 * dynamically adding formats.
863 */
864 private void addFormat(Format format,
865 List<Format> list,
866 Map<String, Format> map) {
867 format.setId(list.size());
868 list.add(format);
869 map.put(format.getClassName(), format);
870 }
871
872 /**
873 * Installs an existing format when no evolution is needed, i.e, when the
874 * new and old formats are identical.
875 */
876 void useExistingFormat(Format oldFormat) {
877 assert oldFormat.isCurrentVersion();
878 formatMap.put(oldFormat.getClassName(), oldFormat);
879 }
880
881 /**
882 * Returns a set of all persistent (non-simple type) class names.
883 */
884 Set<String> getModelClasses() {
885 Set<String> classes = new HashSet<String>();
886 for (Format format : formatMap.values()) {
887 if (format.isModelClass()) {
888 classes.add(format.getClassName());
889 }
890 }
891 return Collections.unmodifiableSet(classes);
892 }
893
894 /**
895 * Returns all formats as RawTypes.
896 */
897 public List<RawType> getAllRawTypes() {
898 List<RawType> list = new ArrayList<RawType>();
899 for (RawType type : formatList) {
900 if (type != null) {
901 list.add(type);
902 }
903 }
904 return Collections.unmodifiableList(list);
905 }
906
907 /**
908 * When a format is intialized, this method is called to get the version
909 * of the serialized object to be initialized. See Catalog.
910 */
911 public int getInitVersion(Format format, boolean forReader) {
912
913 if (initData == null || initData.formatList == null ||
914 format.getId() >= initData.formatList.size()) {
915
916 /*
917 * For new formats, use the current version. If initData is null,
918 * the Catalog ctor is finished and the format must be new. If the
919 * ctor is in progress, the format is new if its ID is greater than
920 * the ID of all pre-existing formats.
921 */
922 return Catalog.CURRENT_VERSION;
923 } else {
924
925 /*
926 * Get the version of a pre-existing format during execution of the
927 * Catalog ctor. The initData field is non-null, but initEvolver
928 * may be null if the catalog is opened in raw mode.
929 */
930 assert initData != null;
931
932 if (forReader) {
933
934 /*
935 * Get the version of the evolution reader for a pre-existing
936 * format. Use the current version if the format changed
937 * during class evolution, otherwise use the stored version.
938 */
939 return (initEvolver != null &&
940 initEvolver.isFormatChanged(format)) ?
941 Catalog.CURRENT_VERSION : initData.version;
942 } else {
943 /* Always used the stored version for a pre-existing format. */
944 return initData.version;
945 }
946 }
947 }
948
949 public Format getFormat(final int formatId, final boolean expectStored)
950 throws RefreshException {
951
952 if (formatId < 0) {
953 throw DbCompat.unexpectedState
954 ("Format ID " + formatId + " is negative," +
955 " may indicate data corruption.");
956 }
957
958 /**
959 * If we're attempting to read a record containing a format ID that is
960 * greater than the maximum known stored format, then we refresh the
961 * formats from disk, expecting that the stored formats have been
962 * updated by the Master node. Note that format IDs greater than
963 * nStoredFormats may exist in the formatList, if evolution took place
964 * on this Replica in a read-only mode. Such formats are never written
965 * (Replicas do not write) and cannot be used for reading an existing
966 * record. [#16655]
967 *
968 * Do not perform this check if we did not get the format ID from a
969 * stored record (expectStored is false). For example, this would cause
970 * an erroneous RefreshException when this method is called during a
971 * convertRawObject operation, which calls this method to get a fresh
972 * copy of a format that may not be stored. [#18690]
973 */
974 if (expectStored && formatId >= nStoredFormats) {
975 assert store != null;
976 throw new RefreshException(store, this, formatId);
977 }
978
979 Format format = formatList.get(formatId);
980 if (format == null) {
981 throw DbCompat.unexpectedState
982 ("Format ID " + formatId + " has null format," +
983 " may indicate data corruption.");
984 }
985
986 /*
987 * Currently we can't throw DeletedClassException because we should not
988 * do this if we're being called during a Conversion, and we don't have
989 * that state information available.
990 */
991 /*
992 if (format.isDeleted()) {
993 throw new DeletedClassException
994 ("Class " + format.getClassName() +
995 " was deleted with a Deleter muation, format ID " +
996 formatId + '.');
997 }
998 */
999
1000 return format;
1001 }
1002
1003 /**
1004 * Get a format for a given class, creating it if it does not exist.
1005 *
1006 * <p>This method is called for top level entity instances by
1007 * PersistEntityBinding. When a new entity subclass format is added we
1008 * call Store.checkEntitySubclassSecondaries to ensure that all secondary
1009 * databases have been opened, before storing the entity. We do this here
1010 * while not holding a synchronization mutex, not in addNewFormat, to avoid
1011 * deadlocks. checkEntitySubclassSecondaries synchronizes on the Store.
1012 * [#16399]</p>
1013 *
1014 * <p>Historical note: At one time we opened / created the secondary
1015 * databases rather than requiring the user to open them, see [#15247].
1016 * Later we found this to be problematic since a user txn may have locked
1017 * primary records, see [#16399].</p>
1018 */
1019 public Format getFormat(Class cls, boolean checkEntitySubclassIndexes)
1020 throws RefreshException {
1021
1022 Format format = formatMap.get(cls.getName());
1023 if (format == null) {
1024 if (model != null) {
1025 format = addNewFormat(cls);
1026 /* Detect and handle new entity subclass. [#15247] */
1027 if (checkEntitySubclassIndexes && store != null) {
1028 Format entityFormat = format.getEntityFormat();
1029 if (entityFormat != null && entityFormat != format) {
1030 try {
1031 store.checkEntitySubclassSecondaries
1032 (entityFormat.getEntityMetadata(),
1033 cls.getName());
1034 } catch (DatabaseException e) {
1035 throw RuntimeExceptionWrapper.wrapIfNeeded(e);
1036 }
1037 }
1038 }
1039 }
1040 if (format == null) {
1041 throw new IllegalArgumentException
1042 ("Class is not persistent: " + cls.getName());
1043 }
1044 }
1045
1046 return format;
1047 }
1048
1049 public Format getFormat(String className) {
1050 return formatMap.get(className);
1051 }
1052
1053 public Format getLatestVersion(String className) {
1054 return latestFormatMap.get(className);
1055 }
1056
1057 /**
1058 * Returns the name of an entity class to be used to form the database
1059 * name. Normally this is the same as the class name, but in replica
1060 * upgrade mode it may be an earlier version of a renamed class. Returns
1061 * null if there is no stored version of the class. [#16655]
1062 */
1063 public String getDatabaseClassName(final String className) {
1064 final Format format = getStoredFormat(className);
1065 if (format == null) {
1066 return null;
1067 }
1068 return format.getClassName();
1069 }
1070
1071 /**
1072 * Similar to getDatabaseClassName but instead handles an earlier version
1073 * of a renamed key. [#16655]
1074 */
1075 public String getDatabaseKeyName(final String className,
1076 final String keyName) {
1077 final Format format = getStoredFormat(className);
1078 if (format == null) {
1079 return null;
1080 }
1081 return format.getOldKeyName(keyName);
1082 }
1083
1084 private Format getStoredFormat(final String className) {
1085 Format format = getFormat(className);
1086 while (format != null && format.getId() >= nStoredFormats) {
1087 format = format.getPreviousVersion();
1088 }
1089 return format;
1090 }
1091
1092 /**
1093 * Metadata needs refreshing when a Replica with stale metadata is elected
1094 * master, and then a user write operation is attempted. [#16655]
1095 */
1096 void checkWriteInReplicaUpgradeMode()
1097 throws RefreshException {
1098
1099 if (nStoredFormats < formatList.size()) {
1100 throw new RefreshException(store, this, -1 /*formatId*/);
1101 }
1102 }
1103
1104 /**
1105 * For unit testing.
1106 */
1107 boolean isReplicaUpgradeMode() {
1108 return nStoredFormats < formatList.size();
1109 }
1110
1111 /**
1112 * Adds a format for a new class. Returns the format added for the given
1113 * class, or throws an exception if the given class is not persistent.
1114 *
1115 * <p>This method uses a copy-on-write technique to add new formats without
1116 * impacting other threads.</p>
1117 */
1118 private synchronized Format addNewFormat(Class cls)
1119 throws RefreshException {
1120
1121 /*
1122 * After synchronizing, check whether another thread has added the
1123 * format needed. Note that this is not the double-check technique
1124 * because the formatMap field is volatile and is not itself checked
1125 * for null. (The double-check technique is known to be flawed in
1126 * Java.)
1127 */
1128 Format format = getFormatFromMap(cls, formatMap);
1129 if (format != null) {
1130 return format;
1131 }
1132
1133 /* Copy the read-only format collections. */
1134 List<Format> newFormatList = new ArrayList<Format>(formatList);
1135 Map<String, Format> newFormatMap =
1136 new HashMap<String, Format>(formatMap);
1137 Map<String, Format> newLatestFormatMap =
1138 new HashMap<String, Format>(latestFormatMap);
1139
1140 /* Add the new format and all related new formats. */
1141 Map<String, Format> newFormats = new HashMap<String, Format>();
1142 format = createFormat(cls, newFormats);
1143 for (Format newFormat : newFormats.values()) {
1144 addFormat(newFormat, newFormatList, newFormatMap);
1145 }
1146
1147 /*
1148 * Initialize new formats using a read-only catalog because we can't
1149 * update this catalog until after we store it (below).
1150 */
1151 Catalog newFormatCatalog = new ReadOnlyCatalog
1152 (ModelInternal.getClassLoader(model), newFormatList, newFormatMap);
1153 for (Format newFormat : newFormats.values()) {
1154 newFormat.initializeIfNeeded(newFormatCatalog, model);
1155 newLatestFormatMap.put(newFormat.getClassName(), newFormat);
1156 }
1157
1158 /*
1159 * Write the updated catalog using auto-commit, then assign the new
1160 * collections. The database write must occur before the collections
1161 * are used, since a format must be persistent before it can be
1162 * referenced by a data record.
1163 *
1164 * In readOnly mode, which includes Replica upgrade mode, we should not
1165 * attempt to write since we could be elected Master and write stale
1166 * metadata. If ReplicaWriteException occurs then we transition to
1167 * Replica upgrade mode in the same manner as in the init() method.
1168 * This can happen when no schema change is made except for one or more
1169 * new entity classes. The new entity class will not be detected by
1170 * evolution (during init()) but will be detected here if the user
1171 * calls getPrimaryIndex. [#16655]
1172 */
1173 if (!readOnly) {
1174 try {
1175 Data newData = new Data();
1176 newData.formatList = newFormatList;
1177 newData.mutations = mutations;
1178 writeDataCheckStale(newData);
1179 } catch (DatabaseException e) {
1180 throw RuntimeExceptionWrapper.wrapIfNeeded(e);
1181 }
1182 }
1183 formatList = newFormatList;
1184 formatMap = newFormatMap;
1185 latestFormatMap = newLatestFormatMap;
1186
1187 return format;
1188 }
1189
1190 /**
1191 * Used to write the catalog when a format has been changed, for example,
1192 * when Store.evolve has updated a Format's EvolveNeeded property. Uses
1193 * auto-commit.
1194 */
1195 public synchronized void flush(Transaction txn)
1196 throws DatabaseException {
1197
1198 Data newData = new Data();
1199 newData.formatList = formatList;
1200 newData.mutations = mutations;
1201 writeData(txn, newData);
1202 }
1203
1204 /**
1205 * Returns the number of stored formats.
1206 */
1207 int getNFormats() {
1208 return nStoredFormats;
1209 }
1210
1211 /**
1212 * Reads catalog Data, converting old versions as necessary. An empty
1213 * Data object is returned if no catalog data currently exists. Null is
1214 * never returned.
1215 */
1216 private Data readData(Transaction txn)
1217 throws DatabaseException {
1218
1219 Data oldData;
1220 DatabaseEntry key = new DatabaseEntry(DATA_KEY);
1221 DatabaseEntry data = new DatabaseEntry();
1222 OperationStatus status = db.get(txn, key, data, null);
1223 if (status == OperationStatus.SUCCESS) {
1224 ByteArrayInputStream bais = new ByteArrayInputStream
1225 (data.getData(), data.getOffset(), data.getSize());
1226 try {
1227 ObjectInputStream ois = new ObjectInputStream(bais);
1228 Object object = ois.readObject();
1229 assert ois.available() == 0;
1230 if (object instanceof Data) {
1231 oldData = (Data) object;
1232 } else {
1233 if (!(object instanceof List)) {
1234 throw DbCompat.unexpectedState
1235 (object.getClass().getName());
1236 }
1237 oldData = new Data();
1238 oldData.formatList = (List) object;
1239 oldData.version = BETA_VERSION;
1240 }
1241 return oldData;
1242 } catch (ClassNotFoundException e) {
1243 throw DbCompat.unexpectedException(e);
1244 } catch (IOException e) {
1245 throw DbCompat.unexpectedException(e);
1246 }
1247 } else {
1248 oldData = new Data();
1249 oldData.version = Catalog.CURRENT_VERSION;
1250 }
1251 return oldData;
1252 }
1253
1254 /**
1255 * Metadata needs refreshing when a Replica with stale metadata is elected
1256 * master, and then a user write operation is attempted that also requires
1257 * a metadata update. [#16655]
1258 */
1259 boolean isMetadataStale(Transaction txn)
1260 throws DatabaseException {
1261
1262 Data oldData = readData(txn);
1263
1264 return (oldData.formatList != null &&
1265 oldData.formatList.size() > nStoredFormats);
1266 }
1267
1268 /**
1269 * Writes catalog Data after checking for stale metadata.
1270 */
1271 private void writeDataCheckStale(Data newData)
1272 throws DatabaseException, RefreshException {
1273
1274 for (int i = 0;; i += 1) {
1275 Transaction txn = null;
1276 if (transactional && DbCompat.getThreadTransaction(env) == null) {
1277 txn =
1278 env.beginTransaction(null, store.getAutoCommitTxnConfig());
1279 }
1280 boolean success = false;
1281 try {
1282 if (isMetadataStale(txn)) {
1283 throw new RefreshException(store, this, -1 /*formatId*/);
1284 }
1285 writeData(txn, newData);
1286 success = true;
1287 return;
1288 } catch (DeadlockException e) {
1289
1290 /*
1291 * A lock conflict should not occur because writes to the
1292 * catalog DB are in synchronized methods. However, because we
1293 * read-modify-update the catalog record,
1294 * LockPreemptedException must be handled in a replicated JE
1295 * environment. Since LockPreemptedException is a
1296 * LockConfictException, it is simplest to retry when any
1297 * LockConfictException occurs.
1298 */
1299 if (i >= MAX_TXN_RETRIES) {
1300 throw e;
1301 }
1302 continue;
1303 } finally {
1304
1305 /*
1306 * If the catalog is read-only we abort rather than commit,
1307 * because a ReplicaWriteException may have occurred.
1308 * ReplicaWriteException invalidates the transaction, and there
1309 * are no writes to commit anyway. [#16655]
1310 */
1311 if (txn != null) {
1312 if (success && !isReadOnly()) {
1313 txn.commit();
1314 } else {
1315 txn.abort();
1316 }
1317 }
1318 }
1319 }
1320 }
1321
1322 /**
1323 * Writes catalog Data. Does not check for stale metadata.
1324 */
1325 private void writeData(Transaction txn, Data newData)
1326 throws DatabaseException {
1327
1328 /* Catalog data is written in the current version. */
1329 boolean wasBetaVersion = (newData.version == BETA_VERSION);
1330 newData.version = CURRENT_VERSION;
1331
1332 ByteArrayOutputStream baos = new ByteArrayOutputStream();
1333 try {
1334 ObjectOutputStream oos = new ObjectOutputStream(baos);
1335 oos.writeObject(newData);
1336 } catch (IOException e) {
1337 throw DbCompat.unexpectedException(e);
1338 }
1339 DatabaseEntry key = new DatabaseEntry(DATA_KEY);
1340 DatabaseEntry data = new DatabaseEntry(baos.toByteArray());
1341 db.put(txn, key, data);
1342
1343 /*
1344 * Delete the unused beta mutations record if we read the beta version
1345 * record earlier.
1346 */
1347 if (wasBetaVersion) {
1348 key.setData(BETA_MUTATIONS_KEY);
1349 db.delete(txn, key);
1350 }
1351
1352 nStoredFormats = newData.formatList.size();
1353 }
1354
1355 public boolean isRawAccess() {
1356 return rawAccess;
1357 }
1358
1359 public Object convertRawObject(RawObject o, IdentityHashMap converted)
1360 throws RefreshException {
1361
1362 Format format = (Format) o.getType();
1363 if (this == format.getCatalog()) {
1364 /* Ensure a fresh format is used, in case of Replica refresh. */
1365 format = getFormat(format.getId(), false /*expectStored*/);
1366 } else {
1367
1368 /*
1369 * Use the corresponding format in this catalog when the external
1370 * raw object was created using a different catalog. Create the
1371 * format if it does not already exist, for example, when this
1372 * store is empty. [#16253].
1373 */
1374 String clsName = format.getClassName();
1375 Class cls;
1376 try {
1377 cls = resolveClass(clsName);
1378 format = getFormat(cls, true /*checkEntitySubclassIndexes*/);
1379 } catch (ClassNotFoundException e) {
1380 format = null;
1381 }
1382 if (format == null) {
1383 throw new IllegalArgumentException
1384 ("External raw type not found: " + clsName);
1385 }
1386 }
1387 Format proxiedFormat = format.getProxiedFormat();
1388 if (proxiedFormat != null) {
1389 format = proxiedFormat;
1390 }
1391 if (converted == null) {
1392 converted = new IdentityHashMap();
1393 }
1394 return format.convertRawObject(this, false, o, converted);
1395 }
1396
1397 public Class resolveClass(String clsName)
1398 throws ClassNotFoundException {
1399
1400 return SimpleCatalog.resolveClass
1401 (clsName, ModelInternal.getClassLoader(model));
1402 }
1403
1404 public Class resolveKeyClass(String clsName) {
1405 return SimpleCatalog.resolveKeyClass
1406 (clsName, ModelInternal.getClassLoader(model));
1407 }
1408 }